title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to merge multiple files into a new file using Python?
To merge multiple files in a new file, you can simply read files and write them to a new file using loops. filenames = ['file1.txt', 'file2.txt', 'file3.txt'] with open('output_file', 'w') as outfile: for fname in filenames: with open(fname) as infile: outfile.write(infile.read()) If you have very big files, instead of writing them at once, you could write them line by line. filenames = ['file1.txt', 'file2.txt', 'file3.txt'] with open('output_file', 'w') as outfile: for fname in filenames: with open(fname) as infile: for line in infile: outfile.write(line)
[ { "code": null, "e": 1294, "s": 1187, "text": "To merge multiple files in a new file, you can simply read files and write them to a new file using loops." }, { "code": null, "e": 1493, "s": 1294, "text": "filenames = ['file1.txt', 'file2.txt', 'file3.txt']\nwith open('output_file', 'w') as outfile:\n for fname in filenames:\n with open(fname) as infile:\n outfile.write(infile.read())" }, { "code": null, "e": 1589, "s": 1493, "text": "If you have very big files, instead of writing them at once, you could write them line by line." }, { "code": null, "e": 1815, "s": 1589, "text": "filenames = ['file1.txt', 'file2.txt', 'file3.txt']\nwith open('output_file', 'w') as outfile:\n for fname in filenames:\n with open(fname) as infile:\n for line in infile:\n outfile.write(line)" } ]
How to Customize Option Menu of Toolbar in Android?
14 Feb, 2021 In this article, we will see how to add icons and change background color in the options menu of the toolbar. Option menu is a collection of menu items of an activity. Android Option Menus are the primary menus of the activity. They can be used for settings, search, delete items, etc. We will first create vector assets for the icon. Then we will set the icon in the toolbar items. Similarly, for the background, we will first create a custom style for the toolbar. Then we will set the theme in the toolbar. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Implement Option Menu To create option menu of an activity in Android Studio refer to How to implement Options Menu in Android. Step 3: Add Vector Assets Right Click on the drawable folder and go to the new vector asset. Search from many vector icons and create one. You can also add an image from the outside but with the right dimension. Step 4: Define Colors It is always better to pre-define strings and colors instead of hard coding them hence we will define the colors. Open the colors.xml file by navigating to the app -> res -> values -> colors.xml. Create a color tag inside the resources tag with a name and set a color with its hex code. Add the below lines inside the colors.xml file. XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="green">#0F9D58</color></resources> Step 5: Create Custom Style We need to create a new style with parent=”ThemeOverlay.AppCompat.Light” as the parent theme. Below is the code for style. XML <resources> <style name="MyToolbarStyle" parent="ThemeOverlay.AppCompat.Light"> <item name="android:colorBackground">@color/green</item> <item name="android:textColor">@color/black</item> </style></resources> Step 6: Set Style in Toolbar In the toolbar tag set the style in the popupTheme attribute. Look at the code below for reference. 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:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.appcompat.widget.Toolbar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/toolbar" android:background="@color/black" app:popupTheme="@style/MyToolbarStyle" app:title="GFG" /> </RelativeLayout> Step 7: Add the Icons to the Items Go to the menu.xml file where the items are created Set the main item tag’s showAsAction attribute to always Set the icon in the sub-items tag using the icon attribute 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/overflowMenu" android:icon="@drawable/ic_baseline_more_vert_24" android:title="" app:showAsAction="always"> <menu> <item android:icon="@drawable/ic_baseline_settings_24" android:title="Setting" /> <item android:icon="@drawable/ic_baseline_login_24" android:title="Logout" /> </menu> </item></menu> android Technical Scripter 2020 Android Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Android SDK and it's Components Broadcast Receiver in Android With Example Navigation Drawer in Android How to Create and Add Data to SQLite Database in Android? Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? How to Update Gradle in Android Studio? Content Providers in Android with Example
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Feb, 2021" }, { "code": null, "e": 539, "s": 28, "text": "In this article, we will see how to add icons and change background color in the options menu of the toolbar. Option menu is a collection of menu items of an activity. Android Option Menus are the primary menus of the activity. They can be used for settings, search, delete items, etc. We will first create vector assets for the icon. Then we will set the icon in the toolbar items. Similarly, for the background, we will first create a custom style for the toolbar. Then we will set the theme in the toolbar. " }, { "code": null, "e": 568, "s": 539, "text": "Step 1: Create a New Project" }, { "code": null, "e": 680, "s": 568, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. " }, { "code": null, "e": 710, "s": 680, "text": "Step 2: Implement Option Menu" }, { "code": null, "e": 816, "s": 710, "text": "To create option menu of an activity in Android Studio refer to How to implement Options Menu in Android." }, { "code": null, "e": 842, "s": 816, "text": "Step 3: Add Vector Assets" }, { "code": null, "e": 1028, "s": 842, "text": "Right Click on the drawable folder and go to the new vector asset. Search from many vector icons and create one. You can also add an image from the outside but with the right dimension." }, { "code": null, "e": 1050, "s": 1028, "text": "Step 4: Define Colors" }, { "code": null, "e": 1164, "s": 1050, "text": "It is always better to pre-define strings and colors instead of hard coding them hence we will define the colors." }, { "code": null, "e": 1246, "s": 1164, "text": "Open the colors.xml file by navigating to the app -> res -> values -> colors.xml." }, { "code": null, "e": 1337, "s": 1246, "text": "Create a color tag inside the resources tag with a name and set a color with its hex code." }, { "code": null, "e": 1385, "s": 1337, "text": "Add the below lines inside the colors.xml file." }, { "code": null, "e": 1389, "s": 1385, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"black\">#FF000000</color> <color name=\"white\">#FFFFFFFF</color> <color name=\"green\">#0F9D58</color></resources>", "e": 1572, "s": 1389, "text": null }, { "code": null, "e": 1600, "s": 1572, "text": "Step 5: Create Custom Style" }, { "code": null, "e": 1723, "s": 1600, "text": "We need to create a new style with parent=”ThemeOverlay.AppCompat.Light” as the parent theme. Below is the code for style." }, { "code": null, "e": 1727, "s": 1723, "text": "XML" }, { "code": "<resources> <style name=\"MyToolbarStyle\" parent=\"ThemeOverlay.AppCompat.Light\"> <item name=\"android:colorBackground\">@color/green</item> <item name=\"android:textColor\">@color/black</item> </style></resources>", "e": 1956, "s": 1727, "text": null }, { "code": null, "e": 1985, "s": 1956, "text": "Step 6: Set Style in Toolbar" }, { "code": null, "e": 2085, "s": 1985, "text": "In the toolbar tag set the style in the popupTheme attribute. Look at the code below for reference." }, { "code": null, "e": 2089, "s": 2085, "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:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <androidx.appcompat.widget.Toolbar android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/toolbar\" android:background=\"@color/black\" app:popupTheme=\"@style/MyToolbarStyle\" app:title=\"GFG\" /> </RelativeLayout>", "e": 2716, "s": 2089, "text": null }, { "code": null, "e": 2751, "s": 2716, "text": "Step 7: Add the Icons to the Items" }, { "code": null, "e": 2803, "s": 2751, "text": "Go to the menu.xml file where the items are created" }, { "code": null, "e": 2860, "s": 2803, "text": "Set the main item tag’s showAsAction attribute to always" }, { "code": null, "e": 2919, "s": 2860, "text": "Set the icon in the sub-items tag using the icon attribute" }, { "code": null, "e": 2923, "s": 2919, "text": "XML" }, { "code": "<?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/overflowMenu\" android:icon=\"@drawable/ic_baseline_more_vert_24\" android:title=\"\" app:showAsAction=\"always\"> <menu> <item android:icon=\"@drawable/ic_baseline_settings_24\" android:title=\"Setting\" /> <item android:icon=\"@drawable/ic_baseline_login_24\" android:title=\"Logout\" /> </menu> </item></menu>", "e": 3569, "s": 2923, "text": null }, { "code": null, "e": 3577, "s": 3569, "text": "android" }, { "code": null, "e": 3601, "s": 3577, "text": "Technical Scripter 2020" }, { "code": null, "e": 3609, "s": 3601, "text": "Android" }, { "code": null, "e": 3628, "s": 3609, "text": "Technical Scripter" }, { "code": null, "e": 3636, "s": 3628, "text": "Android" }, { "code": null, "e": 3734, "s": 3636, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3803, "s": 3734, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3834, "s": 3803, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 3866, "s": 3834, "text": "Android SDK and it's Components" }, { "code": null, "e": 3909, "s": 3866, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 3938, "s": 3909, "text": "Navigation Drawer in Android" }, { "code": null, "e": 3996, "s": 3938, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 4035, "s": 3996, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 4084, "s": 4035, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 4124, "s": 4084, "text": "How to Update Gradle in Android Studio?" } ]
Hoare’s vs Lomuto partition scheme in QuickSort
09 Jun, 2022 We have discussed the implementation of QuickSort using Lomuto partition scheme. Lomuto’s partition scheme is easy to implement as compared to Hoare scheme. This has inferior performance to Hoare’s QuickSort. Lomuto’s Partition Scheme: This algorithm works by assuming the pivot element as the last element. If any other element is given as a pivot element then swap it first with the last element. Now initialize two variables i as low and j also low, iterate over the array and increment i when arr[j] <= pivot and swap arr[i] with arr[j] otherwise increment only i. After coming out from the loop swap arr[i] with arr[hi]. This i stores the pivot element. partition(arr[], lo, hi) pivot = arr[hi] i = lo // place for swapping for j := lo to hi – 1 do if arr[j] <= pivot then i = i + 1 swap arr[i] with arr[j] swap arr[i] with arr[hi] return i Refer QuickSort for details of this partitioning scheme. Below are implementations of this approach:- C++ Java Python3 C# Javascript /* C++ implementation QuickSort using Lomuto's partition Scheme.*/#include<bits/stdc++.h>using namespace std; /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */int partition(int arr[], int low, int high){ int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // increment index of smaller element swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return (i + 1);} /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */void quickSort(int arr[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n");} // Driver program to test above functionsint main(){ int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr)/sizeof(arr[0]); quickSort(arr, 0, n-1); printf("Sorted array: \n"); printArray(arr, n); return 0;} // Java implementation QuickSort// using Lomuto's partition Schemeimport java.io.*; class GFG{static void Swap(int[] array, int position1, int position2){ // Swaps elements in an array // Copy the first position's element int temp = array[position1]; // Assign to the second element array[position1] = array[position2]; // Assign to the first element array[position2] = temp;} /* This function takes last element aspivot, places the pivot element at itscorrect position in sorted array, andplaces all smaller (smaller than pivot)to left of pivot and all greater elementsto right of pivot */static int partition(int []arr, int low, int high){ int pivot = arr[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high- 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // increment index of // smaller element Swap(arr, i, j); } } Swap(arr, i + 1, high); return (i + 1);} /* The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */static void quickSort(int []arr, int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */static void printArray(int []arr, int size){ int i; for (i = 0; i < size; i++) System.out.print(" " + arr[i]); System.out.println();} // Driver Codestatic public void main (String[] args){ int []arr = {10, 7, 8, 9, 1, 5}; int n = arr.length; quickSort(arr, 0, n-1); System.out.println("Sorted array: "); printArray(arr, n);}} // This code is contributed by vt_m. ''' Python3 implementation QuickSort using Lomuto's partitionScheme.''' ''' This function takes last element as pivot, placesthe pivot element at its correct position in sorted array, and places all smaller (smaller than pivot)to left of pivot and all greater elements to rightof pivot '''def partition(arr, low, high): # pivot pivot = arr[high] # Index of smaller element i = (low - 1) for j in range(low, high): # If current element is smaller than or # equal to pivot if (arr[j] <= pivot): # increment index of smaller element i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return (i + 1) ''' The main function that implements QuickSortarr --> Array to be sorted,low --> Starting index,high --> Ending index '''def quickSort(arr, low, high): if (low < high): ''' pi is partitioning index, arr[p] is now at right place ''' pi = partition(arr, low, high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi - 1) quickSort(arr, pi + 1, high) ''' Function to print an array '''def printArray(arr, size): for i in range(size): print(arr[i], end = " ") print() # Driver code arr = [10, 7, 8, 9, 1, 5]n = len(arr)quickSort(arr, 0, n - 1)print("Sorted array:")printArray(arr, n) # This code is contributed by SHUBHAMSINGH10 // C# implementation QuickSort// using Lomuto's partition Schemeusing System; class GFG{static void Swap(int[] array, int position1, int position2){ // Swaps elements in an array // Copy the first position's element int temp = array[position1]; // Assign to the second element array[position1] = array[position2]; // Assign to the first element array[position2] = temp;} /* This function takes last element aspivot, places the pivot element at itscorrect position in sorted array, andplaces all smaller (smaller than pivot)to left of pivot and all greater elementsto right of pivot */static int partition(int []arr, int low, int high){ int pivot = arr[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high- 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // increment index of // smaller element Swap(arr, i, j); } } Swap(arr, i + 1, high); return (i + 1);} /* The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */static void quickSort(int []arr, int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */static void printArray(int []arr, int size){ int i; for (i = 0; i < size; i++) Console.Write(" " + arr[i]); Console.WriteLine();} // Driver Codestatic public void Main(){ int []arr = {10, 7, 8, 9, 1, 5}; int n = arr.Length; quickSort(arr, 0, n-1); Console.WriteLine("Sorted array: "); printArray(arr, n);}} // This code is contributed by vt_m. <script> // JavaScript implementation QuickSort// using Lomuto's partition Scheme function Swap(array, position1, position2){ // Swaps elements in an array // Copy the first position's element let temp = array[position1]; // Assign to the second element array[position1] = array[position2]; // Assign to the first element array[position2] = temp;} /* This function takes last element aspivot, places the pivot element at itscorrect position in sorted array, andplaces all smaller (smaller than pivot)to left of pivot and all greater elementsto right of pivot */function partition(arr, low, high){ let pivot = arr[high]; // Index of smaller element let i = (low - 1); for (let j = low; j <= high- 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // increment index of // smaller element Swap(arr, i, j); } } Swap(arr, i + 1, high); return (i + 1);} /* The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */function quickSort(arr, low, high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ let pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */function printArray(arr, size){ let i; for (i = 0; i < size; i++) document.write(" " + arr[i]); document.write("<br/>");} // Driver Code let arr = [10, 7, 8, 9, 1, 5]; let n = arr.length; quickSort(arr, 0, n-1); document.write("Sorted array: "); printArray(arr, n); // This code is contributed by chinmoy1997pal.</script> Sorted array: 1 5 7 8 9 10 Hoare’s Partition Scheme: Hoare’s Partition Scheme works by initializing two indexes that start at two ends, the two indexes move toward each other until an inversion is (A smaller value on the left side and greater value on the right side) found. When an inversion is found, two values are swapped and the process is repeated. Algorithm: partition(arr[], lo, hi) pivot = arr[lo] i = lo - 1 // Initialize left index j = hi + 1 // Initialize right index // Find a value in left side greater // than pivot do i = i + 1 while arr[i] < pivot // Find a value in right side smaller // than pivot do j--; while (arr[j] > pivot); if i >= j then return j swap arr[i] with arr[j] Below are implementations of this approach:- C++ Java Python3 C# Javascript /* C++ implementation of QuickSort using Hoare's partition scheme. */#include <bits/stdc++.h>using namespace std; /* This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side*/int partition(int arr[], int low, int high){ int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater than // or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller than // or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; swap(arr[i], arr[j]); }} /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */void quickSort(int arr[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); }} /* Function to print an array */void printArray(int arr[], int n){ for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Driver Codeint main(){ int arr[] = { 10, 7, 8, 9, 1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf("Sorted array: \n"); printArray(arr, n); return 0;} // Java implementation of QuickSort// using Hoare's partition schemeimport java.io.*; class GFG { /* This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side*/ static int partition(int[] arr, int low, int high) { int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater // than or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller // than or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // swap(arr[i], arr[j]); } } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void quickSort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); } } /* Function to print an array */ static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) System.out.print(" " + arr[i]); System.out.println(); } // Driver Code static public void main(String[] args) { int[] arr = { 10, 7, 8, 9, 1, 5 }; int n = arr.length; quickSort(arr, 0, n - 1); System.out.println("Sorted array: "); printArray(arr, n); }} // This code is contributed by vt_m. ''' Python implementation of QuickSort using Hoare'spartition scheme. ''' ''' This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side ''' def partition(arr, low, high): pivot = arr[low] i = low - 1 j = high + 1 while (True): # Find leftmost element greater than # or equal to pivot i += 1 while (arr[i] < pivot): i += 1 # Find rightmost element smaller than # or equal to pivot j -= 1 while (arr[j] > pivot): j -= 1 # If two pointers met. if (i >= j): return j arr[i], arr[j] = arr[j], arr[i] ''' The main function that implements QuickSortarr --> Array to be sorted,low --> Starting index,high --> Ending index ''' def quickSort(arr, low, high): ''' pi is partitioning index, arr[p] is now at right place ''' if (low < high): pi = partition(arr, low, high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi) quickSort(arr, pi + 1, high) ''' Function to print an array ''' def printArray(arr, n): for i in range(n): print(arr[i], end=" ") print() # Driver codearr = [10, 7, 8, 9, 1, 5]n = len(arr)quickSort(arr, 0, n - 1)print("Sorted array:")printArray(arr, n) # This code is contributed by shubhamsingh10 // C# implementation of QuickSort// using Hoare's partition schemeusing System; class GFG { /* This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side*/ static int partition(int[] arr, int low, int high) { int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater // than or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller // than or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // swap(arr[i], arr[j]); } } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void quickSort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); } } /* Function to print an array */ static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(" " + arr[i]); Console.WriteLine(); } // Driver Code static public void Main() { int[] arr = { 10, 7, 8, 9, 1, 5 }; int n = arr.Length; quickSort(arr, 0, n - 1); Console.WriteLine("Sorted array: "); printArray(arr, n); }} // This code is contributed by vt_m. <script> // Javascript implementation of QuickSort // using Hoare's partition scheme /* This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side*/ function partition(arr, low, high) { let pivot = arr[low]; let i = low - 1, j = high + 1; while (true) { // Find leftmost element greater // than or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller // than or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // swap(arr[i], arr[j]); } } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ function quickSort(arr, low, high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ let pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); } } /* Function to print an array */ function printArray(arr, n) { for (let i = 0; i < n; i++) document.write(" " + arr[i]); document.write("</br>"); } let arr = [ 10, 7, 8, 9, 1, 5 ]; let n = arr.length; quickSort(arr, 0, n - 1); document.write("Sorted array: " + "</br>"); printArray(arr, n); </script> Sorted array: 1 5 7 8 9 10 Note : If we change Hoare’s partition to pick the last element as pivot, then the Hoare’s partition may cause QuickSort to go into in an infinite recursion. For example, {10, 5, 6, 20} and pivot is arr[high], then returned index will always be high and call to same QuickSort will be made. To handle a random pivot, we can always swap that random element with the first element and simply follow the above algorithm.Comparison: Hoare’s scheme is more efficient than Lomuto’s partition scheme because it does three times fewer swaps on average, and it creates efficient partitions even when all values are equal.Like Lomuto’s partition scheme, Hoare partitioning also causes Quick sort to degrade to O(n^2) when the input array is already sorted, it also doesn’t produce a stable sort.Note that in this scheme, the pivot’s final location is not necessarily at the index that was returned, and the next two segments that the main algorithm recurs on are (lo..p) and (p+1..hi) as opposed to (lo..p-1) and (p+1..hi) as in Lomuto’s scheme.Both Hoare’s Partition, as well as Lomuto’s partition, are unstable. Hoare’s scheme is more efficient than Lomuto’s partition scheme because it does three times fewer swaps on average, and it creates efficient partitions even when all values are equal. Like Lomuto’s partition scheme, Hoare partitioning also causes Quick sort to degrade to O(n^2) when the input array is already sorted, it also doesn’t produce a stable sort. Note that in this scheme, the pivot’s final location is not necessarily at the index that was returned, and the next two segments that the main algorithm recurs on are (lo..p) and (p+1..hi) as opposed to (lo..p-1) and (p+1..hi) as in Lomuto’s scheme. Both Hoare’s Partition, as well as Lomuto’s partition, are unstable. Source : https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_schemeThis article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m SHUBHAMSINGH10 akuma36 chinmoy1997pal aodennison mukesh07 soubhikmitra98 geeky01adarsh surinderdawra388 simmytarika5 samarthpandya134 abhishant24952 Quick Sort Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2022" }, { "code": null, "e": 263, "s": 54, "text": "We have discussed the implementation of QuickSort using Lomuto partition scheme. Lomuto’s partition scheme is easy to implement as compared to Hoare scheme. This has inferior performance to Hoare’s QuickSort." }, { "code": null, "e": 290, "s": 263, "text": "Lomuto’s Partition Scheme:" }, { "code": null, "e": 714, "s": 290, "text": "This algorithm works by assuming the pivot element as the last element. If any other element is given as a pivot element then swap it first with the last element. Now initialize two variables i as low and j also low, iterate over the array and increment i when arr[j] <= pivot and swap arr[i] with arr[j] otherwise increment only i. After coming out from the loop swap arr[i] with arr[hi]. This i stores the pivot element." }, { "code": null, "e": 959, "s": 714, "text": "partition(arr[], lo, hi) \n pivot = arr[hi]\n i = lo // place for swapping\n for j := lo to hi – 1 do\n if arr[j] <= pivot then\n i = i + 1 \n swap arr[i] with arr[j]\n swap arr[i] with arr[hi]\n return i" }, { "code": null, "e": 1061, "s": 959, "text": "Refer QuickSort for details of this partitioning scheme. Below are implementations of this approach:-" }, { "code": null, "e": 1065, "s": 1061, "text": "C++" }, { "code": null, "e": 1070, "s": 1065, "text": "Java" }, { "code": null, "e": 1078, "s": 1070, "text": "Python3" }, { "code": null, "e": 1081, "s": 1078, "text": "C#" }, { "code": null, "e": 1092, "s": 1081, "text": "Javascript" }, { "code": "/* C++ implementation QuickSort using Lomuto's partition Scheme.*/#include<bits/stdc++.h>using namespace std; /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */int partition(int arr[], int low, int high){ int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // increment index of smaller element swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return (i + 1);} /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */void quickSort(int arr[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver program to test above functionsint main(){ int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr)/sizeof(arr[0]); quickSort(arr, 0, n-1); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}", "e": 2738, "s": 1092, "text": null }, { "code": "// Java implementation QuickSort// using Lomuto's partition Schemeimport java.io.*; class GFG{static void Swap(int[] array, int position1, int position2){ // Swaps elements in an array // Copy the first position's element int temp = array[position1]; // Assign to the second element array[position1] = array[position2]; // Assign to the first element array[position2] = temp;} /* This function takes last element aspivot, places the pivot element at itscorrect position in sorted array, andplaces all smaller (smaller than pivot)to left of pivot and all greater elementsto right of pivot */static int partition(int []arr, int low, int high){ int pivot = arr[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high- 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // increment index of // smaller element Swap(arr, i, j); } } Swap(arr, i + 1, high); return (i + 1);} /* The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */static void quickSort(int []arr, int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */static void printArray(int []arr, int size){ int i; for (i = 0; i < size; i++) System.out.print(\" \" + arr[i]); System.out.println();} // Driver Codestatic public void main (String[] args){ int []arr = {10, 7, 8, 9, 1, 5}; int n = arr.length; quickSort(arr, 0, n-1); System.out.println(\"Sorted array: \"); printArray(arr, n);}} // This code is contributed by vt_m.", "e": 4816, "s": 2738, "text": null }, { "code": "''' Python3 implementation QuickSort using Lomuto's partitionScheme.''' ''' This function takes last element as pivot, placesthe pivot element at its correct position in sorted array, and places all smaller (smaller than pivot)to left of pivot and all greater elements to rightof pivot '''def partition(arr, low, high): # pivot pivot = arr[high] # Index of smaller element i = (low - 1) for j in range(low, high): # If current element is smaller than or # equal to pivot if (arr[j] <= pivot): # increment index of smaller element i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return (i + 1) ''' The main function that implements QuickSortarr --> Array to be sorted,low --> Starting index,high --> Ending index '''def quickSort(arr, low, high): if (low < high): ''' pi is partitioning index, arr[p] is now at right place ''' pi = partition(arr, low, high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi - 1) quickSort(arr, pi + 1, high) ''' Function to print an array '''def printArray(arr, size): for i in range(size): print(arr[i], end = \" \") print() # Driver code arr = [10, 7, 8, 9, 1, 5]n = len(arr)quickSort(arr, 0, n - 1)print(\"Sorted array:\")printArray(arr, n) # This code is contributed by SHUBHAMSINGH10", "e": 6328, "s": 4816, "text": null }, { "code": "// C# implementation QuickSort// using Lomuto's partition Schemeusing System; class GFG{static void Swap(int[] array, int position1, int position2){ // Swaps elements in an array // Copy the first position's element int temp = array[position1]; // Assign to the second element array[position1] = array[position2]; // Assign to the first element array[position2] = temp;} /* This function takes last element aspivot, places the pivot element at itscorrect position in sorted array, andplaces all smaller (smaller than pivot)to left of pivot and all greater elementsto right of pivot */static int partition(int []arr, int low, int high){ int pivot = arr[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high- 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // increment index of // smaller element Swap(arr, i, j); } } Swap(arr, i + 1, high); return (i + 1);} /* The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */static void quickSort(int []arr, int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */static void printArray(int []arr, int size){ int i; for (i = 0; i < size; i++) Console.Write(\" \" + arr[i]); Console.WriteLine();} // Driver Codestatic public void Main(){ int []arr = {10, 7, 8, 9, 1, 5}; int n = arr.Length; quickSort(arr, 0, n-1); Console.WriteLine(\"Sorted array: \"); printArray(arr, n);}} // This code is contributed by vt_m.", "e": 8381, "s": 6328, "text": null }, { "code": "<script> // JavaScript implementation QuickSort// using Lomuto's partition Scheme function Swap(array, position1, position2){ // Swaps elements in an array // Copy the first position's element let temp = array[position1]; // Assign to the second element array[position1] = array[position2]; // Assign to the first element array[position2] = temp;} /* This function takes last element aspivot, places the pivot element at itscorrect position in sorted array, andplaces all smaller (smaller than pivot)to left of pivot and all greater elementsto right of pivot */function partition(arr, low, high){ let pivot = arr[high]; // Index of smaller element let i = (low - 1); for (let j = low; j <= high- 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { i++; // increment index of // smaller element Swap(arr, i, j); } } Swap(arr, i + 1, high); return (i + 1);} /* The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */function quickSort(arr, low, high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ let pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */function printArray(arr, size){ let i; for (i = 0; i < size; i++) document.write(\" \" + arr[i]); document.write(\"<br/>\");} // Driver Code let arr = [10, 7, 8, 9, 1, 5]; let n = arr.length; quickSort(arr, 0, n-1); document.write(\"Sorted array: \"); printArray(arr, n); // This code is contributed by chinmoy1997pal.</script>", "e": 10272, "s": 8381, "text": null }, { "code": null, "e": 10301, "s": 10272, "text": "Sorted array: \n1 5 7 8 9 10 " }, { "code": null, "e": 10327, "s": 10301, "text": "Hoare’s Partition Scheme:" }, { "code": null, "e": 10629, "s": 10327, "text": "Hoare’s Partition Scheme works by initializing two indexes that start at two ends, the two indexes move toward each other until an inversion is (A smaller value on the left side and greater value on the right side) found. When an inversion is found, two values are swapped and the process is repeated." }, { "code": null, "e": 10640, "s": 10629, "text": "Algorithm:" }, { "code": null, "e": 11035, "s": 10640, "text": "partition(arr[], lo, hi)\n pivot = arr[lo]\n i = lo - 1 // Initialize left index\n j = hi + 1 // Initialize right index\n\n // Find a value in left side greater\n // than pivot\n do\n i = i + 1\n while arr[i] < pivot\n\n // Find a value in right side smaller\n // than pivot\n do\n j--;\n while (arr[j] > pivot);\n\n if i >= j then \n return j\n\n swap arr[i] with arr[j]" }, { "code": null, "e": 11081, "s": 11035, "text": "Below are implementations of this approach:- " }, { "code": null, "e": 11085, "s": 11081, "text": "C++" }, { "code": null, "e": 11090, "s": 11085, "text": "Java" }, { "code": null, "e": 11098, "s": 11090, "text": "Python3" }, { "code": null, "e": 11101, "s": 11098, "text": "C#" }, { "code": null, "e": 11112, "s": 11101, "text": "Javascript" }, { "code": "/* C++ implementation of QuickSort using Hoare's partition scheme. */#include <bits/stdc++.h>using namespace std; /* This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side*/int partition(int arr[], int low, int high){ int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater than // or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller than // or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; swap(arr[i], arr[j]); }} /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */void quickSort(int arr[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); }} /* Function to print an array */void printArray(int arr[], int n){ for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver Codeint main(){ int arr[] = { 10, 7, 8, 9, 1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}", "e": 12800, "s": 11112, "text": null }, { "code": "// Java implementation of QuickSort// using Hoare's partition schemeimport java.io.*; class GFG { /* This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side*/ static int partition(int[] arr, int low, int high) { int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater // than or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller // than or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // swap(arr[i], arr[j]); } } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void quickSort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); } } /* Function to print an array */ static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) System.out.print(\" \" + arr[i]); System.out.println(); } // Driver Code static public void main(String[] args) { int[] arr = { 10, 7, 8, 9, 1, 5 }; int n = arr.length; quickSort(arr, 0, n - 1); System.out.println(\"Sorted array: \"); printArray(arr, n); }} // This code is contributed by vt_m.", "e": 14867, "s": 12800, "text": null }, { "code": "''' Python implementation of QuickSort using Hoare'spartition scheme. ''' ''' This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side ''' def partition(arr, low, high): pivot = arr[low] i = low - 1 j = high + 1 while (True): # Find leftmost element greater than # or equal to pivot i += 1 while (arr[i] < pivot): i += 1 # Find rightmost element smaller than # or equal to pivot j -= 1 while (arr[j] > pivot): j -= 1 # If two pointers met. if (i >= j): return j arr[i], arr[j] = arr[j], arr[i] ''' The main function that implements QuickSortarr --> Array to be sorted,low --> Starting index,high --> Ending index ''' def quickSort(arr, low, high): ''' pi is partitioning index, arr[p] is now at right place ''' if (low < high): pi = partition(arr, low, high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi) quickSort(arr, pi + 1, high) ''' Function to print an array ''' def printArray(arr, n): for i in range(n): print(arr[i], end=\" \") print() # Driver codearr = [10, 7, 8, 9, 1, 5]n = len(arr)quickSort(arr, 0, n - 1)print(\"Sorted array:\")printArray(arr, n) # This code is contributed by shubhamsingh10", "e": 16406, "s": 14867, "text": null }, { "code": "// C# implementation of QuickSort// using Hoare's partition schemeusing System; class GFG { /* This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side*/ static int partition(int[] arr, int low, int high) { int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater // than or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller // than or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // swap(arr[i], arr[j]); } } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void quickSort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); } } /* Function to print an array */ static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(\" \" + arr[i]); Console.WriteLine(); } // Driver Code static public void Main() { int[] arr = { 10, 7, 8, 9, 1, 5 }; int n = arr.Length; quickSort(arr, 0, n - 1); Console.WriteLine(\"Sorted array: \"); printArray(arr, n); }} // This code is contributed by vt_m.", "e": 18449, "s": 16406, "text": null }, { "code": "<script> // Javascript implementation of QuickSort // using Hoare's partition scheme /* This function takes first element as pivot, and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side. It returns the index of the last element on the smaller side*/ function partition(arr, low, high) { let pivot = arr[low]; let i = low - 1, j = high + 1; while (true) { // Find leftmost element greater // than or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller // than or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met. if (i >= j) return j; let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // swap(arr[i], arr[j]); } } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ function quickSort(arr, low, high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ let pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); } } /* Function to print an array */ function printArray(arr, n) { for (let i = 0; i < n; i++) document.write(\" \" + arr[i]); document.write(\"</br>\"); } let arr = [ 10, 7, 8, 9, 1, 5 ]; let n = arr.length; quickSort(arr, 0, n - 1); document.write(\"Sorted array: \" + \"</br>\"); printArray(arr, n); </script>", "e": 20368, "s": 18449, "text": null }, { "code": null, "e": 20397, "s": 20368, "text": "Sorted array: \n1 5 7 8 9 10 " }, { "code": null, "e": 20826, "s": 20397, "text": "Note : If we change Hoare’s partition to pick the last element as pivot, then the Hoare’s partition may cause QuickSort to go into in an infinite recursion. For example, {10, 5, 6, 20} and pivot is arr[high], then returned index will always be high and call to same QuickSort will be made. To handle a random pivot, we can always swap that random element with the first element and simply follow the above algorithm.Comparison: " }, { "code": null, "e": 21501, "s": 20826, "text": "Hoare’s scheme is more efficient than Lomuto’s partition scheme because it does three times fewer swaps on average, and it creates efficient partitions even when all values are equal.Like Lomuto’s partition scheme, Hoare partitioning also causes Quick sort to degrade to O(n^2) when the input array is already sorted, it also doesn’t produce a stable sort.Note that in this scheme, the pivot’s final location is not necessarily at the index that was returned, and the next two segments that the main algorithm recurs on are (lo..p) and (p+1..hi) as opposed to (lo..p-1) and (p+1..hi) as in Lomuto’s scheme.Both Hoare’s Partition, as well as Lomuto’s partition, are unstable." }, { "code": null, "e": 21685, "s": 21501, "text": "Hoare’s scheme is more efficient than Lomuto’s partition scheme because it does three times fewer swaps on average, and it creates efficient partitions even when all values are equal." }, { "code": null, "e": 21859, "s": 21685, "text": "Like Lomuto’s partition scheme, Hoare partitioning also causes Quick sort to degrade to O(n^2) when the input array is already sorted, it also doesn’t produce a stable sort." }, { "code": null, "e": 22110, "s": 21859, "text": "Note that in this scheme, the pivot’s final location is not necessarily at the index that was returned, and the next two segments that the main algorithm recurs on are (lo..p) and (p+1..hi) as opposed to (lo..p-1) and (p+1..hi) as in Lomuto’s scheme." }, { "code": null, "e": 22179, "s": 22110, "text": "Both Hoare’s Partition, as well as Lomuto’s partition, are unstable." }, { "code": null, "e": 22678, "s": 22179, "text": "Source : https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_schemeThis article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 22683, "s": 22678, "text": "vt_m" }, { "code": null, "e": 22698, "s": 22683, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 22706, "s": 22698, "text": "akuma36" }, { "code": null, "e": 22721, "s": 22706, "text": "chinmoy1997pal" }, { "code": null, "e": 22732, "s": 22721, "text": "aodennison" }, { "code": null, "e": 22741, "s": 22732, "text": "mukesh07" }, { "code": null, "e": 22756, "s": 22741, "text": "soubhikmitra98" }, { "code": null, "e": 22770, "s": 22756, "text": "geeky01adarsh" }, { "code": null, "e": 22787, "s": 22770, "text": "surinderdawra388" }, { "code": null, "e": 22800, "s": 22787, "text": "simmytarika5" }, { "code": null, "e": 22817, "s": 22800, "text": "samarthpandya134" }, { "code": null, "e": 22832, "s": 22817, "text": "abhishant24952" }, { "code": null, "e": 22843, "s": 22832, "text": "Quick Sort" }, { "code": null, "e": 22851, "s": 22843, "text": "Sorting" }, { "code": null, "e": 22859, "s": 22851, "text": "Sorting" } ]
ES6 - Syntax
Syntax defines the set of rules for writing programs. Every language specification defines its own syntax. A JavaScript program can be composed of − Variables − Represents a named memory block that can store values for the program. Variables − Represents a named memory block that can store values for the program. Literals − Represents constant/fixed values. Literals − Represents constant/fixed values. Operators − Symbols that define how the operands will be processed. Operators − Symbols that define how the operands will be processed. Keywords − Words that have a special meaning in the context of a language. Keywords − Words that have a special meaning in the context of a language. The following table lists some keywords in JavaScript. Some commonly used keywords are listed in the following table. Modules − Represents code blocks that can be reused across different programs/scripts. Modules − Represents code blocks that can be reused across different programs/scripts. Comments − Used to improve code readability. These are ignored by the JavaScript engine. Comments − Used to improve code readability. These are ignored by the JavaScript engine. Identifiers − These are the names given to elements in a program like variables, functions, etc. The rules for identifiers are − Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit. Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($). Identifiers cannot be keywords. They must be unique. Identifiers are case sensitive. Identifiers cannot contain spaces. Identifiers − These are the names given to elements in a program like variables, functions, etc. The rules for identifiers are − Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit. Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit. Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($). Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($). Identifiers cannot be keywords. They must be unique. Identifiers cannot be keywords. They must be unique. Identifiers are case sensitive. Identifiers cannot contain spaces. Identifiers are case sensitive. Identifiers cannot contain spaces. The following table illustrates some valid and invalid identifiers. firstName first_name num1 $result Var# first name first-name 1number ES6 ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand. JavaScript is case-sensitive. This means that JavaScript differentiates between the uppercase and the lowercase characters. Each line of instruction is called a statement. Semicolons are optional in JavaScript. console.log("hello world") console.log("We are learning ES6") A single line can contain multiple statements. However, these statements must be separated by a semicolon. Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like the author of the code, hints about a function/construct, etc. Comments are ignored by the compiler. JavaScript supports the following types of comments − Single-line comments (//) − Any text between a // and the end of a line is treated as a comment. Single-line comments (//) − Any text between a // and the end of a line is treated as a comment. Multi-line comments (/* */) − These comments may span multiple lines. Multi-line comments (/* */) − These comments may span multiple lines. //this is single line comment /* This is a Multi-line comment */ Let us start with the traditional “Hello World” example". var message = "Hello World" console.log(message) The program can be analyzed as − Line 1 declares a variable by the name message. Variables are a mechanism to store values in a program. Line 1 declares a variable by the name message. Variables are a mechanism to store values in a program. Line 2 prints the variable’s value to the prompt. Here, the console refers to the terminal window. The function log () is used to display the text on the screen. Line 2 prints the variable’s value to the prompt. Here, the console refers to the terminal window. The function log () is used to display the text on the screen. We shall use Node.js to execute our code. Step 1 − Save the file as Test.js Step 1 − Save the file as Test.js Step 2 − Right-click the Test.js file under the working files option in the project-explorer window of the Visual Studio Code. Step 2 − Right-click the Test.js file under the working files option in the project-explorer window of the Visual Studio Code. Step 3 − Select Open in Command Prompt option. Step 3 − Select Open in Command Prompt option. Step 4 − Type the following command in Node’s terminal window. Step 4 − Type the following command in Node’s terminal window. node Test.js The following output is displayed on successful execution of the file. Hello World ECMAScript 2015(ES6) features are classified into three groups − For Shipping − These are features that V8 considers stable. For Shipping − These are features that V8 considers stable. Staged Features − These are almost completed features but not considered stable by the V8 team. Staged Features − These are almost completed features but not considered stable by the V8 team. In Progress − These features should be used only for testing purposes. In Progress − These features should be used only for testing purposes. The first category of features is fully supported and turned on by default by node. Staged features require a runtime - - harmony flag to execute. A list of component specific CLI flags for Node.js can be found here − https://nodejs.org/api/cli.html The fifth edition of the ECMAScript specification introduced the Strict Mode. The Strict Mode imposes a layer of constraint on JavaScript. It makes several changes to normal JavaScript semantics. The code can be transitioned to work in the Strict Mode by including the following − // Whole-script strict mode syntax "use strict"; v = "Hi! I'm a strict mode script!"; // ERROR: Variable v is not declared In the above snippet, the entire code runs as a constrained variant of JavaScript. JavaScript also allows to restrict, the Strict Mode within a block’s scope as that of a function. This is illustrated as follows − v = 15 function f1() { "use strict"; var v = "Hi! I'm a strict mode script!"; } In, the above snippet, any code outside the function will run in the non-strict mode. All statements within the function will be executed in the Strict Mode. The JavaScript engine, by default, moves declarations to the top. This feature is termed as hoisting. This feature applies to variables and functions. Hoisting allows JavaScript to use a component before it has been declared. However, the concept of hoisting does not apply to scripts that are run in the Strict Mode. Variable Hoisting and Function Hoisting are explained in the subsequent chapters. 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2384, "s": 2277, "text": "Syntax defines the set of rules for writing programs. Every language specification defines its own syntax." }, { "code": null, "e": 2426, "s": 2384, "text": "A JavaScript program can be composed of −" }, { "code": null, "e": 2509, "s": 2426, "text": "Variables − Represents a named memory block that can store values for the program." }, { "code": null, "e": 2592, "s": 2509, "text": "Variables − Represents a named memory block that can store values for the program." }, { "code": null, "e": 2637, "s": 2592, "text": "Literals − Represents constant/fixed values." }, { "code": null, "e": 2682, "s": 2637, "text": "Literals − Represents constant/fixed values." }, { "code": null, "e": 2750, "s": 2682, "text": "Operators − Symbols that define how the operands will be processed." }, { "code": null, "e": 2818, "s": 2750, "text": "Operators − Symbols that define how the operands will be processed." }, { "code": null, "e": 2893, "s": 2818, "text": "Keywords − Words that have a special meaning in the context of a language." }, { "code": null, "e": 2968, "s": 2893, "text": "Keywords − Words that have a special meaning in the context of a language." }, { "code": null, "e": 3086, "s": 2968, "text": "The following table lists some keywords in JavaScript. Some commonly used keywords are listed in the following table." }, { "code": null, "e": 3173, "s": 3086, "text": "Modules − Represents code blocks that can be reused across different programs/scripts." }, { "code": null, "e": 3260, "s": 3173, "text": "Modules − Represents code blocks that can be reused across different programs/scripts." }, { "code": null, "e": 3349, "s": 3260, "text": "Comments − Used to improve code readability. These are ignored by the JavaScript engine." }, { "code": null, "e": 3438, "s": 3349, "text": "Comments − Used to improve code readability. These are ignored by the JavaScript engine." }, { "code": null, "e": 3885, "s": 3438, "text": "Identifiers − These are the names given to elements in a program like variables, functions, etc. The rules for identifiers are −\n\nIdentifiers can include both, characters and digits. However, the identifier cannot begin with a digit.\nIdentifiers cannot include special symbols except for underscore (_) or a dollar sign ($).\nIdentifiers cannot be keywords. They must be unique.\nIdentifiers are case sensitive. Identifiers cannot contain spaces.\n\n" }, { "code": null, "e": 4014, "s": 3885, "text": "Identifiers − These are the names given to elements in a program like variables, functions, etc. The rules for identifiers are −" }, { "code": null, "e": 4118, "s": 4014, "text": "Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit." }, { "code": null, "e": 4222, "s": 4118, "text": "Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit." }, { "code": null, "e": 4313, "s": 4222, "text": "Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($)." }, { "code": null, "e": 4404, "s": 4313, "text": "Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($)." }, { "code": null, "e": 4457, "s": 4404, "text": "Identifiers cannot be keywords. They must be unique." }, { "code": null, "e": 4510, "s": 4457, "text": "Identifiers cannot be keywords. They must be unique." }, { "code": null, "e": 4577, "s": 4510, "text": "Identifiers are case sensitive. Identifiers cannot contain spaces." }, { "code": null, "e": 4644, "s": 4577, "text": "Identifiers are case sensitive. Identifiers cannot contain spaces." }, { "code": null, "e": 4712, "s": 4644, "text": "The following table illustrates some valid and invalid identifiers." }, { "code": null, "e": 4722, "s": 4712, "text": "firstName" }, { "code": null, "e": 4733, "s": 4722, "text": "first_name" }, { "code": null, "e": 4738, "s": 4733, "text": "num1" }, { "code": null, "e": 4746, "s": 4738, "text": "$result" }, { "code": null, "e": 4751, "s": 4746, "text": "Var#" }, { "code": null, "e": 4762, "s": 4751, "text": "first name" }, { "code": null, "e": 4773, "s": 4762, "text": "first-name" }, { "code": null, "e": 4781, "s": 4773, "text": "1number" }, { "code": null, "e": 5037, "s": 4781, "text": "ES6 ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand." }, { "code": null, "e": 5161, "s": 5037, "text": "JavaScript is case-sensitive. This means that JavaScript differentiates between the uppercase and the lowercase characters." }, { "code": null, "e": 5248, "s": 5161, "text": "Each line of instruction is called a statement. Semicolons are optional in JavaScript." }, { "code": null, "e": 5312, "s": 5248, "text": "console.log(\"hello world\") \nconsole.log(\"We are learning ES6\") " }, { "code": null, "e": 5419, "s": 5312, "text": "A single line can contain multiple statements. However, these statements must be separated by a semicolon." }, { "code": null, "e": 5656, "s": 5419, "text": "Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like the author of the code, hints about a function/construct, etc. Comments are ignored by the compiler." }, { "code": null, "e": 5710, "s": 5656, "text": "JavaScript supports the following types of comments −" }, { "code": null, "e": 5807, "s": 5710, "text": "Single-line comments (//) − Any text between a // and the end of a line is treated as a comment." }, { "code": null, "e": 5904, "s": 5807, "text": "Single-line comments (//) − Any text between a // and the end of a line is treated as a comment." }, { "code": null, "e": 5976, "s": 5904, "text": "Multi-line comments (/* */) − These comments may span multiple lines." }, { "code": null, "e": 6048, "s": 5976, "text": "Multi-line comments (/* */) − These comments may span multiple lines." }, { "code": null, "e": 6118, "s": 6048, "text": "//this is single line comment \n/* This is a \nMulti-line comment \n*/" }, { "code": null, "e": 6176, "s": 6118, "text": "Let us start with the traditional “Hello World” example\"." }, { "code": null, "e": 6226, "s": 6176, "text": "var message = \"Hello World\" \nconsole.log(message)" }, { "code": null, "e": 6259, "s": 6226, "text": "The program can be analyzed as −" }, { "code": null, "e": 6363, "s": 6259, "text": "Line 1 declares a variable by the name message. Variables are a mechanism to store values in a program." }, { "code": null, "e": 6467, "s": 6363, "text": "Line 1 declares a variable by the name message. Variables are a mechanism to store values in a program." }, { "code": null, "e": 6629, "s": 6467, "text": "Line 2 prints the variable’s value to the prompt. Here, the console refers to the terminal window. The function log () is used to display the text on the screen." }, { "code": null, "e": 6791, "s": 6629, "text": "Line 2 prints the variable’s value to the prompt. Here, the console refers to the terminal window. The function log () is used to display the text on the screen." }, { "code": null, "e": 6833, "s": 6791, "text": "We shall use Node.js to execute our code." }, { "code": null, "e": 6867, "s": 6833, "text": "Step 1 − Save the file as Test.js" }, { "code": null, "e": 6901, "s": 6867, "text": "Step 1 − Save the file as Test.js" }, { "code": null, "e": 7028, "s": 6901, "text": "Step 2 − Right-click the Test.js file under the working files option in the project-explorer window of the Visual Studio Code." }, { "code": null, "e": 7155, "s": 7028, "text": "Step 2 − Right-click the Test.js file under the working files option in the project-explorer window of the Visual Studio Code." }, { "code": null, "e": 7202, "s": 7155, "text": "Step 3 − Select Open in Command Prompt option." }, { "code": null, "e": 7249, "s": 7202, "text": "Step 3 − Select Open in Command Prompt option." }, { "code": null, "e": 7312, "s": 7249, "text": "Step 4 − Type the following command in Node’s terminal window." }, { "code": null, "e": 7375, "s": 7312, "text": "Step 4 − Type the following command in Node’s terminal window." }, { "code": null, "e": 7390, "s": 7375, "text": "node Test.js \n" }, { "code": null, "e": 7461, "s": 7390, "text": "The following output is displayed on successful execution of the file." }, { "code": null, "e": 7474, "s": 7461, "text": "Hello World\n" }, { "code": null, "e": 7539, "s": 7474, "text": "ECMAScript 2015(ES6) features are classified into three groups −" }, { "code": null, "e": 7599, "s": 7539, "text": "For Shipping − These are features that V8 considers stable." }, { "code": null, "e": 7659, "s": 7599, "text": "For Shipping − These are features that V8 considers stable." }, { "code": null, "e": 7755, "s": 7659, "text": "Staged Features − These are almost completed features but not considered stable by the V8 team." }, { "code": null, "e": 7851, "s": 7755, "text": "Staged Features − These are almost completed features but not considered stable by the V8 team." }, { "code": null, "e": 7922, "s": 7851, "text": "In Progress − These features should be used only for testing purposes." }, { "code": null, "e": 7993, "s": 7922, "text": "In Progress − These features should be used only for testing purposes." }, { "code": null, "e": 8140, "s": 7993, "text": "The first category of features is fully supported and turned on by default by node. Staged features require a runtime - - harmony flag to execute." }, { "code": null, "e": 8243, "s": 8140, "text": "A list of component specific CLI flags for Node.js can be found here − https://nodejs.org/api/cli.html" }, { "code": null, "e": 8439, "s": 8243, "text": "The fifth edition of the ECMAScript specification introduced the Strict Mode. The Strict Mode imposes a layer of constraint on JavaScript. It makes several changes to normal JavaScript semantics." }, { "code": null, "e": 8524, "s": 8439, "text": "The code can be transitioned to work in the Strict Mode by including the following −" }, { "code": null, "e": 8652, "s": 8524, "text": "// Whole-script strict mode syntax \n\"use strict\"; \n v = \"Hi! I'm a strict mode script!\"; // ERROR: Variable v is not declared" }, { "code": null, "e": 8735, "s": 8652, "text": "In the above snippet, the entire code runs as a constrained variant of JavaScript." }, { "code": null, "e": 8866, "s": 8735, "text": "JavaScript also allows to restrict, the Strict Mode within a block’s scope as that of a function. This is illustrated as follows −" }, { "code": null, "e": 8957, "s": 8866, "text": "v = 15 \nfunction f1() { \n \"use strict\"; \n var v = \"Hi! I'm a strict mode script!\"; \n}" }, { "code": null, "e": 9115, "s": 8957, "text": "In, the above snippet, any code outside the function will run in the non-strict mode. All statements within the function will be executed in the Strict Mode." }, { "code": null, "e": 9433, "s": 9115, "text": "The JavaScript engine, by default, moves declarations to the top. This feature is termed as hoisting. This feature applies to variables and functions. Hoisting allows JavaScript to use a component before it has been declared. However, the concept of hoisting does not apply to scripts that are run in the Strict Mode." }, { "code": null, "e": 9515, "s": 9433, "text": "Variable Hoisting and Function Hoisting are explained in the subsequent chapters." }, { "code": null, "e": 9550, "s": 9515, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9564, "s": 9550, "text": " Sharad Kumar" }, { "code": null, "e": 9597, "s": 9564, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 9615, "s": 9597, "text": " Richa Maheshwari" }, { "code": null, "e": 9648, "s": 9615, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 9662, "s": 9648, "text": " Anadi Sharma" }, { "code": null, "e": 9697, "s": 9662, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 9714, "s": 9697, "text": " Gowthami Swarna" }, { "code": null, "e": 9747, "s": 9714, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9763, "s": 9747, "text": " Deepti Trivedi" }, { "code": null, "e": 9798, "s": 9763, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9806, "s": 9798, "text": " Shweta" }, { "code": null, "e": 9813, "s": 9806, "text": " Print" }, { "code": null, "e": 9824, "s": 9813, "text": " Add Notes" } ]
Data Analysis & Visualization in Finance — Technical Analysis of Stocks using Python | by Pratik Nabriya | Towards Data Science
With an increase in the penetration of analytics into numerous facets of our lives, finance is definitely one of the earliest to catch onto this trend. In this article, I have attempted to showcase how data analytics and visualization techniques can be incorporated in the world of finance. For this analysis, I have used 2 years of historical data from around mid-Feb 2018 to Feb 2020 of the below stocks listed on National Stock Exchange(NSE)— HDFC Ltd. Sun Pharmaceutical Industries Ltd. Tata Consultancy Services Ltd. Jindal Steel & Power Ltd. Jubilant FoodWorks Ltd. The reason why I selected these is because I had worked on these stocks during the my recent internship. You may choose your own set of stocks and the time period for the analysis. The stocks I selected are from different sectors and market cap. You’ll see how it is advantageous as we progress in this article. For the start, we’ll investigate the HDFC stock individually and then move on to the combined analysis. For this section, I have downloaded the csv file of historical data of HDFC stock from Yahoo finance . In next section, we’ll be using an awesome tool to directly extract stock prices from the web. Import necessary libraries — import numpy as np import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport datetimeimport warningswarnings.filterwarnings('ignore') Read data from csv file and display first few rows — HDFC_df = pd.read_csv(“HDFC.csv”) HDFC_df.head() Output: Since our time-frame of analysis is large, we can relax on number of decimal places to consider. HDFC_df = HDFC_df.round(2)HDFC_df.head(2) Output: Better! Now, lets determine the shape of the dataset — HDFC_df.shape Output: (491, 7) Our HDFC dataset has 491 rows and 7 columns. Next, we check if the dataset has any null values — HDFC_df.isnull().sum() Output: Drop the null entries from the dataset — HDFC_df.dropna(inplace = True, axis = 0) Now, let’s check the data type of each column — HDFC_df.dtypes Output: As we can see, the ‘Date’ column is not in appropriate format. Pandas has inbuilt features to deal with time-series data in a smarter way. But to make use of Pandas functionality for dates, we need to ensure that the ‘Date’ column is of type ‘datetime64(ns)’. HDFC_df['Date'] = pd.to_datetime(HDFC_df['Date'])HDFC_df.head(2 To get total time duration for which we’re carrying out this analysis — HDFC_df[‘Date’].max() — HDFC_df[‘Date’].min() Output: Timedelta(‘729 days 00:00:00’) There are approximately 252 trading days in an year with an average of 21 days per month, or 63 days per quarter. Out of a possible 365 days, 104 days are weekends (Saturday and Sunday) when the stock exchanges are closed. Next, we’ll use the describe() function of Pandas to get high-level overview of how the HDFC stock performed in about last couple of months — HDFC_df.iloc[-90:].describe().astype(int) Output: In last 90 days, the average closing price for HDFC stock was about ₹2307. For about 75% of time the stock was trading below ₹2421 and it clocked maximum of ₹2492. The maximum volume of shares traded on a single day was 8808006 with median quantity being 2776142. Before we move on towards further investigation, we’ll set the ‘Date’ column as the index of the dataframe. It makes plotting easy. HDFC_df.index = HDFC_df[‘Date’] Now plot the closing price (adjusted) of the stock over the period of 2 years to get a general idea of how the stock performed in the given period. HDFC_df[‘Adj Close’].plot(figsize = (15,8))plt.show() Output: In the above plot, if you notice, there is a drastic decrease in the price of stock sometime around the month of September 2018. Apart from the “September effect”, the general decline in the stock price of HDFC can be attributed to the escalating tariff war between the US and China that had a ripple effect on Indian financial markets. Daily percentage change in the price of the stock is calculated on the basis of percentage change between 2 consecutive days’ closing prices. Let’s say if the closing price of the stock yesterday was ₹500 and today the stock closed as ₹550. So, the percentage change is 10%. i.e. ((550–500) / 500)*100. No mystery here! Accordingly, we’ll introduce a new column ‘Day_Perc_Change’ denoting the daily returns in the price of the stock. This can be done using in-built pct_change() function in python. HDFC_df[‘Day_Perc_Change’] = HDFC_df[‘Adj Close’].pct_change()*100HDFC_df.head() Output: You’ll notice that the first value in the ‘Day_Perc_Change’ column is NaN. We’ll drop this row. HDFC_df.dropna(axis = 0, inplace = True) Representing daily returns in form of a plot — HDFC_df[‘Day_Perc_Change’].plot(figsize = (12, 6), fontsize = 12) Output: It can be observed that for most of the days, the returns are between -2% to 2% with few spikes in between crossing 6% mark on both the sides. Likewise you can find similar news articles for the days when there was drastic rise/fall in the price of the stock. Plotting daily returns distribution histogram — HDFC_df[‘Day_Perc_Change’].hist(bins = 50, figsize = (10,5)) plt.xlabel(‘Daily returns’)plt.ylabel(‘Frequency’)plt.show()#satisticsHDFC_df.Day_Perc_Change.describe() Output: The daily returns histogram is centered about origin. For the past 2 years, the mean daily returns has been about 0.072 and for most of the days the daily return was less than 1% implying that the HDFC stock has been less volatile over the period. During the period, the highest % change in positive direction was observed to be 6.46% and was 6.56% in negative direction. Clearly, we didn’t had any instances of ‘bull run’ or ‘bear drop’! Next we add a new column ‘Trend’ whose values are based on the day-to-day percentage change we calculated above. Trend is determined from below relationship — def trend(x): if x > -0.5 and x <= 0.5: return ‘Slight or No change’ elif x > 0.5 and x <= 1: return ‘Slight Positive’ elif x > -1 and x <= -0.5: return ‘Slight Negative’ elif x > 1 and x <= 3: return ‘Positive’ elif x > -3 and x <= -1: return ‘Negative’ elif x > 3 and x <= 7: return ‘Among top gainers’ elif x > -7 and x <= -3: return ‘Among top losers’ elif x > 7: return ‘Bull run’ elif x <= -7: return ‘Bear drop’HDFC_df[‘Trend’]= np.zeros(HDFC_df[‘Day_Perc_Change’].count())HDFC_df[‘Trend’]= HDFC_df[‘Day_Perc_Change’].apply(lambda x:trend(x))HDFC_df.head() Output: We wish to see how the stock was trending in past 2 years. This can be visualized as a pie chart, with each sector representing the percentage of days each trend occurred. We’ll plot a pie chart for the ‘Trend’ column to visualize the relative frequency of each trend category. For this, we’ll use the groupby() function with the trend column to aggregate all days with the same trend into a single group before plotting the pie chart. Visualizing Trend Frequency with Pie-Chart — DFC_pie_data = HDFC_df.groupby('Trend')pie_label = sorted([i for i in HDFC_df.loc[:, 'Trend'].unique()])plt.pie(HDFC_pie_data['Trend'].count(), labels = pie_label, autopct = '%1.1f%%', radius = 2)plt.show() Output: For the period under consideration from mid-Feb 2018 to Feb 2020, the HDFC stock was among the top gainers for about 1.8% of the time, and among the top losers for 1.6 %. For about 12.4% of the time period, the stock has performed positively on a given day. Likewise, for most period of time (about 29.6%) the stock showed a very slight change in the price. These observations are consistent with the daily return histogram we saw in above section. plt.stem(HDFC_df[‘Date’], HDFC_df[‘Day_Perc_Change’])(HDFC_df[‘Volume’]/1000000).plot(figsize = (15, 7.5), color = ‘green’, alpha = 0.5) Output: (* Daily volume of trade has been reduced in scale to match with the daily return scale) By juxtaposing the daily trade volume(in green) with the daily returns(in blue), it was observed that whenever the volume of shares traded is high, there is comparatively high rise or fall in the price of the stock leading to the high returns. Thus, on a given day if unconventionally high volume of trading takes place, then one can expect a big change in the market in the either direction. Volume of shares traded when coupled with the rise or fall in Price of stock, in general, is an indicator of the confidence of the traders & investors in a particular company. “Never put all your eggs in a single basket” Whenever we go for the diversification of the portfolio, we would NOT want the stocks to be related to each other. Mathematically, Pearson’s correlation coefficient (also called Pearson’s R value) between any pair of stocks should be close to 0. The idea behind is simple — suppose your portfolio comprises of the stocks that are highly correlated, then if one stock tumbles, the others might fall too and you’re at the risk of losing all your investment! I selected the aforementioned stocks to perform the correlation analysis. All these stocks are from different segments of Industry and Market cap. You are free to choose the stocks of your interest. the procedure remains the same. In previous section we’ve used the pre-downloaded csv file for analysis. In this section, we’ll take the help of Pandas web data reader package to extract the prices of stocks. # import packageimport pandas_datareader.data as web# set start and end dates start = datetime.datetime(2018, 2, 15)end = datetime.datetime(2020, 2, 14) # extract the closing price datacombined_df = web.DataReader([‘HDFC.NS’, ‘JINDALSTEL.NS’, ‘JUBLFOOD.NS’,‘SUNPHARMA.NS’, ‘TCS.NS’, ‘^NSEI’],‘yahoo’, start = start, end = end)[‘Adj Close’] Drop null values and display first few rows — # drop null valuescombined_df.dropna(inplace = True, axis = 0)# display first few rowscombined_df.head() Output: (^ NSEI is symbol for National Stock Exchange Index — NIFTY 50 ) Next we’ll analyse the correlation between the different stocks in a pair-wise fashion with Seaborn pairplot. # store daily returns of all above stocks in a new dataframe pct_chg_df = combined_df.pct_change()*100pct_chg_df.dropna(inplace = True, how = ‘any’, axis = 0)# plotting pairplot import seaborn as snssns.set(style = ‘ticks’, font_scale = 1.25)sns.pairplot(pct_chg_df) Output: Note that the correlation analysis is performed on the daily percentage change(daily returns) of the stock price and not on the stock price. If you observe carefully, the plots in the lower triangular area are the same as the plots in the upper triangular area with just axes interchanged. So, analyzing either set of plots would suffice. The diagonal represents the histograms, just like the one seen above for HDFC stock. Takeaway: HDFC, Jindal Steel, Jubilant Foods, Sun Pharma and TCS stocks can be included in a portfolio as no two stocks show any significant correlation. Drawback: Although the pair plots provide very good visualization of all possible combinations between the bunch of stocks, it doesn’t provide any detailed information like Pearson’s R value or null-hypothesis p value to quantify the correlation. That’s where the joint plot comes into the picture! While Pair plot provides a visual insight into all possible correlations, Seaborn jointplot provides detailed information like Pearson’s R value (Pearson’s correlation coefficient) for each pair of stocks. Pearson’s R value ranges from -1 to 1. Negative value indicates a negative linear relation between the variables, while positive value indicates a positive relationship. Pearson’s R value closer to 1 (or -1) indicates strong correlation, while value closer to 0 indicates weak correlation. In addition to Pearson’s R value, joint plot also shows the respective histograms on the edges as well as null hypothesis p-value. Here’s an example of a joint plots between the stocks of Sun Pharma vs Jindal Steel and Jindal Steel vs HDFC — from scipy.stats import statssns.jointplot(‘SUNPHARMA.NS’, ‘JINDALSTEL.NS’, pct_chg_df, kind = ‘scatter’).annotate(stats.pearsonr)sns.jointplot(‘JINDALSTEL.NS’, ‘HDFC.NS’, pct_chg_df, kind = ‘scatter’).annotate(stats.pearsonr)plt.show() Output: Takeaways: The Pearson’s R value is 0.24 for Jindal Steel v/s Sun Pharma which is very less. This indicates a weak correlation. Similarly, the Pearson’s R value is observed to be 0.29 in case of HDFC v/s Jindal Steel indicating weak correlation between HDFC and Jindal Steel stocks. These above results from Joint plots equip us with the numerical figures to ascertain the insights we derived by visually observing the Pair plot previously. Beware! having correlation is not the only parameter to determine which stocks to include in an portfolio and which to remove. There are several other factors at play. It’s best to seek advice of the experts and make an informed decision. Volatility is one of the most important pillars in financial markets. A stock is said to have high volatility if its value can change dramatically within a short span of time. On other hand, lower volatility means that value of stock tends to be relatively steady over a period of time. These movements are due to several factors including demand and supply, sentiment, corporate actions, greed, and fear, etc. Mathematically, volatility is measured using a statistical measure called ‘standard deviation’, which measures an asset’s departure from its average value. We have already calculated the intraday returns (daily returns) of the HDFC stock and several other stocks. Next, we will calculate the 7-day rolling mean(also called moving average) of the daily returns, then compute the standard deviation (which is square root of the variance) and plot the values. Relax, we don’t have to calculate all this manually; Pandas ‘rolling()’ function and ‘std()’ function does the job for us in just one line! HDFC_vol = pct_chg_df[‘HDFC.NS’].rolling(7).std()*np.sqrt(7)HDFC_vol.plot(figsize = (15, 7)) Output: Next we’ll see the comparative volatility analysis of HDFC stock with SunPharma stock and NIFTY50 index. Just like above, we compute 7-day rolling mean, and standard deviation, all in a single line of code. Pandas indeed makes our life easy! volatility = pct_chg_df[['HDFC.NS', 'SUNPHARMA.NS', '^NSEI']].rolling(7).std()*np.sqrt(7)volatility.plot(figsize = (15, 7)) Output: You can observe that Sun Pharma stock has higher volatility as compared to HDFC stock, while the Nifty index has least volatility. This is expected as Sun Pharma is a mid-cap stock and mid-cap stocks in general tend to have higher volatility as compared to the large-cap stocks such as HDFC. Many traders and investors seek out higher volatility investments in order to make higher profits. If a stock does not move, not only it has low volatility, but also it has low gain potential. On the other hand, a stock or other security with a very high volatility level can have tremendous profit potential, but the risk is equally high. There is no full-proof strategy that can guarantee profit on your investment. In the real-world, there are a number of factors that traders take into account before making an investment. By using the right strategies and techniques, we can only improve our chances. I am looking forward to introduce some of these strategies & techniques along with demonstration using python in my subsequent articles. References: For Data — Yahoo FinanceFor Finance technicalities — Investopedia For Data — Yahoo Finance For Finance technicalities — Investopedia — — — — — — — — — — — — — — — — — — — — — — — — —Disclaimer — This article is purely for educational purpose and does not endorse any company or stock. Kindly consult experts before making any decision related to buying or selling of stocks.— — — — — — — — — — — — — — — — — — — — — — — — —
[ { "code": null, "e": 463, "s": 172, "text": "With an increase in the penetration of analytics into numerous facets of our lives, finance is definitely one of the earliest to catch onto this trend. In this article, I have attempted to showcase how data analytics and visualization techniques can be incorporated in the world of finance." }, { "code": null, "e": 618, "s": 463, "text": "For this analysis, I have used 2 years of historical data from around mid-Feb 2018 to Feb 2020 of the below stocks listed on National Stock Exchange(NSE)—" }, { "code": null, "e": 628, "s": 618, "text": "HDFC Ltd." }, { "code": null, "e": 663, "s": 628, "text": "Sun Pharmaceutical Industries Ltd." }, { "code": null, "e": 694, "s": 663, "text": "Tata Consultancy Services Ltd." }, { "code": null, "e": 720, "s": 694, "text": "Jindal Steel & Power Ltd." }, { "code": null, "e": 744, "s": 720, "text": "Jubilant FoodWorks Ltd." }, { "code": null, "e": 925, "s": 744, "text": "The reason why I selected these is because I had worked on these stocks during the my recent internship. You may choose your own set of stocks and the time period for the analysis." }, { "code": null, "e": 1358, "s": 925, "text": "The stocks I selected are from different sectors and market cap. You’ll see how it is advantageous as we progress in this article. For the start, we’ll investigate the HDFC stock individually and then move on to the combined analysis. For this section, I have downloaded the csv file of historical data of HDFC stock from Yahoo finance . In next section, we’ll be using an awesome tool to directly extract stock prices from the web." }, { "code": null, "e": 1387, "s": 1358, "text": "Import necessary libraries —" }, { "code": null, "e": 1541, "s": 1387, "text": "import numpy as np import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport datetimeimport warningswarnings.filterwarnings('ignore')" }, { "code": null, "e": 1594, "s": 1541, "text": "Read data from csv file and display first few rows —" }, { "code": null, "e": 1643, "s": 1594, "text": "HDFC_df = pd.read_csv(“HDFC.csv”) HDFC_df.head()" }, { "code": null, "e": 1651, "s": 1643, "text": "Output:" }, { "code": null, "e": 1748, "s": 1651, "text": "Since our time-frame of analysis is large, we can relax on number of decimal places to consider." }, { "code": null, "e": 1790, "s": 1748, "text": "HDFC_df = HDFC_df.round(2)HDFC_df.head(2)" }, { "code": null, "e": 1798, "s": 1790, "text": "Output:" }, { "code": null, "e": 1853, "s": 1798, "text": "Better! Now, lets determine the shape of the dataset —" }, { "code": null, "e": 1867, "s": 1853, "text": "HDFC_df.shape" }, { "code": null, "e": 1884, "s": 1867, "text": "Output: (491, 7)" }, { "code": null, "e": 1981, "s": 1884, "text": "Our HDFC dataset has 491 rows and 7 columns. Next, we check if the dataset has any null values —" }, { "code": null, "e": 2004, "s": 1981, "text": "HDFC_df.isnull().sum()" }, { "code": null, "e": 2012, "s": 2004, "text": "Output:" }, { "code": null, "e": 2053, "s": 2012, "text": "Drop the null entries from the dataset —" }, { "code": null, "e": 2094, "s": 2053, "text": "HDFC_df.dropna(inplace = True, axis = 0)" }, { "code": null, "e": 2142, "s": 2094, "text": "Now, let’s check the data type of each column —" }, { "code": null, "e": 2157, "s": 2142, "text": "HDFC_df.dtypes" }, { "code": null, "e": 2165, "s": 2157, "text": "Output:" }, { "code": null, "e": 2425, "s": 2165, "text": "As we can see, the ‘Date’ column is not in appropriate format. Pandas has inbuilt features to deal with time-series data in a smarter way. But to make use of Pandas functionality for dates, we need to ensure that the ‘Date’ column is of type ‘datetime64(ns)’." }, { "code": null, "e": 2489, "s": 2425, "text": "HDFC_df['Date'] = pd.to_datetime(HDFC_df['Date'])HDFC_df.head(2" }, { "code": null, "e": 2561, "s": 2489, "text": "To get total time duration for which we’re carrying out this analysis —" }, { "code": null, "e": 2607, "s": 2561, "text": "HDFC_df[‘Date’].max() — HDFC_df[‘Date’].min()" }, { "code": null, "e": 2646, "s": 2607, "text": "Output: Timedelta(‘729 days 00:00:00’)" }, { "code": null, "e": 2869, "s": 2646, "text": "There are approximately 252 trading days in an year with an average of 21 days per month, or 63 days per quarter. Out of a possible 365 days, 104 days are weekends (Saturday and Sunday) when the stock exchanges are closed." }, { "code": null, "e": 3011, "s": 2869, "text": "Next, we’ll use the describe() function of Pandas to get high-level overview of how the HDFC stock performed in about last couple of months —" }, { "code": null, "e": 3053, "s": 3011, "text": "HDFC_df.iloc[-90:].describe().astype(int)" }, { "code": null, "e": 3061, "s": 3053, "text": "Output:" }, { "code": null, "e": 3325, "s": 3061, "text": "In last 90 days, the average closing price for HDFC stock was about ₹2307. For about 75% of time the stock was trading below ₹2421 and it clocked maximum of ₹2492. The maximum volume of shares traded on a single day was 8808006 with median quantity being 2776142." }, { "code": null, "e": 3457, "s": 3325, "text": "Before we move on towards further investigation, we’ll set the ‘Date’ column as the index of the dataframe. It makes plotting easy." }, { "code": null, "e": 3489, "s": 3457, "text": "HDFC_df.index = HDFC_df[‘Date’]" }, { "code": null, "e": 3637, "s": 3489, "text": "Now plot the closing price (adjusted) of the stock over the period of 2 years to get a general idea of how the stock performed in the given period." }, { "code": null, "e": 3691, "s": 3637, "text": "HDFC_df[‘Adj Close’].plot(figsize = (15,8))plt.show()" }, { "code": null, "e": 3699, "s": 3691, "text": "Output:" }, { "code": null, "e": 4036, "s": 3699, "text": "In the above plot, if you notice, there is a drastic decrease in the price of stock sometime around the month of September 2018. Apart from the “September effect”, the general decline in the stock price of HDFC can be attributed to the escalating tariff war between the US and China that had a ripple effect on Indian financial markets." }, { "code": null, "e": 4356, "s": 4036, "text": "Daily percentage change in the price of the stock is calculated on the basis of percentage change between 2 consecutive days’ closing prices. Let’s say if the closing price of the stock yesterday was ₹500 and today the stock closed as ₹550. So, the percentage change is 10%. i.e. ((550–500) / 500)*100. No mystery here!" }, { "code": null, "e": 4535, "s": 4356, "text": "Accordingly, we’ll introduce a new column ‘Day_Perc_Change’ denoting the daily returns in the price of the stock. This can be done using in-built pct_change() function in python." }, { "code": null, "e": 4616, "s": 4535, "text": "HDFC_df[‘Day_Perc_Change’] = HDFC_df[‘Adj Close’].pct_change()*100HDFC_df.head()" }, { "code": null, "e": 4624, "s": 4616, "text": "Output:" }, { "code": null, "e": 4720, "s": 4624, "text": "You’ll notice that the first value in the ‘Day_Perc_Change’ column is NaN. We’ll drop this row." }, { "code": null, "e": 4761, "s": 4720, "text": "HDFC_df.dropna(axis = 0, inplace = True)" }, { "code": null, "e": 4808, "s": 4761, "text": "Representing daily returns in form of a plot —" }, { "code": null, "e": 4874, "s": 4808, "text": "HDFC_df[‘Day_Perc_Change’].plot(figsize = (12, 6), fontsize = 12)" }, { "code": null, "e": 4882, "s": 4874, "text": "Output:" }, { "code": null, "e": 5025, "s": 4882, "text": "It can be observed that for most of the days, the returns are between -2% to 2% with few spikes in between crossing 6% mark on both the sides." }, { "code": null, "e": 5142, "s": 5025, "text": "Likewise you can find similar news articles for the days when there was drastic rise/fall in the price of the stock." }, { "code": null, "e": 5190, "s": 5142, "text": "Plotting daily returns distribution histogram —" }, { "code": null, "e": 5356, "s": 5190, "text": "HDFC_df[‘Day_Perc_Change’].hist(bins = 50, figsize = (10,5)) plt.xlabel(‘Daily returns’)plt.ylabel(‘Frequency’)plt.show()#satisticsHDFC_df.Day_Perc_Change.describe()" }, { "code": null, "e": 5364, "s": 5356, "text": "Output:" }, { "code": null, "e": 5803, "s": 5364, "text": "The daily returns histogram is centered about origin. For the past 2 years, the mean daily returns has been about 0.072 and for most of the days the daily return was less than 1% implying that the HDFC stock has been less volatile over the period. During the period, the highest % change in positive direction was observed to be 6.46% and was 6.56% in negative direction. Clearly, we didn’t had any instances of ‘bull run’ or ‘bear drop’!" }, { "code": null, "e": 5962, "s": 5803, "text": "Next we add a new column ‘Trend’ whose values are based on the day-to-day percentage change we calculated above. Trend is determined from below relationship —" }, { "code": null, "e": 6562, "s": 5962, "text": "def trend(x): if x > -0.5 and x <= 0.5: return ‘Slight or No change’ elif x > 0.5 and x <= 1: return ‘Slight Positive’ elif x > -1 and x <= -0.5: return ‘Slight Negative’ elif x > 1 and x <= 3: return ‘Positive’ elif x > -3 and x <= -1: return ‘Negative’ elif x > 3 and x <= 7: return ‘Among top gainers’ elif x > -7 and x <= -3: return ‘Among top losers’ elif x > 7: return ‘Bull run’ elif x <= -7: return ‘Bear drop’HDFC_df[‘Trend’]= np.zeros(HDFC_df[‘Day_Perc_Change’].count())HDFC_df[‘Trend’]= HDFC_df[‘Day_Perc_Change’].apply(lambda x:trend(x))HDFC_df.head()" }, { "code": null, "e": 6570, "s": 6562, "text": "Output:" }, { "code": null, "e": 6848, "s": 6570, "text": "We wish to see how the stock was trending in past 2 years. This can be visualized as a pie chart, with each sector representing the percentage of days each trend occurred. We’ll plot a pie chart for the ‘Trend’ column to visualize the relative frequency of each trend category." }, { "code": null, "e": 7006, "s": 6848, "text": "For this, we’ll use the groupby() function with the trend column to aggregate all days with the same trend into a single group before plotting the pie chart." }, { "code": null, "e": 7051, "s": 7006, "text": "Visualizing Trend Frequency with Pie-Chart —" }, { "code": null, "e": 7266, "s": 7051, "text": "DFC_pie_data = HDFC_df.groupby('Trend')pie_label = sorted([i for i in HDFC_df.loc[:, 'Trend'].unique()])plt.pie(HDFC_pie_data['Trend'].count(), labels = pie_label, autopct = '%1.1f%%', radius = 2)plt.show()" }, { "code": null, "e": 7274, "s": 7266, "text": "Output:" }, { "code": null, "e": 7723, "s": 7274, "text": "For the period under consideration from mid-Feb 2018 to Feb 2020, the HDFC stock was among the top gainers for about 1.8% of the time, and among the top losers for 1.6 %. For about 12.4% of the time period, the stock has performed positively on a given day. Likewise, for most period of time (about 29.6%) the stock showed a very slight change in the price. These observations are consistent with the daily return histogram we saw in above section." }, { "code": null, "e": 7926, "s": 7723, "text": "plt.stem(HDFC_df[‘Date’], HDFC_df[‘Day_Perc_Change’])(HDFC_df[‘Volume’]/1000000).plot(figsize = (15, 7.5), color = ‘green’, alpha = 0.5)" }, { "code": null, "e": 7934, "s": 7926, "text": "Output:" }, { "code": null, "e": 8023, "s": 7934, "text": "(* Daily volume of trade has been reduced in scale to match with the daily return scale)" }, { "code": null, "e": 8592, "s": 8023, "text": "By juxtaposing the daily trade volume(in green) with the daily returns(in blue), it was observed that whenever the volume of shares traded is high, there is comparatively high rise or fall in the price of the stock leading to the high returns. Thus, on a given day if unconventionally high volume of trading takes place, then one can expect a big change in the market in the either direction. Volume of shares traded when coupled with the rise or fall in Price of stock, in general, is an indicator of the confidence of the traders & investors in a particular company." }, { "code": null, "e": 8637, "s": 8592, "text": "“Never put all your eggs in a single basket”" }, { "code": null, "e": 9093, "s": 8637, "text": "Whenever we go for the diversification of the portfolio, we would NOT want the stocks to be related to each other. Mathematically, Pearson’s correlation coefficient (also called Pearson’s R value) between any pair of stocks should be close to 0. The idea behind is simple — suppose your portfolio comprises of the stocks that are highly correlated, then if one stock tumbles, the others might fall too and you’re at the risk of losing all your investment!" }, { "code": null, "e": 9324, "s": 9093, "text": "I selected the aforementioned stocks to perform the correlation analysis. All these stocks are from different segments of Industry and Market cap. You are free to choose the stocks of your interest. the procedure remains the same." }, { "code": null, "e": 9501, "s": 9324, "text": "In previous section we’ve used the pre-downloaded csv file for analysis. In this section, we’ll take the help of Pandas web data reader package to extract the prices of stocks." }, { "code": null, "e": 9844, "s": 9501, "text": "# import packageimport pandas_datareader.data as web# set start and end dates start = datetime.datetime(2018, 2, 15)end = datetime.datetime(2020, 2, 14) # extract the closing price datacombined_df = web.DataReader([‘HDFC.NS’, ‘JINDALSTEL.NS’, ‘JUBLFOOD.NS’,‘SUNPHARMA.NS’, ‘TCS.NS’, ‘^NSEI’],‘yahoo’, start = start, end = end)[‘Adj Close’]" }, { "code": null, "e": 9890, "s": 9844, "text": "Drop null values and display first few rows —" }, { "code": null, "e": 9995, "s": 9890, "text": "# drop null valuescombined_df.dropna(inplace = True, axis = 0)# display first few rowscombined_df.head()" }, { "code": null, "e": 10003, "s": 9995, "text": "Output:" }, { "code": null, "e": 10068, "s": 10003, "text": "(^ NSEI is symbol for National Stock Exchange Index — NIFTY 50 )" }, { "code": null, "e": 10178, "s": 10068, "text": "Next we’ll analyse the correlation between the different stocks in a pair-wise fashion with Seaborn pairplot." }, { "code": null, "e": 10446, "s": 10178, "text": "# store daily returns of all above stocks in a new dataframe pct_chg_df = combined_df.pct_change()*100pct_chg_df.dropna(inplace = True, how = ‘any’, axis = 0)# plotting pairplot import seaborn as snssns.set(style = ‘ticks’, font_scale = 1.25)sns.pairplot(pct_chg_df)" }, { "code": null, "e": 10454, "s": 10446, "text": "Output:" }, { "code": null, "e": 10595, "s": 10454, "text": "Note that the correlation analysis is performed on the daily percentage change(daily returns) of the stock price and not on the stock price." }, { "code": null, "e": 10878, "s": 10595, "text": "If you observe carefully, the plots in the lower triangular area are the same as the plots in the upper triangular area with just axes interchanged. So, analyzing either set of plots would suffice. The diagonal represents the histograms, just like the one seen above for HDFC stock." }, { "code": null, "e": 10888, "s": 10878, "text": "Takeaway:" }, { "code": null, "e": 11032, "s": 10888, "text": "HDFC, Jindal Steel, Jubilant Foods, Sun Pharma and TCS stocks can be included in a portfolio as no two stocks show any significant correlation." }, { "code": null, "e": 11042, "s": 11032, "text": "Drawback:" }, { "code": null, "e": 11331, "s": 11042, "text": "Although the pair plots provide very good visualization of all possible combinations between the bunch of stocks, it doesn’t provide any detailed information like Pearson’s R value or null-hypothesis p value to quantify the correlation. That’s where the joint plot comes into the picture!" }, { "code": null, "e": 11827, "s": 11331, "text": "While Pair plot provides a visual insight into all possible correlations, Seaborn jointplot provides detailed information like Pearson’s R value (Pearson’s correlation coefficient) for each pair of stocks. Pearson’s R value ranges from -1 to 1. Negative value indicates a negative linear relation between the variables, while positive value indicates a positive relationship. Pearson’s R value closer to 1 (or -1) indicates strong correlation, while value closer to 0 indicates weak correlation." }, { "code": null, "e": 11958, "s": 11827, "text": "In addition to Pearson’s R value, joint plot also shows the respective histograms on the edges as well as null hypothesis p-value." }, { "code": null, "e": 12069, "s": 11958, "text": "Here’s an example of a joint plots between the stocks of Sun Pharma vs Jindal Steel and Jindal Steel vs HDFC —" }, { "code": null, "e": 12306, "s": 12069, "text": "from scipy.stats import statssns.jointplot(‘SUNPHARMA.NS’, ‘JINDALSTEL.NS’, pct_chg_df, kind = ‘scatter’).annotate(stats.pearsonr)sns.jointplot(‘JINDALSTEL.NS’, ‘HDFC.NS’, pct_chg_df, kind = ‘scatter’).annotate(stats.pearsonr)plt.show()" }, { "code": null, "e": 12314, "s": 12306, "text": "Output:" }, { "code": null, "e": 12325, "s": 12314, "text": "Takeaways:" }, { "code": null, "e": 12442, "s": 12325, "text": "The Pearson’s R value is 0.24 for Jindal Steel v/s Sun Pharma which is very less. This indicates a weak correlation." }, { "code": null, "e": 12597, "s": 12442, "text": "Similarly, the Pearson’s R value is observed to be 0.29 in case of HDFC v/s Jindal Steel indicating weak correlation between HDFC and Jindal Steel stocks." }, { "code": null, "e": 12755, "s": 12597, "text": "These above results from Joint plots equip us with the numerical figures to ascertain the insights we derived by visually observing the Pair plot previously." }, { "code": null, "e": 12994, "s": 12755, "text": "Beware! having correlation is not the only parameter to determine which stocks to include in an portfolio and which to remove. There are several other factors at play. It’s best to seek advice of the experts and make an informed decision." }, { "code": null, "e": 13561, "s": 12994, "text": "Volatility is one of the most important pillars in financial markets. A stock is said to have high volatility if its value can change dramatically within a short span of time. On other hand, lower volatility means that value of stock tends to be relatively steady over a period of time. These movements are due to several factors including demand and supply, sentiment, corporate actions, greed, and fear, etc. Mathematically, volatility is measured using a statistical measure called ‘standard deviation’, which measures an asset’s departure from its average value." }, { "code": null, "e": 14002, "s": 13561, "text": "We have already calculated the intraday returns (daily returns) of the HDFC stock and several other stocks. Next, we will calculate the 7-day rolling mean(also called moving average) of the daily returns, then compute the standard deviation (which is square root of the variance) and plot the values. Relax, we don’t have to calculate all this manually; Pandas ‘rolling()’ function and ‘std()’ function does the job for us in just one line!" }, { "code": null, "e": 14095, "s": 14002, "text": "HDFC_vol = pct_chg_df[‘HDFC.NS’].rolling(7).std()*np.sqrt(7)HDFC_vol.plot(figsize = (15, 7))" }, { "code": null, "e": 14103, "s": 14095, "text": "Output:" }, { "code": null, "e": 14345, "s": 14103, "text": "Next we’ll see the comparative volatility analysis of HDFC stock with SunPharma stock and NIFTY50 index. Just like above, we compute 7-day rolling mean, and standard deviation, all in a single line of code. Pandas indeed makes our life easy!" }, { "code": null, "e": 14469, "s": 14345, "text": "volatility = pct_chg_df[['HDFC.NS', 'SUNPHARMA.NS', '^NSEI']].rolling(7).std()*np.sqrt(7)volatility.plot(figsize = (15, 7))" }, { "code": null, "e": 14477, "s": 14469, "text": "Output:" }, { "code": null, "e": 14769, "s": 14477, "text": "You can observe that Sun Pharma stock has higher volatility as compared to HDFC stock, while the Nifty index has least volatility. This is expected as Sun Pharma is a mid-cap stock and mid-cap stocks in general tend to have higher volatility as compared to the large-cap stocks such as HDFC." }, { "code": null, "e": 15109, "s": 14769, "text": "Many traders and investors seek out higher volatility investments in order to make higher profits. If a stock does not move, not only it has low volatility, but also it has low gain potential. On the other hand, a stock or other security with a very high volatility level can have tremendous profit potential, but the risk is equally high." }, { "code": null, "e": 15512, "s": 15109, "text": "There is no full-proof strategy that can guarantee profit on your investment. In the real-world, there are a number of factors that traders take into account before making an investment. By using the right strategies and techniques, we can only improve our chances. I am looking forward to introduce some of these strategies & techniques along with demonstration using python in my subsequent articles." }, { "code": null, "e": 15524, "s": 15512, "text": "References:" }, { "code": null, "e": 15590, "s": 15524, "text": "For Data — Yahoo FinanceFor Finance technicalities — Investopedia" }, { "code": null, "e": 15615, "s": 15590, "text": "For Data — Yahoo Finance" }, { "code": null, "e": 15657, "s": 15615, "text": "For Finance technicalities — Investopedia" } ]
LinkedList AddAfter method in C#
Set a LinkedList. int [] num = {1, 2, 3, 4, 5}; LinkedList<int> list = new LinkedList<int>(num); Now add a node at the end using AddLast() method. var newNode = list.AddLast(20); To add a node after the above added node, use the AddAfter() method. list.AddAfter(newNode, 30); Live Demo using System; using System.Collections.Generic; class Demo { static void Main() { int [] num = {1, 2, 3, 4, 5}; LinkedList<int> list = new LinkedList<int>(num); foreach (var n in list) { Console.WriteLine(n); } // adding a node at the end var newNode = list.AddLast(20); // adding a new node after the node added above list.AddAfter(newNode, 30); Console.WriteLine("LinkedList after adding new nodes..."); foreach (var n in list) { Console.WriteLine(n); } } } 1 2 3 4 5 LinkedList after adding new nodes... 1 2 3 4 5 20 30
[ { "code": null, "e": 1080, "s": 1062, "text": "Set a LinkedList." }, { "code": null, "e": 1159, "s": 1080, "text": "int [] num = {1, 2, 3, 4, 5};\nLinkedList<int> list = new LinkedList<int>(num);" }, { "code": null, "e": 1209, "s": 1159, "text": "Now add a node at the end using AddLast() method." }, { "code": null, "e": 1241, "s": 1209, "text": "var newNode = list.AddLast(20);" }, { "code": null, "e": 1310, "s": 1241, "text": "To add a node after the above added node, use the AddAfter() method." }, { "code": null, "e": 1338, "s": 1310, "text": "list.AddAfter(newNode, 30);" }, { "code": null, "e": 1349, "s": 1338, "text": " Live Demo" }, { "code": null, "e": 1899, "s": 1349, "text": "using System;\nusing System.Collections.Generic;\nclass Demo {\n static void Main() {\n int [] num = {1, 2, 3, 4, 5};\n LinkedList<int> list = new LinkedList<int>(num);\n foreach (var n in list) {\n Console.WriteLine(n);\n }\n // adding a node at the end\n var newNode = list.AddLast(20);\n // adding a new node after the node added above\n list.AddAfter(newNode, 30);\n Console.WriteLine(\"LinkedList after adding new nodes...\");\n foreach (var n in list) {\n Console.WriteLine(n);\n }\n }\n}" }, { "code": null, "e": 1962, "s": 1899, "text": "1\n2\n3\n4\n5\nLinkedList after adding new nodes...\n1\n2\n3\n4\n5\n20\n30" } ]
Java - toRadians() Method
The method converts the argument value to radians. double toRadians(double d) Here is the detail of parameters − d − A double data type. d − A double data type. This method returns a double value. public class Test { public static void main(String args[]) { double x = 45.0; double y = 30.0; System.out.println( Math.toRadians(x) ); System.out.println( Math.toRadians(y) ); } } This will produce the following result − 0.7853981633974483 0.5235987755982988 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": 2428, "s": 2377, "text": "The method converts the argument value to radians." }, { "code": null, "e": 2456, "s": 2428, "text": "double toRadians(double d)\n" }, { "code": null, "e": 2491, "s": 2456, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2515, "s": 2491, "text": "d − A double data type." }, { "code": null, "e": 2539, "s": 2515, "text": "d − A double data type." }, { "code": null, "e": 2575, "s": 2539, "text": "This method returns a double value." }, { "code": null, "e": 2789, "s": 2575, "text": "public class Test { \n\n public static void main(String args[]) {\n double x = 45.0;\n double y = 30.0;\n\n System.out.println( Math.toRadians(x) );\n System.out.println( Math.toRadians(y) );\n }\n}" }, { "code": null, "e": 2830, "s": 2789, "text": "This will produce the following result −" }, { "code": null, "e": 2869, "s": 2830, "text": "0.7853981633974483\n0.5235987755982988\n" }, { "code": null, "e": 2902, "s": 2869, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 2918, "s": 2902, "text": " Malhar Lathkar" }, { "code": null, "e": 2951, "s": 2918, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 2967, "s": 2951, "text": " Malhar Lathkar" }, { "code": null, "e": 3002, "s": 2967, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3016, "s": 3002, "text": " Anadi Sharma" }, { "code": null, "e": 3050, "s": 3016, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3064, "s": 3050, "text": " Tushar Kale" }, { "code": null, "e": 3101, "s": 3064, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3116, "s": 3101, "text": " Monica Mittal" }, { "code": null, "e": 3149, "s": 3116, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3168, "s": 3149, "text": " Arnab Chakraborty" }, { "code": null, "e": 3175, "s": 3168, "text": " Print" }, { "code": null, "e": 3186, "s": 3175, "text": " Add Notes" } ]
Simple Dashboards Just with Jupyter | by Michael Keith | Towards Data Science
There is such a thing as the right tool for the job. When you or your organization have access to expensive visualization software, such as Tableau, Power BI, or Domo, every problem looks like a nail and your program is the hammer. If you are a data analyst for such an organization, you will inevitably spend countless hours on one of these dashboards and imbed every conceivable answer to any question a senior decision-maker of the company could have, just to be greeted with an email a week later containing some request that makes it obvious that no one is even using the dashboard’s most basic functionality. I cannot pretend to know why some people (especially upper management) don’t enjoy the beauty of an interactive Tableau application with the bar charts, leaflets, and line graphs all synchronized together in perfect harmony, but it might be that people who don’t deal with data all day don’t naturally know how to navigate such a thing and don’t want to spend any valuable time trying to figure it out. Instead of dealing with all that hassle, consider using Jupyter Lab, together with basic Python and markdown, to create simple visualizations, exported to an HTML or PDF document that get straight to the point, require basically no cost to maintain, and can be cobbled together in a couple of hours. I’m not contesting that such a thing is appropriate for all situations, but it can be an arrow in the quiver for when whoever is needing the dashboard would be fine with a quick overview of the data rather than a perfect mosaic of visual aids. I’ve found that many higher-ups can more readily access something so simple and appreciate how few resources have to be dedicated to setting up and maintaining it. github.com To get started, I suggest using Anaconda to run Jupyter Lab. There are many resources that describe how to do this — I particularly like the guide from pandas. I personally use the 64-Bit Graphical Installer Anaconda distribution (click here to download) for Windows to run most of my Python applications, but understand there are other ways to go about this. Use whatever makes most sense for your situation. After Anaconda is installed, you should be able to run Jupyter Lab by opening the Anaconda Navigator and selecting Launch in the JupyterLab application box. You can also start it by typing “jupyter lab” in Anaconda Prompt. Next, you will need to install Nbconvert. I recommend reading the entire documentation in case you run into trouble with my summary. To install it, use this command in Anaconda Prompt: conda install nbconvert To export your final product to an HTML document, you need to install Pandoc. For Windows, the installer is recommended, but there are other installation methods. You can find all of that information here. I prefer exporting results to HTML only — it is fast and the end product looks great. But there are other export options you can explore, including PDF and Latex. The installation for these tools is more complicated. Again, all of that can be found in the Nbconvert documentation. Finally, let’s import data. I would imagine this means setting up a SQL connection to a data warehouse for most users (it’s what it usually means for me), but this could also mean importing the data from a shared drive, API, etc. The important part here is that the import be completed without warnings in the code. Warnings won’t stop your code from working, but they will export to the final HTML document unless you clear them from your notebook manually. This is true for every coding block you run. For this example, I will be using COVID-19 vaccination data available through Our World in Data on GitHub. Here is the list of needed imports: import datetimeimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport seaborn as snsfrom IPython.core.display import display, HTMLpd.options.display.max_rows = None # to print tablespd.options.display.max_columns = None # to print tablesdata_state = pd.read_csv('us_state_vaccinations.csv')data_manufac = pd.read_csv('vaccinations-by-manufacturer.csv') Now that we have Jupyter Lab installed with all of the necessary add-ons and we’ve read in the data, we can begin making data visualizations. For this example, I will build three graphics and include two tables in the output. I will also use Markdown on Jupyter for easy navigation between sections. For this graphic, I use a line chart with three statistics represented: total vaccines distributed, people who have received one does, and people who are fully vaccinated over time from 12/15/2020 to present (4/15/2021). This is a very simple visualization with the only potentially challenging part being placing the last data point at the end of each line to give the total figures for the respective groups using the matplotlib text() function. The Python code is given below. First, to prepare the data: Then, to build the chart: The output looks like this: Next, a chart to represent the performance by U.S. state/territory. The first thought for many to represent these statistics would be a leaflet chart, which is basically a regional map of the area you are charting with different areas shaded to represent different densities. However, those can be difficult to produce in this scenario and also are not as straightforward to obtain the pertinent comparisons as a simple heat map. Let’s see how the heat map looks. We can use the data prepared for the previous chart for this one. The code to create the visual aid: And the output: We can also add in a table with this information, as well as total vaccination numbers for each of these states. The code for that is included in the notebook linked in GitHub above. Finally, let’s breakdown the data by manufacturer. For this chart, we can try something more advanced: a stacked bar chart overlaid with a shaded line representing the 7-day rolling average. It can be tricky to get the dates to align between the bar graph and line plot as the underlying matplotlib functions default to different date representations for the two charts. The code to prepare the data is given below: The code to make the visualization: The output: One thing that surprised me was to see how few Johnson & Johnson vaccines are being administered. Considering that is a one-dose vaccine, I expected it to be more popular. Even with simple visualizations, interesting insights from data can be revealed. Now that we have our three visualizations, we can export the notebook to an HTML document. There is a way to theoretically make these charts all interactive by using the `%matplotlib widget` command in the code, but I haven’t been able to get that to work on my system. Any tips in the comments would be welcome. Regardless, the export command involves using Anaconda Prompt to run two commands: cd local/path/to/jupyter/notebookjupyter nbconvert --to html --no-input dashboard.ipynb This will place an HTML document in the same local directory as your notebook. For the complete code used in this example, see here. To refresh the analysis with new data, you will just have to make sure you’ve established a live feed to the data (in this example, I used flat files that would have to be redownloaded). It is then as easy as selecting ‘kernel →Restart Kernel and Run All Cells’ in your browser with the Jupyter Notebook open. Confirm that you want to restart the kernel, then rerun the commands given in the prior section on Anaconda Prompt, and you will have fresh output that you can email to whoever needs it. This process is much simpler than building state-of-the-art dashboards and can be an effective solution when you need something simple and you need it quickly.
[ { "code": null, "e": 1190, "s": 172, "text": "There is such a thing as the right tool for the job. When you or your organization have access to expensive visualization software, such as Tableau, Power BI, or Domo, every problem looks like a nail and your program is the hammer. If you are a data analyst for such an organization, you will inevitably spend countless hours on one of these dashboards and imbed every conceivable answer to any question a senior decision-maker of the company could have, just to be greeted with an email a week later containing some request that makes it obvious that no one is even using the dashboard’s most basic functionality. I cannot pretend to know why some people (especially upper management) don’t enjoy the beauty of an interactive Tableau application with the bar charts, leaflets, and line graphs all synchronized together in perfect harmony, but it might be that people who don’t deal with data all day don’t naturally know how to navigate such a thing and don’t want to spend any valuable time trying to figure it out." }, { "code": null, "e": 1898, "s": 1190, "text": "Instead of dealing with all that hassle, consider using Jupyter Lab, together with basic Python and markdown, to create simple visualizations, exported to an HTML or PDF document that get straight to the point, require basically no cost to maintain, and can be cobbled together in a couple of hours. I’m not contesting that such a thing is appropriate for all situations, but it can be an arrow in the quiver for when whoever is needing the dashboard would be fine with a quick overview of the data rather than a perfect mosaic of visual aids. I’ve found that many higher-ups can more readily access something so simple and appreciate how few resources have to be dedicated to setting up and maintaining it." }, { "code": null, "e": 1909, "s": 1898, "text": "github.com" }, { "code": null, "e": 2319, "s": 1909, "text": "To get started, I suggest using Anaconda to run Jupyter Lab. There are many resources that describe how to do this — I particularly like the guide from pandas. I personally use the 64-Bit Graphical Installer Anaconda distribution (click here to download) for Windows to run most of my Python applications, but understand there are other ways to go about this. Use whatever makes most sense for your situation." }, { "code": null, "e": 2476, "s": 2319, "text": "After Anaconda is installed, you should be able to run Jupyter Lab by opening the Anaconda Navigator and selecting Launch in the JupyterLab application box." }, { "code": null, "e": 2542, "s": 2476, "text": "You can also start it by typing “jupyter lab” in Anaconda Prompt." }, { "code": null, "e": 2727, "s": 2542, "text": "Next, you will need to install Nbconvert. I recommend reading the entire documentation in case you run into trouble with my summary. To install it, use this command in Anaconda Prompt:" }, { "code": null, "e": 2751, "s": 2727, "text": "conda install nbconvert" }, { "code": null, "e": 2957, "s": 2751, "text": "To export your final product to an HTML document, you need to install Pandoc. For Windows, the installer is recommended, but there are other installation methods. You can find all of that information here." }, { "code": null, "e": 3238, "s": 2957, "text": "I prefer exporting results to HTML only — it is fast and the end product looks great. But there are other export options you can explore, including PDF and Latex. The installation for these tools is more complicated. Again, all of that can be found in the Nbconvert documentation." }, { "code": null, "e": 3742, "s": 3238, "text": "Finally, let’s import data. I would imagine this means setting up a SQL connection to a data warehouse for most users (it’s what it usually means for me), but this could also mean importing the data from a shared drive, API, etc. The important part here is that the import be completed without warnings in the code. Warnings won’t stop your code from working, but they will export to the final HTML document unless you clear them from your notebook manually. This is true for every coding block you run." }, { "code": null, "e": 3849, "s": 3742, "text": "For this example, I will be using COVID-19 vaccination data available through Our World in Data on GitHub." }, { "code": null, "e": 3885, "s": 3849, "text": "Here is the list of needed imports:" }, { "code": null, "e": 4292, "s": 3885, "text": "import datetimeimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport seaborn as snsfrom IPython.core.display import display, HTMLpd.options.display.max_rows = None # to print tablespd.options.display.max_columns = None # to print tablesdata_state = pd.read_csv('us_state_vaccinations.csv')data_manufac = pd.read_csv('vaccinations-by-manufacturer.csv')" }, { "code": null, "e": 4434, "s": 4292, "text": "Now that we have Jupyter Lab installed with all of the necessary add-ons and we’ve read in the data, we can begin making data visualizations." }, { "code": null, "e": 4592, "s": 4434, "text": "For this example, I will build three graphics and include two tables in the output. I will also use Markdown on Jupyter for easy navigation between sections." }, { "code": null, "e": 5072, "s": 4592, "text": "For this graphic, I use a line chart with three statistics represented: total vaccines distributed, people who have received one does, and people who are fully vaccinated over time from 12/15/2020 to present (4/15/2021). This is a very simple visualization with the only potentially challenging part being placing the last data point at the end of each line to give the total figures for the respective groups using the matplotlib text() function. The Python code is given below." }, { "code": null, "e": 5100, "s": 5072, "text": "First, to prepare the data:" }, { "code": null, "e": 5126, "s": 5100, "text": "Then, to build the chart:" }, { "code": null, "e": 5154, "s": 5126, "text": "The output looks like this:" }, { "code": null, "e": 5618, "s": 5154, "text": "Next, a chart to represent the performance by U.S. state/territory. The first thought for many to represent these statistics would be a leaflet chart, which is basically a regional map of the area you are charting with different areas shaded to represent different densities. However, those can be difficult to produce in this scenario and also are not as straightforward to obtain the pertinent comparisons as a simple heat map. Let’s see how the heat map looks." }, { "code": null, "e": 5719, "s": 5618, "text": "We can use the data prepared for the previous chart for this one. The code to create the visual aid:" }, { "code": null, "e": 5735, "s": 5719, "text": "And the output:" }, { "code": null, "e": 5918, "s": 5735, "text": "We can also add in a table with this information, as well as total vaccination numbers for each of these states. The code for that is included in the notebook linked in GitHub above." }, { "code": null, "e": 6289, "s": 5918, "text": "Finally, let’s breakdown the data by manufacturer. For this chart, we can try something more advanced: a stacked bar chart overlaid with a shaded line representing the 7-day rolling average. It can be tricky to get the dates to align between the bar graph and line plot as the underlying matplotlib functions default to different date representations for the two charts." }, { "code": null, "e": 6334, "s": 6289, "text": "The code to prepare the data is given below:" }, { "code": null, "e": 6370, "s": 6334, "text": "The code to make the visualization:" }, { "code": null, "e": 6382, "s": 6370, "text": "The output:" }, { "code": null, "e": 6635, "s": 6382, "text": "One thing that surprised me was to see how few Johnson & Johnson vaccines are being administered. Considering that is a one-dose vaccine, I expected it to be more popular. Even with simple visualizations, interesting insights from data can be revealed." }, { "code": null, "e": 7031, "s": 6635, "text": "Now that we have our three visualizations, we can export the notebook to an HTML document. There is a way to theoretically make these charts all interactive by using the `%matplotlib widget` command in the code, but I haven’t been able to get that to work on my system. Any tips in the comments would be welcome. Regardless, the export command involves using Anaconda Prompt to run two commands:" }, { "code": null, "e": 7119, "s": 7031, "text": "cd local/path/to/jupyter/notebookjupyter nbconvert --to html --no-input dashboard.ipynb" }, { "code": null, "e": 7252, "s": 7119, "text": "This will place an HTML document in the same local directory as your notebook. For the complete code used in this example, see here." } ]
Hadoop - HDFS Operations
Initially you have to format the configured HDFS file system, open namenode (HDFS server), and execute the following command. $ hadoop namenode -format After formatting the HDFS, start the distributed file system. The following command will start the namenode as well as the data nodes as cluster. $ start-dfs.sh After loading the information in the server, we can find the list of files in a directory, status of a file, using ‘ls’. Given below is the syntax of ls that you can pass to a directory or a filename as an argument. $ $HADOOP_HOME/bin/hadoop fs -ls <args> Assume we have data in the file called file.txt in the local system which is ought to be saved in the hdfs file system. Follow the steps given below to insert the required file in the Hadoop file system. You have to create an input directory. $ $HADOOP_HOME/bin/hadoop fs -mkdir /user/input Transfer and store a data file from local systems to the Hadoop file system using the put command. $ $HADOOP_HOME/bin/hadoop fs -put /home/file.txt /user/input You can verify the file using ls command. $ $HADOOP_HOME/bin/hadoop fs -ls /user/input Assume we have a file in HDFS called outfile. Given below is a simple demonstration for retrieving the required file from the Hadoop file system. Initially, view the data from HDFS using cat command. $ $HADOOP_HOME/bin/hadoop fs -cat /user/output/outfile Get the file from HDFS to the local file system using get command. $ $HADOOP_HOME/bin/hadoop fs -get /user/output/ /home/hadoop_tp/ You can shut down the HDFS by using the following command. $ stop-dfs.sh 39 Lectures 2.5 hours Arnab Chakraborty 65 Lectures 6 hours Arnab Chakraborty 12 Lectures 1 hours Pranjal Srivastava 24 Lectures 6.5 hours Pari Margu 89 Lectures 11.5 hours TELCOMA Global 43 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 1977, "s": 1851, "text": "Initially you have to format the configured HDFS file system, open namenode (HDFS server), and execute the following command." }, { "code": null, "e": 2005, "s": 1977, "text": "$ hadoop namenode -format \n" }, { "code": null, "e": 2151, "s": 2005, "text": "After formatting the HDFS, start the distributed file system. The following command will start the namenode as well as the data nodes as cluster." }, { "code": null, "e": 2168, "s": 2151, "text": "$ start-dfs.sh \n" }, { "code": null, "e": 2384, "s": 2168, "text": "After loading the information in the server, we can find the list of files in a directory, status of a file, using ‘ls’. Given below is the syntax of ls that you can pass to a directory or a filename as an argument." }, { "code": null, "e": 2425, "s": 2384, "text": "$ $HADOOP_HOME/bin/hadoop fs -ls <args>\n" }, { "code": null, "e": 2629, "s": 2425, "text": "Assume we have data in the file called file.txt in the local system which is ought to be saved in the hdfs file system. Follow the steps given below to insert the required file in the Hadoop file system." }, { "code": null, "e": 2668, "s": 2629, "text": "You have to create an input directory." }, { "code": null, "e": 2718, "s": 2668, "text": "$ $HADOOP_HOME/bin/hadoop fs -mkdir /user/input \n" }, { "code": null, "e": 2817, "s": 2718, "text": "Transfer and store a data file from local systems to the Hadoop file system using the put command." }, { "code": null, "e": 2880, "s": 2817, "text": "$ $HADOOP_HOME/bin/hadoop fs -put /home/file.txt /user/input \n" }, { "code": null, "e": 2922, "s": 2880, "text": "You can verify the file using ls command." }, { "code": null, "e": 2969, "s": 2922, "text": "$ $HADOOP_HOME/bin/hadoop fs -ls /user/input \n" }, { "code": null, "e": 3115, "s": 2969, "text": "Assume we have a file in HDFS called outfile. Given below is a simple demonstration for retrieving the required file from the Hadoop file system." }, { "code": null, "e": 3169, "s": 3115, "text": "Initially, view the data from HDFS using cat command." }, { "code": null, "e": 3226, "s": 3169, "text": "$ $HADOOP_HOME/bin/hadoop fs -cat /user/output/outfile \n" }, { "code": null, "e": 3293, "s": 3226, "text": "Get the file from HDFS to the local file system using get command." }, { "code": null, "e": 3360, "s": 3293, "text": "$ $HADOOP_HOME/bin/hadoop fs -get /user/output/ /home/hadoop_tp/ \n" }, { "code": null, "e": 3419, "s": 3360, "text": "You can shut down the HDFS by using the following command." }, { "code": null, "e": 3435, "s": 3419, "text": "$ stop-dfs.sh \n" }, { "code": null, "e": 3470, "s": 3435, "text": "\n 39 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3489, "s": 3470, "text": " Arnab Chakraborty" }, { "code": null, "e": 3522, "s": 3489, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 3541, "s": 3522, "text": " Arnab Chakraborty" }, { "code": null, "e": 3574, "s": 3541, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 3594, "s": 3574, "text": " Pranjal Srivastava" }, { "code": null, "e": 3629, "s": 3594, "text": "\n 24 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3641, "s": 3629, "text": " Pari Margu" }, { "code": null, "e": 3677, "s": 3641, "text": "\n 89 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3693, "s": 3677, "text": " TELCOMA Global" }, { "code": null, "e": 3728, "s": 3693, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3746, "s": 3728, "text": " Bigdata Engineer" }, { "code": null, "e": 3753, "s": 3746, "text": " Print" }, { "code": null, "e": 3764, "s": 3753, "text": " Add Notes" } ]
\mathscr - Tex Command
\mathscr - Used to turn on script typestyle for uppercase letters. If lowercase script letters are not available, then they are typeset in a roman typestyle. { \mathscr #1 } \mathscr command is used to turn on script typestyle for uppercase letters. If lowercase script letters are not available, then they are typeset in a roman typestyle. \mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ} ABCDEFGHIJKLMNOPQRSTUVWXYZ \mathscr{0123456789} 0123456789 \mathscr{abcdefghijklmnopqrstuvwxyz} abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz \mathscr{AB}AB ABAB \mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ} ABCDEFGHIJKLMNOPQRSTUVWXYZ \mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ} \mathscr{0123456789} 0123456789 \mathscr{0123456789} \mathscr{abcdefghijklmnopqrstuvwxyz} abcdefghijklmnopqrstuvwxyz \mathscr{abcdefghijklmnopqrstuvwxyz} abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz \mathscr{AB}AB ABAB \mathscr{AB}AB 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8144, "s": 7986, "text": "\\mathscr - Used to turn on script typestyle for uppercase letters. If lowercase script letters are not available, then they are typeset in a roman typestyle." }, { "code": null, "e": 8160, "s": 8144, "text": "{ \\mathscr #1 }" }, { "code": null, "e": 8327, "s": 8160, "text": "\\mathscr command is used to turn on script typestyle for uppercase letters. If lowercase script letters are not available, then they are typeset in a roman typestyle." }, { "code": null, "e": 8578, "s": 8327, "text": "\n\\mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ}\n\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n\n\n\\mathscr{0123456789}\n\n0123456789\n\n\n\\mathscr{abcdefghijklmnopqrstuvwxyz}\n\nabcdefghijklmnopqrstuvwxyz\n\n\nabcdefghijklmnopqrstuvwxyz\n\nabcdefghijklmnopqrstuvwxyz\n\n\n\\mathscr{AB}AB\n\nABAB\n\n\n" }, { "code": null, "e": 8645, "s": 8578, "text": "\\mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ}\n\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n\n" }, { "code": null, "e": 8682, "s": 8645, "text": "\\mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ}" }, { "code": null, "e": 8717, "s": 8682, "text": "\\mathscr{0123456789}\n\n0123456789\n\n" }, { "code": null, "e": 8738, "s": 8717, "text": "\\mathscr{0123456789}" }, { "code": null, "e": 8805, "s": 8738, "text": "\\mathscr{abcdefghijklmnopqrstuvwxyz}\n\nabcdefghijklmnopqrstuvwxyz\n\n" }, { "code": null, "e": 8842, "s": 8805, "text": "\\mathscr{abcdefghijklmnopqrstuvwxyz}" }, { "code": null, "e": 8899, "s": 8842, "text": "abcdefghijklmnopqrstuvwxyz\n\nabcdefghijklmnopqrstuvwxyz\n\n" }, { "code": null, "e": 8926, "s": 8899, "text": "abcdefghijklmnopqrstuvwxyz" }, { "code": null, "e": 8949, "s": 8926, "text": "\\mathscr{AB}AB\n\nABAB\n\n" }, { "code": null, "e": 8964, "s": 8949, "text": "\\mathscr{AB}AB" }, { "code": null, "e": 8996, "s": 8964, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 9009, "s": 8996, "text": " Ashraf Said" }, { "code": null, "e": 9042, "s": 9009, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 9055, "s": 9042, "text": " Ashraf Said" }, { "code": null, "e": 9087, "s": 9055, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 9123, "s": 9087, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 9158, "s": 9123, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9175, "s": 9158, "text": " Mohammad Nauman" }, { "code": null, "e": 9208, "s": 9175, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9222, "s": 9208, "text": " Daniel Stern" }, { "code": null, "e": 9254, "s": 9222, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 9269, "s": 9254, "text": " Nishant Kumar" }, { "code": null, "e": 9276, "s": 9269, "text": " Print" }, { "code": null, "e": 9287, "s": 9276, "text": " Add Notes" } ]
C++ Program to Generate Randomized Sequence of Given Range of Numbers
At first let us discuss about the rand() function. rand() function is a predefined method of C++. It is declared in <stdlib.h> header file. rand() is used to generate random number within a range. Here min_n is the minimum range of the random numbers and max_n is the maximum range of the numbers. So rand() will return the random numbers between min_n to (max_n – 1) inclusive of the limit values. Here if we mention lower and upper limits as 1 and 100 respectively, then rand() will return values from 1 to (100 – 1). i.e. from 1 to 99. Begin Declare max_n to the integer datatype. Initialize max_n = 100. Declare min_n to the integer datatype. Initialize min_n = 1. Declare new_n to the integer datatype. Declare i of integer datatype. Print “The random number is:”. for (i = 0; i < 10; i++) new_n = ((rand() % (max_n + 1 - min_n)) + min_n) Print the value of new_n. End. #include <iostream> #include <stdlib.h> using namespace std; int main() { int max_n = 100; int min_n = 1; int new_n; int i; cout<<"The random number is: \n"; for (i = 0; i < 10; i++) { new_n = ((rand() % (max_n + 1 - min_n)) + min_n); //rand() returns random decimal number. cout<<new_n<<endl; } return 0; } The random number is: 42 68 35 1 70 25 79 59 63 65
[ { "code": null, "e": 1601, "s": 1062, "text": "At first let us discuss about the rand() function. rand() function is a predefined method of C++. It is declared in <stdlib.h> header file. rand() is used to generate random number within a range. Here min_n is the minimum range of the random numbers and max_n is the maximum range of the numbers. So rand() will return the random numbers between min_n to (max_n – 1) inclusive of the limit values. Here if we mention lower and upper limits as 1 and 100 respectively, then rand() will return values from 1 to (100 – 1). i.e. from 1 to 99." }, { "code": null, "e": 1976, "s": 1601, "text": "Begin\n Declare max_n to the integer datatype.\n Initialize max_n = 100.\n Declare min_n to the integer datatype.\n Initialize min_n = 1.\n Declare new_n to the integer datatype.\n Declare i of integer datatype.\n Print “The random number is:”.\n for (i = 0; i < 10; i++)\n new_n = ((rand() % (max_n + 1 - min_n)) + min_n)\n Print the value of new_n.\nEnd." }, { "code": null, "e": 2326, "s": 1976, "text": "#include <iostream>\n#include <stdlib.h>\nusing namespace std;\nint main() {\n int max_n = 100;\n int min_n = 1;\n int new_n;\n int i;\n cout<<\"The random number is: \\n\";\n for (i = 0; i < 10; i++) {\n new_n = ((rand() % (max_n + 1 - min_n)) + min_n);\n //rand() returns random decimal number.\n cout<<new_n<<endl;\n }\n return 0;\n}" }, { "code": null, "e": 2377, "s": 2326, "text": "The random number is:\n42\n68\n35\n1\n70\n25\n79\n59\n63\n65" } ]
Part II: All you need to know about Regular Expressions | by Ria Kulshrestha | Towards Data Science
Assuming you know what Regular Expressions are (in case you don’t, check out Part1 of this tutorial for a quick overview) we’ll now learn how to use them in Python. :) The ‘re’ module provides an interface to the regular expression engine, and allows us to compile REs into objects and then perform matches with them. We’ll start with importing the module. Then we will combine a regular expression by passing it as a string and turn it into a pattern object. >>> import re>>> pat_obj = re.compile('[a-z]+')>>> print(pat_obj)re.compile('[a-z]+') match(): Determine if the RE matches at the beginning of the string. >>> m = pat_obj.match('helloworld')>>> print(m)<_sre.SRE_Match object; span=(0, 10), match='helloworld'>#Note how it doesn't take into account white spaces.>>> m = pat_obj.match('hello world')>>> print(m)<_sre.SRE_Match object; span=(0, 5), match='hello'># Note that it is case-sensitive.>>> m = pat_obj.match('Helloworld')>>> print(m)None#To ignore case>>> pat_obj = re.compile('[a-z]+', re.IGNORECASE)>>> m = pat_obj.match('Helloworld')>>> print(m)<_sre.SRE_Match object; span=(0, 10), match='Helloworld'> search(): Scan through a string, looking for any location where this RE matches. #Note how it only prints the first match>>> s = pat_obj.search('Hello World!')>>> print(s)<_sre.SRE_Match object; span=(1, 5), match='ello'> To print all the matches, findall(): Find all substrings where the RE matches and returns them as a list. >>> s = pat_obj.findall('Hello World!')>>> print(s)<_sre.SRE_Match object; span=(1, 5), match='ello'>['ello', 'orld']#To find all the numbers in a string>>> pat_obj_num = re.compile(r'\d+')>>> pat_obj_num.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')['12', '11', '10'] group(): Returns the string matched by the RE. Because honestly, that’s what you’re interested in. Ain’t nobody got time for all that information. #Using group with search>>> s = pat_obj.search('Hello World!')>>> print(s)<_sre.SRE_Match object; span=(1, 5), match='ello'>>>> print(s.group())ello#Using group with match>>> m = pat_obj.match("hello world")>>> print(m)<_sre.SRE_Match object; span=(0, 5), match='hello'>>>> print(m.group())hello#Using group with findall>>> m = pat_obj.findall("hello world")>>> print(m)['hello', 'world']>>> print(m.group())Error! span(): Returns a tuple containing the (start, end) positions of the match.start(), end(): Returns the starting and ending position of the match respectively. >>> pat_obj = re.compile('[a-z]+', re.IGNORECASE)>>> m = pat_obj.match('Helloworld')>>> print(m)<_sre.SRE_Match object; span=(0, 10), match='Helloworld'>>>> print(m.start())0>>> print(m.end())10>>> print(m.span())(0, 10) Groups are marked by the ( )meta-characters. They group together the expressions contained inside them, and you can repeat the contents of a group with a repeating qualifier, such as *, +, ? or {m, n}.Groups are numbered starting with 0. Group 0 is always present; it’s the whole RE, so match object methods all have group 0 as their default argument. Subgroups are numbered from left to right, from 1 upward. Groups can be nested; to determine the number, just count the opening parenthesis characters, going from left to right. >>> pat_obj_group = re.compile('(a(b)c(d))e')>>> m = pat_obj_group.match('abcde')>>> print(m)<_sre.SRE_Match object; span=(0, 5), match='abcde'>#Note m.group(0) matches the same regex as m.match()>>> print(m.group(0))abcde>>> print(m.group(1))abcd#Note the number is determined left to right>>> print(m.group(2))b>>> print(m.group(3))d# Note that multiple arguments can be passes to group()>>> print(m.group(2,1,3))('b', 'abcd', 'd') groups(): returns a tuple containing the strings for all the subgroups, from 1 up to however many there are. >>> print(m.groups())('abcd', 'b', 'd') sub(): Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, the string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Empty matches for the pattern are replaced only when not adjacent to a previously empty match. >>> print(re.sub('x','-','abxd'))ab-d>>> print(re.sub('ab*','-','abxd'))-xd>>> print(re.sub('x*','-','abxd'))-a-b-d- The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Though passing Regular Expressions helps in keeping things simple, it has one disadvantage. The backslash character (‘\’) is used to allow special characters to be used without invoking their special meaning which conflicts with Python’s usage of the same character in string literals where it is used to interpret the character following it differently. For example, ’n’ by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character. Ah oh! Let’s say you want to write a RE that matches the string ‘\section’, which might be found in a LaTeX file.We’ll start with the desired string to be matched. Next, we must escape any backslashes and other metacharacters by preceding them with a backslash, resulting in the string ‘\\section’. The resulting string that must be passed to re.compil() must be ‘\\section’. However, to express this as a Python string literal, both backslashes must be escaped again, resulting in the string ‘\\\\section’. In short, to match a literal backslash, one has to write ‘\\\\’ as the RE string, because the regular expression must be \\, and each backslash must be expressed as \\ inside a regular Python string literal. The solution is to use Python’s raw string notation for regular expressions; backslashes are not handled in any special way in a string literal prefixed with ‘r’, so r‘\n’ is a two-character string containing ‘\’ and ‘n’, while ‘\n’ is a one-character string containing a newline. Regular string and corresponding Raw string "ab*" -> r"ab*""\\\\section" -> r"\\section""\\w+\\s+\\1" -> r"\w+\s+\1" Regexone Visualizing tool RegexTips Learning Git in Under 8 minutes! I‘m glad you made it till the end of this article. 🎉I hope your reading experience was as enriching as the one I had writing this. 💖 Do check out my other articles here. If you want to reach out to me, my medium of choice would be Twitter.
[ { "code": null, "e": 339, "s": 171, "text": "Assuming you know what Regular Expressions are (in case you don’t, check out Part1 of this tutorial for a quick overview) we’ll now learn how to use them in Python. :)" }, { "code": null, "e": 489, "s": 339, "text": "The ‘re’ module provides an interface to the regular expression engine, and allows us to compile REs into objects and then perform matches with them." }, { "code": null, "e": 631, "s": 489, "text": "We’ll start with importing the module. Then we will combine a regular expression by passing it as a string and turn it into a pattern object." }, { "code": null, "e": 717, "s": 631, "text": ">>> import re>>> pat_obj = re.compile('[a-z]+')>>> print(pat_obj)re.compile('[a-z]+')" }, { "code": null, "e": 786, "s": 717, "text": "match(): Determine if the RE matches at the beginning of the string." }, { "code": null, "e": 1294, "s": 786, "text": ">>> m = pat_obj.match('helloworld')>>> print(m)<_sre.SRE_Match object; span=(0, 10), match='helloworld'>#Note how it doesn't take into account white spaces.>>> m = pat_obj.match('hello world')>>> print(m)<_sre.SRE_Match object; span=(0, 5), match='hello'># Note that it is case-sensitive.>>> m = pat_obj.match('Helloworld')>>> print(m)None#To ignore case>>> pat_obj = re.compile('[a-z]+', re.IGNORECASE)>>> m = pat_obj.match('Helloworld')>>> print(m)<_sre.SRE_Match object; span=(0, 10), match='Helloworld'>" }, { "code": null, "e": 1375, "s": 1294, "text": "search(): Scan through a string, looking for any location where this RE matches." }, { "code": null, "e": 1516, "s": 1375, "text": "#Note how it only prints the first match>>> s = pat_obj.search('Hello World!')>>> print(s)<_sre.SRE_Match object; span=(1, 5), match='ello'>" }, { "code": null, "e": 1622, "s": 1516, "text": "To print all the matches, findall(): Find all substrings where the RE matches and returns them as a list." }, { "code": null, "e": 1915, "s": 1622, "text": ">>> s = pat_obj.findall('Hello World!')>>> print(s)<_sre.SRE_Match object; span=(1, 5), match='ello'>['ello', 'orld']#To find all the numbers in a string>>> pat_obj_num = re.compile(r'\\d+')>>> pat_obj_num.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')['12', '11', '10']" }, { "code": null, "e": 2062, "s": 1915, "text": "group(): Returns the string matched by the RE. Because honestly, that’s what you’re interested in. Ain’t nobody got time for all that information." }, { "code": null, "e": 2479, "s": 2062, "text": "#Using group with search>>> s = pat_obj.search('Hello World!')>>> print(s)<_sre.SRE_Match object; span=(1, 5), match='ello'>>>> print(s.group())ello#Using group with match>>> m = pat_obj.match(\"hello world\")>>> print(m)<_sre.SRE_Match object; span=(0, 5), match='hello'>>>> print(m.group())hello#Using group with findall>>> m = pat_obj.findall(\"hello world\")>>> print(m)['hello', 'world']>>> print(m.group())Error!" }, { "code": null, "e": 2638, "s": 2479, "text": "span(): Returns a tuple containing the (start, end) positions of the match.start(), end(): Returns the starting and ending position of the match respectively." }, { "code": null, "e": 2859, "s": 2638, "text": ">>> pat_obj = re.compile('[a-z]+', re.IGNORECASE)>>> m = pat_obj.match('Helloworld')>>> print(m)<_sre.SRE_Match object; span=(0, 10), match='Helloworld'>>>> print(m.start())0>>> print(m.end())10>>> print(m.span())(0, 10)" }, { "code": null, "e": 3211, "s": 2859, "text": "Groups are marked by the ( )meta-characters. They group together the expressions contained inside them, and you can repeat the contents of a group with a repeating qualifier, such as *, +, ? or {m, n}.Groups are numbered starting with 0. Group 0 is always present; it’s the whole RE, so match object methods all have group 0 as their default argument." }, { "code": null, "e": 3389, "s": 3211, "text": "Subgroups are numbered from left to right, from 1 upward. Groups can be nested; to determine the number, just count the opening parenthesis characters, going from left to right." }, { "code": null, "e": 3823, "s": 3389, "text": ">>> pat_obj_group = re.compile('(a(b)c(d))e')>>> m = pat_obj_group.match('abcde')>>> print(m)<_sre.SRE_Match object; span=(0, 5), match='abcde'>#Note m.group(0) matches the same regex as m.match()>>> print(m.group(0))abcde>>> print(m.group(1))abcd#Note the number is determined left to right>>> print(m.group(2))b>>> print(m.group(3))d# Note that multiple arguments can be passes to group()>>> print(m.group(2,1,3))('b', 'abcd', 'd')" }, { "code": null, "e": 3932, "s": 3823, "text": "groups(): returns a tuple containing the strings for all the subgroups, from 1 up to however many there are." }, { "code": null, "e": 3972, "s": 3932, "text": ">>> print(m.groups())('abcd', 'b', 'd')" }, { "code": null, "e": 4374, "s": 3972, "text": "sub(): Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, the string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth." }, { "code": null, "e": 4469, "s": 4374, "text": "Empty matches for the pattern are replaced only when not adjacent to a previously empty match." }, { "code": null, "e": 4586, "s": 4469, "text": ">>> print(re.sub('x','-','abxd'))ab-d>>> print(re.sub('ab*','-','abxd'))-xd>>> print(re.sub('x*','-','abxd'))-a-b-d-" }, { "code": null, "e": 4767, "s": 4586, "text": "The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced." }, { "code": null, "e": 5265, "s": 4767, "text": "Though passing Regular Expressions helps in keeping things simple, it has one disadvantage. The backslash character (‘\\’) is used to allow special characters to be used without invoking their special meaning which conflicts with Python’s usage of the same character in string literals where it is used to interpret the character following it differently. For example, ’n’ by itself is simply a letter, but when you precede it with a backslash, it becomes \\n, which is the newline character. Ah oh!" }, { "code": null, "e": 5766, "s": 5265, "text": "Let’s say you want to write a RE that matches the string ‘\\section’, which might be found in a LaTeX file.We’ll start with the desired string to be matched. Next, we must escape any backslashes and other metacharacters by preceding them with a backslash, resulting in the string ‘\\\\section’. The resulting string that must be passed to re.compil() must be ‘\\\\section’. However, to express this as a Python string literal, both backslashes must be escaped again, resulting in the string ‘\\\\\\\\section’." }, { "code": null, "e": 5974, "s": 5766, "text": "In short, to match a literal backslash, one has to write ‘\\\\\\\\’ as the RE string, because the regular expression must be \\\\, and each backslash must be expressed as \\\\ inside a regular Python string literal." }, { "code": null, "e": 6255, "s": 5974, "text": "The solution is to use Python’s raw string notation for regular expressions; backslashes are not handled in any special way in a string literal prefixed with ‘r’, so r‘\\n’ is a two-character string containing ‘\\’ and ‘n’, while ‘\\n’ is a one-character string containing a newline." }, { "code": null, "e": 6299, "s": 6255, "text": "Regular string and corresponding Raw string" }, { "code": null, "e": 6372, "s": 6299, "text": "\"ab*\" -> r\"ab*\"\"\\\\\\\\section\" -> r\"\\\\section\"\"\\\\w+\\\\s+\\\\1\" -> r\"\\w+\\s+\\1\"" }, { "code": null, "e": 6381, "s": 6372, "text": "Regexone" }, { "code": null, "e": 6398, "s": 6381, "text": "Visualizing tool" }, { "code": null, "e": 6408, "s": 6398, "text": "RegexTips" }, { "code": null, "e": 6441, "s": 6408, "text": "Learning Git in Under 8 minutes!" }, { "code": null, "e": 6574, "s": 6441, "text": "I‘m glad you made it till the end of this article. 🎉I hope your reading experience was as enriching as the one I had writing this. 💖" }, { "code": null, "e": 6611, "s": 6574, "text": "Do check out my other articles here." } ]
How to fade in and fade out background with bootstrap text carousel ? - GeeksforGeeks
12 May, 2021 In this article, we will show you how to fade in and fade out the background with a bootstrap text carousel. Carousel is a slideshow, and it is used for cycling components like images or text. Approach: To create a fade-in and fade-out background with a bootstrap text carousel we have followed some basic steps. Step 1: Add bootstrap CDN to your HTML code. Step 1: Add bootstrap CDN to your HTML code. Step 2: For making a bootstrap carousel you have to add class = “carousel” in your HTML div box. Step 2: For making a bootstrap carousel you have to add class = “carousel” in your HTML div box. Step 3: To create the carousel fade in and fade out transition instead of a slider you have to add a class=”carousel-fade”. Step 3: To create the carousel fade in and fade out transition instead of a slider you have to add a class=”carousel-fade”. Step 4: Finally add text in your div box which you want to play in the carousel with a class=”carousel-item”. Step 4: Finally add text in your div box which you want to play in the carousel with a class=”carousel-item”. Example: HTML <!DOCTYPE html> <html> <head> <link href= "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" /> <script src= "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> h1 { color: green; } *, *::before, *::after { margin: 0; padding: 0; } html { box-sizing: border-box; } body { box-sizing: inherit; color: #fff !important; } h1 { margin-top: 0; text-align: center; font-weight: 600; } .carousel { margin-top: 10%; width: 100%; background-color: black; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id="carouselExampleFade" class="carousel slide carousel-fade" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <h1>Hii GeeksforGeeks</h1> </div> <div class="carousel-item"> <h1>Hello there</h1> </div> <div class="carousel-item"> <h1>GFG</h1> </div> </div> <a class="carousel-control-prev" href="#carouselExampleFade" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"> </span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleFade" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"> </span> <span class="sr-only">Next</span> </a> </div> </body> </html> Output : Carousel Bootstrap-Questions Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? 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 ? Convert a string to an integer in JavaScript
[ { "code": null, "e": 25694, "s": 25663, "text": " \n12 May, 2021\n" }, { "code": null, "e": 25887, "s": 25694, "text": "In this article, we will show you how to fade in and fade out the background with a bootstrap text carousel. Carousel is a slideshow, and it is used for cycling components like images or text." }, { "code": null, "e": 26007, "s": 25887, "text": "Approach: To create a fade-in and fade-out background with a bootstrap text carousel we have followed some basic steps." }, { "code": null, "e": 26054, "s": 26007, "text": "\nStep 1: Add bootstrap CDN to your HTML code.\n" }, { "code": null, "e": 26099, "s": 26054, "text": "Step 1: Add bootstrap CDN to your HTML code." }, { "code": null, "e": 26199, "s": 26099, "text": "\nStep 2: For making a bootstrap carousel you have to add class = “carousel” in your HTML div box.\n" }, { "code": null, "e": 26297, "s": 26199, "text": "Step 2: For making a bootstrap carousel you have to add class = “carousel” in your HTML div box." }, { "code": null, "e": 26423, "s": 26297, "text": "\nStep 3: To create the carousel fade in and fade out transition instead of a slider you have to add a class=”carousel-fade”.\n" }, { "code": null, "e": 26547, "s": 26423, "text": "Step 3: To create the carousel fade in and fade out transition instead of a slider you have to add a class=”carousel-fade”." }, { "code": null, "e": 26659, "s": 26547, "text": "\nStep 4: Finally add text in your div box which you want to play in the carousel with a class=”carousel-item”.\n" }, { "code": null, "e": 26769, "s": 26659, "text": "Step 4: Finally add text in your div box which you want to play in the carousel with a class=”carousel-item”." }, { "code": null, "e": 26778, "s": 26769, "text": "Example:" }, { "code": null, "e": 26783, "s": 26778, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n <head> \n <link href= \n\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" \n rel=\"stylesheet\" /> \n <script src= \n\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> \n </script> \n <script src= \n\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> \n </script> \n <script src= \n\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> \n </script> \n \n <style> \n h1 { \n color: green; \n } \n *, \n *::before, \n *::after { \n margin: 0; \n padding: 0; \n } \n \n html { \n box-sizing: border-box; \n } \n body { \n box-sizing: inherit; \n color: #fff !important; \n } \n \n h1 { \n margin-top: 0; \n text-align: center; \n font-weight: 600; \n } \n .carousel { \n margin-top: 10%; \n width: 100%; \n background-color: black; \n } \n </style> \n </head> \n <body> \n <h1>GeeksforGeeks</h1> \n \n <div id=\"carouselExampleFade\" \n class=\"carousel slide carousel-fade\" \n data-ride=\"carousel\"> \n <div class=\"carousel-inner\"> \n <div class=\"carousel-item active\"> \n <h1>Hii GeeksforGeeks</h1> \n </div> \n <div class=\"carousel-item\"> \n <h1>Hello there</h1> \n </div> \n <div class=\"carousel-item\"> \n <h1>GFG</h1> \n </div> \n </div> \n <a class=\"carousel-control-prev\" \n href=\"#carouselExampleFade\" \n role=\"button\" data-slide=\"prev\"> \n <span class=\"carousel-control-prev-icon\" \n aria-hidden=\"true\"> \n </span> \n <span class=\"sr-only\">Previous</span> \n </a> \n <a class=\"carousel-control-next\" \n href=\"#carouselExampleFade\" \n role=\"button\" data-slide=\"next\"> \n <span class=\"carousel-control-next-icon\" \n aria-hidden=\"true\"> \n </span> \n <span class=\"sr-only\">Next</span> \n </a> \n </div> \n </body> \n</html> \n\n\n\n\n\n", "e": 29335, "s": 26793, "text": null }, { "code": null, "e": 29344, "s": 29335, "text": "Output :" }, { "code": null, "e": 29353, "s": 29344, "text": "Carousel" }, { "code": null, "e": 29375, "s": 29353, "text": "\nBootstrap-Questions\n" }, { "code": null, "e": 29384, "s": 29375, "text": "\nPicked\n" }, { "code": null, "e": 29396, "s": 29384, "text": "\nBootstrap\n" }, { "code": null, "e": 29415, "s": 29396, "text": "\nWeb Technologies\n" }, { "code": null, "e": 29620, "s": 29415, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 29661, "s": 29620, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 29724, "s": 29661, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 29757, "s": 29724, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 29783, "s": 29757, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 29832, "s": 29783, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 29874, "s": 29832, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29907, "s": 29874, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29969, "s": 29907, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30012, "s": 29969, "text": "How to fetch data from an API in ReactJS ?" } ]
ACPI command in Linux with examples - GeeksforGeeks
04 Apr, 2019 acpi command is used to display the battery status and other ACPI information. It displays the information from the /proc or the /sys filesystem, such as battery status or thermal information. Syntax: acpi [options] -b | –battery : It displays the battery information. Example: -a | –ac-adapter : It displays the ac adapter information. Example: -t | –thermal : It shows the thermal information. Example: -c | –cooling : It displays the cooling device information. Example: -V | –everything : It is used to show every device, overrides above options. Example: -s | –show-empty : It displays the non-operational devices. Example: -i | –details : It displays the additional details if available. Example: -f | –fahrenheit : It uses fahrenheit as the temperature unit instead of default celsius. Example: -k | –kelvin : It uses kelvin as the temperature unit instead of default celsius. Example: -p | –proc : It uses the old /proc interface, default is the new /sys one. -d | –directory : It uses the path to ACPI info (either /proc/acpi or /sys/class)/ -h | –help : It display help and exit. Example: -v | –version : It shows the output version information and exit. Example: linux-command Linux-misc-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples UDP Server-Client implementation in C curl command in Linux with Examples Conditional Statements | Shell Script Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples Mutex lock for Linux Thread Synchronization
[ { "code": null, "e": 24188, "s": 24160, "text": "\n04 Apr, 2019" }, { "code": null, "e": 24381, "s": 24188, "text": "acpi command is used to display the battery status and other ACPI information. It displays the information from the /proc or the /sys filesystem, such as battery status or thermal information." }, { "code": null, "e": 24389, "s": 24381, "text": "Syntax:" }, { "code": null, "e": 24406, "s": 24389, "text": "acpi [options] " }, { "code": null, "e": 24459, "s": 24406, "text": "-b | –battery : It displays the battery information." }, { "code": null, "e": 24468, "s": 24459, "text": "Example:" }, { "code": null, "e": 24527, "s": 24468, "text": "-a | –ac-adapter : It displays the ac adapter information." }, { "code": null, "e": 24536, "s": 24527, "text": "Example:" }, { "code": null, "e": 24586, "s": 24536, "text": "-t | –thermal : It shows the thermal information." }, { "code": null, "e": 24595, "s": 24586, "text": "Example:" }, { "code": null, "e": 24655, "s": 24595, "text": "-c | –cooling : It displays the cooling device information." }, { "code": null, "e": 24664, "s": 24655, "text": "Example:" }, { "code": null, "e": 24741, "s": 24664, "text": "-V | –everything : It is used to show every device, overrides above options." }, { "code": null, "e": 24750, "s": 24741, "text": "Example:" }, { "code": null, "e": 24810, "s": 24750, "text": "-s | –show-empty : It displays the non-operational devices." }, { "code": null, "e": 24819, "s": 24810, "text": "Example:" }, { "code": null, "e": 24884, "s": 24819, "text": "-i | –details : It displays the additional details if available." }, { "code": null, "e": 24893, "s": 24884, "text": "Example:" }, { "code": null, "e": 24983, "s": 24893, "text": "-f | –fahrenheit : It uses fahrenheit as the temperature unit instead of default celsius." }, { "code": null, "e": 24992, "s": 24983, "text": "Example:" }, { "code": null, "e": 25074, "s": 24992, "text": "-k | –kelvin : It uses kelvin as the temperature unit instead of default celsius." }, { "code": null, "e": 25083, "s": 25074, "text": "Example:" }, { "code": null, "e": 25158, "s": 25083, "text": "-p | –proc : It uses the old /proc interface, default is the new /sys one." }, { "code": null, "e": 25241, "s": 25158, "text": "-d | –directory : It uses the path to ACPI info (either /proc/acpi or /sys/class)/" }, { "code": null, "e": 25280, "s": 25241, "text": "-h | –help : It display help and exit." }, { "code": null, "e": 25289, "s": 25280, "text": "Example:" }, { "code": null, "e": 25355, "s": 25289, "text": "-v | –version : It shows the output version information and exit." }, { "code": null, "e": 25364, "s": 25355, "text": "Example:" }, { "code": null, "e": 25378, "s": 25364, "text": "linux-command" }, { "code": null, "e": 25398, "s": 25378, "text": "Linux-misc-commands" }, { "code": null, "e": 25409, "s": 25398, "text": "Linux-Unix" }, { "code": null, "e": 25507, "s": 25409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25516, "s": 25507, "text": "Comments" }, { "code": null, "e": 25529, "s": 25516, "text": "Old Comments" }, { "code": null, "e": 25567, "s": 25529, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25602, "s": 25567, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 25637, "s": 25602, "text": "tar command in Linux with examples" }, { "code": null, "e": 25675, "s": 25637, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 25711, "s": 25675, "text": "curl command in Linux with Examples" }, { "code": null, "e": 25749, "s": 25711, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 25784, "s": 25749, "text": "Cat command in Linux with examples" }, { "code": null, "e": 25821, "s": 25784, "text": "touch command in Linux with Examples" }, { "code": null, "e": 25857, "s": 25821, "text": "echo command in Linux with Examples" } ]
Find N Geometric Means between A and B - GeeksforGeeks
07 Apr, 2021 Given three integers A, B and N the task is to find N Geometric means between A and B. WE basically need to insert N terms in a Geometric progression. where A and B are first and last terms. Examples: Input : A = 2 B = 32 N = 3 Output : 4 8 16 the geometric progression series as 2, 4, 8, 16 , 32 Input : A = 3 B = 81 N = 2 Output : 9 27 Approach : Let A1, G2, G3, G4......Gn be N geometric Means between two given numbers A and B . Then A, G1, G2 ..... Gn, B will be in Geometric Progression . So B = (N+2)th term of the Geometric progression.Then Here R is the common ratio B = A*RN+1 RN+1 = B/A R = (B/A)1/(N+1)Now we have the value of R And also we have the value of the first term A G1 = AR1 = A * (B/A)1/(N+1) G2 = AR2 = A * (B/A)2/(N+1) G3 = AR3 = A * (B/A)3/(N+1) . . . GN = ARN = A * (B/A)N/(N+1) C++ Java Python3 C# PHP Javascript // C++ program to find n geometric means// between A and B#include <bits/stdc++.h>using namespace std; // Prints N geometric means between// A and B.void printGMeans(int A, int B, int N){ // calculate common ratio(R) float R = (float)pow(float(B / A), 1.0 / (float)(N + 1)); // for finding N the Geometric // mean between A and B for (int i = 1; i <= N; i++) cout << A * pow(R, i) <<" "; } // Driver code to test aboveint main(){ int A = 3, B = 81, N = 2; printGMeans(A, B, N); return 0;} // java program to illustrate// n geometric mean between// A and Bimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // insert function for calculating the means static void printGMeans(int A, int B, int N) { // Finding the value of R Common ration float R = (float)Math.pow((float)(B / A), 1.0 / (float)(N + 1)); // for finding N the Geometric // mean between A and B for (int i = 1; i <= N; i++) System.out.print(A * Math.pow(R, i) + " "); } // Driver code public static void main(String args[]) { int A = 3, B = 81, N = 2; printGMeans(A, B, N); }} # Python3 program to find# n geometric means# between A and Bimport math # Prints N geometric means# between A and B.def printGMeans(A, B, N): # calculate # common ratio(R) R = (math.pow((B / A), 1.0 / (N + 1))); # for finding N the # Geometric mean # between A and B for i in range(1, N + 1): print(int(A * math.pow(R, i)), end = " "); # Driver CodeA = 3;B = 81;N = 2;printGMeans(A, B, N); # This code is contributed# by mits // C# program to illustrate// n geometric mean between// A and Busing System; public class GFG { // insert function for calculating the means static void printGMeans(int A, int B, int N) { // Finding the value of R Common ration float R = (float)Math.Pow((float)(B / A), 1.0 / (float)(N + 1)); // for finding N the Geometric // mean between A and B for (int i = 1; i <= N; i++) Console.Write(A * Math.Pow(R, i) + " "); } // Driver code public static void Main() { int A = 3, B = 81, N = 2; printGMeans(A, B, N); }} // This code is contributed by vt_m. <?php// PHP program to find// n geometric means// between A and B // Pr$s N geometric means// between A and B.function printGMeans($A, $B, $N){ // calculate common ratio(R) $R = pow(($B / $A), 1.0 / ($N + 1)); // for finding N the Geometric // mean between A and B for ($i = 1; $i <= $N; $i++) echo $A * pow($R, $i) ," ";} // Driver Code $A = 3; $B = 81; $N = 2; printGMeans($A, $B, $N); // This code is contributed by anuj_67.?> <script>// JavaScript program to illustrate// n geometric mean between// A and B // insert function for calculating the means function printGMeans(A, B, N) { // Finding the value of R Common ration let R = Math.pow((B / A), 1.0 / (N + 1)); // for finding N the Geometric // mean between A and B for (let i = 1; i <= N; i++) document.write(A * Math.pow(R, i) + " "); } // Driver Code let A = 3, B = 81, N = 2; printGMeans(A, B, N); // This code is contributed by code_hunt.</script> Output : 9 27 vt_m Mithun Kumar ManasChhabra2 code_hunt school-programming series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Sieve of Eratosthenes Program for Decimal to Binary Conversion Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 25092, "s": 25064, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25295, "s": 25092, "text": "Given three integers A, B and N the task is to find N Geometric means between A and B. WE basically need to insert N terms in a Geometric progression. where A and B are first and last terms. Examples: " }, { "code": null, "e": 25443, "s": 25295, "text": "Input : A = 2 B = 32 N = 3\nOutput : 4 8 16\nthe geometric progression series as 2,\n4, 8, 16 , 32\n \nInput : A = 3 B = 81 N = 2\nOutput : 9 27" }, { "code": null, "e": 25914, "s": 25445, "text": "Approach : Let A1, G2, G3, G4......Gn be N geometric Means between two given numbers A and B . Then A, G1, G2 ..... Gn, B will be in Geometric Progression . So B = (N+2)th term of the Geometric progression.Then Here R is the common ratio B = A*RN+1 RN+1 = B/A R = (B/A)1/(N+1)Now we have the value of R And also we have the value of the first term A G1 = AR1 = A * (B/A)1/(N+1) G2 = AR2 = A * (B/A)2/(N+1) G3 = AR3 = A * (B/A)3/(N+1) . . . GN = ARN = A * (B/A)N/(N+1) " }, { "code": null, "e": 25918, "s": 25914, "text": "C++" }, { "code": null, "e": 25923, "s": 25918, "text": "Java" }, { "code": null, "e": 25931, "s": 25923, "text": "Python3" }, { "code": null, "e": 25934, "s": 25931, "text": "C#" }, { "code": null, "e": 25938, "s": 25934, "text": "PHP" }, { "code": null, "e": 25949, "s": 25938, "text": "Javascript" }, { "code": "// C++ program to find n geometric means// between A and B#include <bits/stdc++.h>using namespace std; // Prints N geometric means between// A and B.void printGMeans(int A, int B, int N){ // calculate common ratio(R) float R = (float)pow(float(B / A), 1.0 / (float)(N + 1)); // for finding N the Geometric // mean between A and B for (int i = 1; i <= N; i++) cout << A * pow(R, i) <<\" \"; } // Driver code to test aboveint main(){ int A = 3, B = 81, N = 2; printGMeans(A, B, N); return 0;}", "e": 26496, "s": 25949, "text": null }, { "code": "// java program to illustrate// n geometric mean between// A and Bimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // insert function for calculating the means static void printGMeans(int A, int B, int N) { // Finding the value of R Common ration float R = (float)Math.pow((float)(B / A), 1.0 / (float)(N + 1)); // for finding N the Geometric // mean between A and B for (int i = 1; i <= N; i++) System.out.print(A * Math.pow(R, i) + \" \"); } // Driver code public static void main(String args[]) { int A = 3, B = 81, N = 2; printGMeans(A, B, N); }}", "e": 27224, "s": 26496, "text": null }, { "code": "# Python3 program to find# n geometric means# between A and Bimport math # Prints N geometric means# between A and B.def printGMeans(A, B, N): # calculate # common ratio(R) R = (math.pow((B / A), 1.0 / (N + 1))); # for finding N the # Geometric mean # between A and B for i in range(1, N + 1): print(int(A * math.pow(R, i)), end = \" \"); # Driver CodeA = 3;B = 81;N = 2;printGMeans(A, B, N); # This code is contributed# by mits", "e": 27728, "s": 27224, "text": null }, { "code": "// C# program to illustrate// n geometric mean between// A and Busing System; public class GFG { // insert function for calculating the means static void printGMeans(int A, int B, int N) { // Finding the value of R Common ration float R = (float)Math.Pow((float)(B / A), 1.0 / (float)(N + 1)); // for finding N the Geometric // mean between A and B for (int i = 1; i <= N; i++) Console.Write(A * Math.Pow(R, i) + \" \"); } // Driver code public static void Main() { int A = 3, B = 81, N = 2; printGMeans(A, B, N); }} // This code is contributed by vt_m.", "e": 28445, "s": 27728, "text": null }, { "code": "<?php// PHP program to find// n geometric means// between A and B // Pr$s N geometric means// between A and B.function printGMeans($A, $B, $N){ // calculate common ratio(R) $R = pow(($B / $A), 1.0 / ($N + 1)); // for finding N the Geometric // mean between A and B for ($i = 1; $i <= $N; $i++) echo $A * pow($R, $i) ,\" \";} // Driver Code $A = 3; $B = 81; $N = 2; printGMeans($A, $B, $N); // This code is contributed by anuj_67.?>", "e": 28939, "s": 28445, "text": null }, { "code": "<script>// JavaScript program to illustrate// n geometric mean between// A and B // insert function for calculating the means function printGMeans(A, B, N) { // Finding the value of R Common ration let R = Math.pow((B / A), 1.0 / (N + 1)); // for finding N the Geometric // mean between A and B for (let i = 1; i <= N; i++) document.write(A * Math.pow(R, i) + \" \"); } // Driver Code let A = 3, B = 81, N = 2; printGMeans(A, B, N); // This code is contributed by code_hunt.</script>", "e": 29565, "s": 28939, "text": null }, { "code": null, "e": 29576, "s": 29565, "text": "Output : " }, { "code": null, "e": 29582, "s": 29576, "text": "9 27 " }, { "code": null, "e": 29589, "s": 29584, "text": "vt_m" }, { "code": null, "e": 29602, "s": 29589, "text": "Mithun Kumar" }, { "code": null, "e": 29616, "s": 29602, "text": "ManasChhabra2" }, { "code": null, "e": 29626, "s": 29616, "text": "code_hunt" }, { "code": null, "e": 29645, "s": 29626, "text": "school-programming" }, { "code": null, "e": 29652, "s": 29645, "text": "series" }, { "code": null, "e": 29665, "s": 29652, "text": "Mathematical" }, { "code": null, "e": 29678, "s": 29665, "text": "Mathematical" }, { "code": null, "e": 29685, "s": 29678, "text": "series" }, { "code": null, "e": 29783, "s": 29685, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29807, "s": 29783, "text": "Merge two sorted arrays" }, { "code": null, "e": 29849, "s": 29807, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 29892, "s": 29849, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29906, "s": 29892, "text": "Prime Numbers" }, { "code": null, "e": 29955, "s": 29906, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 29977, "s": 29955, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 30018, "s": 29977, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 30052, "s": 30018, "text": "Program for factorial of a number" }, { "code": null, "e": 30073, "s": 30052, "text": "Operators in C / C++" } ]
Python program to Find the size of a Tuple
When it is required to find the size of a tuple, the ‘sizeof’ method can be used. Below is the demonstration of the same − Live Demo import sys tuple_1 = ("A", 1, "B", 2, "C", 3) tuple_2 = ("Java", "Lee", "Code", "Mark", "John") tuple_3 = ((1, "Bill"), ( 2, "Ant"), (3, "Fox"), (4, "Cheetah")) print("The first tuple is :") print(tuple_1) print("The second tuple is :") print(tuple_2) print("The third tuple is :") print(tuple_3) print("Size of first tuple is : " + str(sys.getsizeof(tuple_1)) + " bytes") print("Size of second tuple is : " + str(sys.getsizeof(tuple_2)) + " bytes") print("Size of third tuple is: " + str(sys.getsizeof(tuple_3)) + " bytes") The first tuple is : ('A', 1, 'B', 2, 'C', 3) The second tuple is : ('Java', 'Lee', 'Code', 'Mark', 'John') The third tuple is : ((1, 'Bill'), (2, 'Ant'), (3, 'Fox'), (4, 'Cheetah')) Size of first tuple is : 96 bytes Size of second tuple is : 88 bytes Size of third tuple is : 80 bytes The required packages are imported. The required packages are imported. The tuples are defined, and are displayed on the console. The tuples are defined, and are displayed on the console. The ‘sizeof’ method is called on every tuple and the length is displayed as output on the console. The ‘sizeof’ method is called on every tuple and the length is displayed as output on the console.
[ { "code": null, "e": 1144, "s": 1062, "text": "When it is required to find the size of a tuple, the ‘sizeof’ method can be used." }, { "code": null, "e": 1185, "s": 1144, "text": "Below is the demonstration of the same −" }, { "code": null, "e": 1196, "s": 1185, "text": " Live Demo" }, { "code": null, "e": 1722, "s": 1196, "text": "import sys\ntuple_1 = (\"A\", 1, \"B\", 2, \"C\", 3)\ntuple_2 = (\"Java\", \"Lee\", \"Code\", \"Mark\", \"John\")\ntuple_3 = ((1, \"Bill\"), ( 2, \"Ant\"), (3, \"Fox\"), (4, \"Cheetah\"))\n\nprint(\"The first tuple is :\")\nprint(tuple_1)\nprint(\"The second tuple is :\")\nprint(tuple_2)\nprint(\"The third tuple is :\")\nprint(tuple_3)\nprint(\"Size of first tuple is : \" + str(sys.getsizeof(tuple_1)) + \" bytes\")\nprint(\"Size of second tuple is : \" + str(sys.getsizeof(tuple_2)) + \" bytes\")\nprint(\"Size of third tuple is: \" + str(sys.getsizeof(tuple_3)) + \" bytes\")" }, { "code": null, "e": 2008, "s": 1722, "text": "The first tuple is :\n('A', 1, 'B', 2, 'C', 3)\nThe second tuple is :\n('Java', 'Lee', 'Code', 'Mark', 'John')\nThe third tuple is :\n((1, 'Bill'), (2, 'Ant'), (3, 'Fox'), (4, 'Cheetah'))\nSize of first tuple is : 96 bytes\nSize of second tuple is : 88 bytes\nSize of third tuple is : 80 bytes" }, { "code": null, "e": 2044, "s": 2008, "text": "The required packages are imported." }, { "code": null, "e": 2080, "s": 2044, "text": "The required packages are imported." }, { "code": null, "e": 2138, "s": 2080, "text": "The tuples are defined, and are displayed on the console." }, { "code": null, "e": 2196, "s": 2138, "text": "The tuples are defined, and are displayed on the console." }, { "code": null, "e": 2295, "s": 2196, "text": "The ‘sizeof’ method is called on every tuple and the length is displayed as output on the console." }, { "code": null, "e": 2394, "s": 2295, "text": "The ‘sizeof’ method is called on every tuple and the length is displayed as output on the console." } ]
Is assignment operator inherited? - GeeksforGeeks
29 Mar, 2022 In C++, like other functions, assignment operator function is inherited in derived class. For example, in the following program, base class assignment operator function can be accessed using the derived class object. #include<iostream> using namespace std; class A { public: A & operator= (A &a) { cout<<" base class assignment operator called "; return *this; }}; class B: public A { }; int main(){ B a, b; a.A::operator=(b); //calling base class assignment operator function // using derived class getchar(); return 0;} Output: base class assignment operator called Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. naggarwal1 C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Socket Programming in C/C++ Constructors in C++ Virtual Function in C++ Multidimensional Arrays in C / C++ Templates in C++ with Examples Copy Constructor in C++
[ { "code": null, "e": 25166, "s": 25138, "text": "\n29 Mar, 2022" }, { "code": null, "e": 25256, "s": 25166, "text": "In C++, like other functions, assignment operator function is inherited in derived class." }, { "code": null, "e": 25383, "s": 25256, "text": "For example, in the following program, base class assignment operator function can be accessed using the derived class object." }, { "code": "#include<iostream> using namespace std; class A { public: A & operator= (A &a) { cout<<\" base class assignment operator called \"; return *this; }}; class B: public A { }; int main(){ B a, b; a.A::operator=(b); //calling base class assignment operator function // using derived class getchar(); return 0;}", "e": 25728, "s": 25383, "text": null }, { "code": null, "e": 25774, "s": 25728, "text": "Output: base class assignment operator called" }, { "code": null, "e": 25899, "s": 25774, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25910, "s": 25899, "text": "naggarwal1" }, { "code": null, "e": 25914, "s": 25910, "text": "C++" }, { "code": null, "e": 25918, "s": 25914, "text": "CPP" }, { "code": null, "e": 26016, "s": 25918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26035, "s": 26016, "text": "Inheritance in C++" }, { "code": null, "e": 26078, "s": 26035, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 26102, "s": 26078, "text": "C++ Classes and Objects" }, { "code": null, "e": 26129, "s": 26102, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 26157, "s": 26129, "text": "Socket Programming in C/C++" }, { "code": null, "e": 26177, "s": 26157, "text": "Constructors in C++" }, { "code": null, "e": 26201, "s": 26177, "text": "Virtual Function in C++" }, { "code": null, "e": 26236, "s": 26201, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26267, "s": 26236, "text": "Templates in C++ with Examples" } ]
Python - Processing CSV Data
Reading data from CSV(comma separated values) is a fundamental necessity in Data Science. Often, we get data from various sources which can get exported to CSV format so that they can be used by other systems. The Panadas library provides features using which we can read the CSV file in full as well as in parts for only a selected group of columns and rows. The csv file is a text file in which the values in the columns are separated by a comma. Let's consider the following data present in the file named input.csv. You can create this file using windows notepad by copying and pasting this data. Save the file as input.csv using the save As All files(*.*) option in notepad. id,name,salary,start_date,dept 1,Rick,623.3,2012-01-01,IT 2,Dan,515.2,2013-09-23,Operations 3,Tusar,611,2014-11-15,IT 4,Ryan,729,2014-05-11,HR 5,Gary,843.25,2015-03-27,Finance 6,Rasmi,578,2013-05-21,IT 7,Pranab,632.8,2013-07-30,Operations 8,Guru,722.5,2014-06-17,Finance The read_csv function of the pandas library is used read the content of a CSV file into the python environment as a pandas DataFrame. The function can read the files from the OS by using proper path to the file. import pandas as pd data = pd.read_csv('path/input.csv') print (data) When we execute the above code, it produces the following result. Please note how an additional column starting with zero as a index has been created by the function. id name salary start_date dept 0 1 Rick 623.30 2012-01-01 IT 1 2 Dan 515.20 2013-09-23 Operations 2 3 Tusar 611.00 2014-11-15 IT 3 4 Ryan 729.00 2014-05-11 HR 4 5 Gary 843.25 2015-03-27 Finance 5 6 Rasmi 578.00 2013-05-21 IT 6 7 Pranab 632.80 2013-07-30 Operations 7 8 Guru 722.50 2014-06-17 Finance The read_csv function of the pandas library can also be used to read some specific rows for a given column. We slice the result from the read_csv function using the code shown below for first 5 rows for the column named salary. import pandas as pd data = pd.read_csv('path/input.csv') # Slice the result for first 5 rows print (data[0:5]['salary']) When we execute the above code, it produces the following result. 0 623.30 1 515.20 2 611.00 3 729.00 4 843.25 Name: salary, dtype: float64 The read_csv function of the pandas library can also be used to read some specific columns. We use the multi-axes indexing method called .loc() for this purpose. We choose to display the salary and name column for all the rows. import pandas as pd data = pd.read_csv('path/input.csv') # Use the multi-axes indexing funtion print (data.loc[:,['salary','name']]) When we execute the above code, it produces the following result. salary name 0 623.30 Rick 1 515.20 Dan 2 611.00 Tusar 3 729.00 Ryan 4 843.25 Gary 5 578.00 Rasmi 6 632.80 Pranab 7 722.50 Guru The read_csv function of the pandas library can also be used to read some specific columns and specific rows. We use the multi-axes indexing method called .loc() for this purpose. We choose to display the salary and name column for some of the rows. import pandas as pd data = pd.read_csv('path/input.csv') # Use the multi-axes indexing funtion print (data.loc[[1,3,5],['salary','name']]) When we execute the above code, it produces the following result. salary name 1 515.2 Dan 3 729.0 Ryan 5 578.0 Rasmi The read_csv function of the pandas library can also be used to read some specific columns and a range of rows. We use the multi-axes indexing method called .loc() for this purpose. We choose to display the salary and name column for some of the rows. import pandas as pd data = pd.read_csv('path/input.csv') # Use the multi-axes indexing funtion print (data.loc[2:6,['salary','name']]) When we execute the above code, it produces the following result. salary name 2 611.00 Tusar 3 729.00 Ryan 4 843.25 Gary 5 578.00 Rasmi 6 632.80 Pranab 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2890, "s": 2529, "text": "Reading data from CSV(comma separated values) is a fundamental necessity in Data Science. Often, we get data from various sources which can get exported to CSV format so that they can be used by other systems. The Panadas library provides features using which we can read the CSV file in full as well as in parts for only a selected group of columns and rows. " }, { "code": null, "e": 3050, "s": 2890, "text": "The csv file is a text file in which the values in the columns are separated by a comma. Let's consider the following data present in the file named input.csv." }, { "code": null, "e": 3210, "s": 3050, "text": "You can create this file using windows notepad by copying and pasting this data. Save the file as input.csv using the save As All files(*.*) option in notepad." }, { "code": null, "e": 3481, "s": 3210, "text": "id,name,salary,start_date,dept\n1,Rick,623.3,2012-01-01,IT\n2,Dan,515.2,2013-09-23,Operations\n3,Tusar,611,2014-11-15,IT\n4,Ryan,729,2014-05-11,HR\n5,Gary,843.25,2015-03-27,Finance\n6,Rasmi,578,2013-05-21,IT\n7,Pranab,632.8,2013-07-30,Operations\n8,Guru,722.5,2014-06-17,Finance" }, { "code": null, "e": 3693, "s": 3481, "text": "The read_csv function of the pandas library is used read the content of a CSV file into the python environment as a pandas DataFrame. The function can read the files from the OS by using proper path to the file." }, { "code": null, "e": 3763, "s": 3693, "text": "import pandas as pd\ndata = pd.read_csv('path/input.csv')\nprint (data)" }, { "code": null, "e": 3930, "s": 3763, "text": "When we execute the above code, it produces the following result. Please note how an additional column starting with zero as a index has been created by the function." }, { "code": null, "e": 4344, "s": 3930, "text": " id name salary start_date dept\n0 1 Rick 623.30 2012-01-01 IT\n1 2 Dan 515.20 2013-09-23 Operations\n2 3 Tusar 611.00 2014-11-15 IT\n3 4 Ryan 729.00 2014-05-11 HR\n4 5 Gary 843.25 2015-03-27 Finance\n5 6 Rasmi 578.00 2013-05-21 IT\n6 7 Pranab 632.80 2013-07-30 Operations\n7 8 Guru 722.50 2014-06-17 Finance" }, { "code": null, "e": 4572, "s": 4344, "text": "The read_csv function of the pandas library can also be used to read some specific rows for a given column. We slice the result from the read_csv function using the code shown below for first 5 rows for the column named salary." }, { "code": null, "e": 4694, "s": 4572, "text": "import pandas as pd\ndata = pd.read_csv('path/input.csv')\n\n# Slice the result for first 5 rows\nprint (data[0:5]['salary'])" }, { "code": null, "e": 4760, "s": 4694, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 4849, "s": 4760, "text": "0 623.30\n1 515.20\n2 611.00\n3 729.00\n4 843.25\nName: salary, dtype: float64" }, { "code": null, "e": 5079, "s": 4849, "text": "The read_csv function of the pandas library can also be used to read some specific columns. \nWe use the multi-axes indexing method called .loc() for this purpose. We choose to display the salary and name column for all the rows. " }, { "code": null, "e": 5213, "s": 5079, "text": "import pandas as pd\ndata = pd.read_csv('path/input.csv')\n\n# Use the multi-axes indexing funtion\nprint (data.loc[:,['salary','name']])" }, { "code": null, "e": 5279, "s": 5213, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 5441, "s": 5279, "text": " salary name\n0 623.30 Rick\n1 515.20 Dan\n2 611.00 Tusar\n3 729.00 Ryan\n4 843.25 Gary\n5 578.00 Rasmi\n6 632.80 Pranab\n7 722.50 Guru" }, { "code": null, "e": 5693, "s": 5441, "text": "The read_csv function of the pandas library can also be used to read some specific columns and specific rows. \nWe use the multi-axes indexing method called .loc() for this purpose. We choose to display the salary and name column for some of the rows. " }, { "code": null, "e": 5833, "s": 5693, "text": "import pandas as pd\ndata = pd.read_csv('path/input.csv')\n\n# Use the multi-axes indexing funtion\nprint (data.loc[[1,3,5],['salary','name']])" }, { "code": null, "e": 5899, "s": 5833, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 5967, "s": 5899, "text": " salary name\n1 515.2 Dan\n3 729.0 Ryan\n5 578.0 Rasmi" }, { "code": null, "e": 6221, "s": 5967, "text": "The read_csv function of the pandas library can also be used to read some specific columns and a range of rows. \nWe use the multi-axes indexing method called .loc() for this purpose. We choose to display the salary and name column for some of the rows. " }, { "code": null, "e": 6357, "s": 6221, "text": "import pandas as pd\ndata = pd.read_csv('path/input.csv')\n\n# Use the multi-axes indexing funtion\nprint (data.loc[2:6,['salary','name']])" }, { "code": null, "e": 6423, "s": 6357, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 6531, "s": 6423, "text": " salary name\n2 611.00 Tusar\n3 729.00 Ryan\n4 843.25 Gary\n5 578.00 Rasmi\n6 632.80 Pranab" }, { "code": null, "e": 6568, "s": 6531, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6584, "s": 6568, "text": " Malhar Lathkar" }, { "code": null, "e": 6617, "s": 6584, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6636, "s": 6617, "text": " Arnab Chakraborty" }, { "code": null, "e": 6671, "s": 6636, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6693, "s": 6671, "text": " In28Minutes Official" }, { "code": null, "e": 6727, "s": 6693, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6755, "s": 6727, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6790, "s": 6755, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6804, "s": 6790, "text": " Lets Kode It" }, { "code": null, "e": 6837, "s": 6804, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6854, "s": 6837, "text": " Abhilash Nelson" }, { "code": null, "e": 6861, "s": 6854, "text": " Print" }, { "code": null, "e": 6872, "s": 6861, "text": " Add Notes" } ]
C++ Matrix Rotation by 180 degree | Practice | GeeksforGeeks
Given a square matrix of size N X N, turn it by 180 degrees in anticlockwise direction without using extra memory. Example 1: Input: N = 4, matrix = {{1, 2, 3, 4}, {5, 6, 7 ,8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output: {{16, 15, 14, 13}, {12, 11, 10, 9}, {8, 7, 6, 5}, {4, 3, 2, 1}} Example 2: Input: N = 2, matrix = {{1, 2}, {3, 4}} Output: {{4, 3}, {2, 1}} Your Task: You don't need to read or print anything. Your task is to complete the function rotate() which takes matrix as input parameter and rotate the matrix by 180 degree wihtout using extraa memory. You have to rotate the matrix in-place which means you have to modify the input matrix directly. Expected Time Complexity: O(N2) Expected Space Complexity: O(1) Constraints: 1 ≤ N ≤ 500 +2 badgujarsachin831 month ago void rotate(vector<vector<int> >& matrix) { // Code here int n=matrix.size(); for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ swap(matrix[i][j],matrix[j][i]); } } for(int i=0;i<n;i++){ for(int j=0;j<n-i;j++){ swap(matrix[i][j],matrix[n-1-j][n-1-i]); } } 0 chessnoobdj2 months ago C++ inplace, take transpose twice void rotate(vector<vector<int> >& A) { int n = A.size(); for(int i=0; i<n; i++) for(int j=i; j<n; j++) swap(A[i][j], A[j][i]); for(int i=0; i<n; i++) for(int j=0; j<n-i; j++) swap(A[i][j], A[n-1-j][n-1-i]); } +1 nyngupta003 months ago void rotate(vector<vector<int> >& matrix) { int n=matrix.size(); for(int i=0;i<n/2;i++) for(int j=0;j<n;j++) { int t=matrix[i][j]; matrix[i][j]=matrix[abs(i-(n-1))][abs(j-(n-1))]; matrix[abs(i-(n-1))][abs(j-(n-1))]=t; } if(n%2!=0) { for(int i=0;i<n/2;i++) { int t=matrix[n/2][i]; matrix[n/2][i]=matrix[n/2][abs(i-(n-1))]; matrix[n/2][abs(i-(n-1))]=t; } } } 0 shubham9063 months ago //User function Template for Java class Solution{ public void rotate(int[][] matrix) { // code here int l = matrix.length; int arr[] = new int[l*l]; int count =0; for(int i=0;i<l;i++) { for(int j=0;j<l;j++) { arr[count]=matrix[i][j]; count++; } } count--; for(int i=0;i<l;i++) { for(int j=0;j<l;j++) { matrix[i][j] = arr[count]; count--; } } }} +3 nitind3563 months ago Simple C++ code: void rotate(vector<vector<int> >& matrix) { reverse(matrix.begin(),matrix.end()); for(int i=0;i<matrix[0].size();i++){ reverse(matrix[i].begin(),matrix[i].end()); } } -1 aprameya0836 months ago C++ code- class Solution { public: void rotate(vector<vector<int> >& matrix) { int t=2; int n=matrix.size(); while(t>0){ for(int i=0; i<n; i++){ for(int j=i; j<n; j++){ int temp1=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp1; } } for(int i=0; i<n/2; i++){ for(int j=0; j<n; j++){ int temp2=matrix[i][j]; matrix[i][j]=matrix[n-i-1][j]; matrix[n-i-1][j]=temp2; } }t--; } } }; 0 Imran Wahid8 months ago Imran Wahid Easy C++ solutionhttps://ide.geeksforgeeks.o... https://uploads.disquscdn.c... 0 Dhruv Bajoria9 months ago Dhruv Bajoria void rotatea(vector<vector<int> >& matrix){ int n=matrix.size(); for(int i=0;i<n;i++) reverse(matrix[i].begin(),matrix[i].end());="" for(int="" i="0;i&lt;n;i++)" {="" for(int="" j="0;j&lt;i;j++)" swap(matrix[i][j],matrix[j][i]);="" }="" }="" void="" rotate(vector<vector<int=""> >& matrix) { rotatea(matrix); rotatea(matrix); } 0 Dhruv Bajoria This comment was deleted. 0 ANKIT SINHA9 months ago ANKIT SINHA https://uploads.disquscdn.c... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 343, "s": 226, "text": "Given a square matrix of size N X N, turn it by 180 degrees in anticlockwise direction without using extra memory.\n " }, { "code": null, "e": 354, "s": 343, "text": "Example 1:" }, { "code": null, "e": 577, "s": 354, "text": "Input: N = 4, \nmatrix = {{1, 2, 3, 4}, \n {5, 6, 7 ,8}, \n {9, 10, 11, 12},\n {13, 14, 15, 16}}\nOutput: {{16, 15, 14, 13}, \n {12, 11, 10, 9}, \n {8, 7, 6, 5}, \n {4, 3, 2, 1}}\n" }, { "code": null, "e": 588, "s": 577, "text": "Example 2:" }, { "code": null, "e": 674, "s": 588, "text": "Input: N = 2,\nmatrix = {{1, 2},\n {3, 4}}\nOutput: {{4, 3}, \n {2, 1}}\n" }, { "code": null, "e": 978, "s": 676, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function rotate() which takes matrix as input parameter and rotate the matrix by 180 degree wihtout using extraa memory. You have to rotate the matrix in-place which means you have to modify the input matrix directly.\n " }, { "code": null, "e": 1044, "s": 978, "text": "Expected Time Complexity: O(N2)\nExpected Space Complexity: O(1)\n " }, { "code": null, "e": 1069, "s": 1044, "text": "Constraints:\n1 ≤ N ≤ 500" }, { "code": null, "e": 1072, "s": 1069, "text": "+2" }, { "code": null, "e": 1100, "s": 1072, "text": "badgujarsachin831 month ago" }, { "code": null, "e": 1482, "s": 1100, "text": " void rotate(vector<vector<int> >& matrix) {\n // Code here\n int n=matrix.size();\n for(int i=0;i<n;i++){\n for(int j=i;j<n;j++){\n swap(matrix[i][j],matrix[j][i]);\n }\n }\n for(int i=0;i<n;i++){\n for(int j=0;j<n-i;j++){\n swap(matrix[i][j],matrix[n-1-j][n-1-i]);\n }\n }" }, { "code": null, "e": 1484, "s": 1482, "text": "0" }, { "code": null, "e": 1508, "s": 1484, "text": "chessnoobdj2 months ago" }, { "code": null, "e": 1542, "s": 1508, "text": "C++ inplace, take transpose twice" }, { "code": null, "e": 1835, "s": 1542, "text": "void rotate(vector<vector<int> >& A) {\n int n = A.size();\n for(int i=0; i<n; i++)\n for(int j=i; j<n; j++)\n swap(A[i][j], A[j][i]);\n for(int i=0; i<n; i++)\n for(int j=0; j<n-i; j++)\n swap(A[i][j], A[n-1-j][n-1-i]);\n }" }, { "code": null, "e": 1838, "s": 1835, "text": "+1" }, { "code": null, "e": 1861, "s": 1838, "text": "nyngupta003 months ago" }, { "code": null, "e": 2354, "s": 1863, "text": " void rotate(vector<vector<int> >& matrix) { int n=matrix.size(); for(int i=0;i<n/2;i++) for(int j=0;j<n;j++) { int t=matrix[i][j]; matrix[i][j]=matrix[abs(i-(n-1))][abs(j-(n-1))]; matrix[abs(i-(n-1))][abs(j-(n-1))]=t; } if(n%2!=0) { for(int i=0;i<n/2;i++) { int t=matrix[n/2][i]; matrix[n/2][i]=matrix[n/2][abs(i-(n-1))]; matrix[n/2][abs(i-(n-1))]=t; } } }" }, { "code": null, "e": 2358, "s": 2356, "text": "0" }, { "code": null, "e": 2381, "s": 2358, "text": "shubham9063 months ago" }, { "code": null, "e": 2417, "s": 2383, "text": "//User function Template for Java" }, { "code": null, "e": 2918, "s": 2417, "text": "class Solution{ public void rotate(int[][] matrix) { // code here int l = matrix.length; int arr[] = new int[l*l]; int count =0; for(int i=0;i<l;i++) { for(int j=0;j<l;j++) { arr[count]=matrix[i][j]; count++; } } count--; for(int i=0;i<l;i++) { for(int j=0;j<l;j++) { matrix[i][j] = arr[count]; count--; } } }}" }, { "code": null, "e": 2921, "s": 2918, "text": "+3" }, { "code": null, "e": 2943, "s": 2921, "text": "nitind3563 months ago" }, { "code": null, "e": 2960, "s": 2943, "text": "Simple C++ code:" }, { "code": null, "e": 3140, "s": 2960, "text": "void rotate(vector<vector<int> >& matrix)\n{\n\treverse(matrix.begin(),matrix.end());\n for(int i=0;i<matrix[0].size();i++){\n reverse(matrix[i].begin(),matrix[i].end());\n }\n}" }, { "code": null, "e": 3143, "s": 3140, "text": "-1" }, { "code": null, "e": 3167, "s": 3143, "text": "aprameya0836 months ago" }, { "code": null, "e": 3177, "s": 3167, "text": "C++ code-" }, { "code": null, "e": 3752, "s": 3177, "text": "class Solution {\npublic:\n void rotate(vector<vector<int> >& matrix) {\n \n int t=2;\n int n=matrix.size();\n while(t>0){\n \n \n for(int i=0; i<n; i++){\n for(int j=i; j<n; j++){\n int temp1=matrix[i][j];\n matrix[i][j]=matrix[j][i]; \n matrix[j][i]=temp1;\n }\n }\n \n for(int i=0; i<n/2; i++){\n for(int j=0; j<n; j++){\n int temp2=matrix[i][j];\n matrix[i][j]=matrix[n-i-1][j]; \n matrix[n-i-1][j]=temp2;\n }\n }t--;\n }\n }\n};" }, { "code": null, "e": 3756, "s": 3754, "text": "0" }, { "code": null, "e": 3780, "s": 3756, "text": "Imran Wahid8 months ago" }, { "code": null, "e": 3792, "s": 3780, "text": "Imran Wahid" }, { "code": null, "e": 3871, "s": 3792, "text": "Easy C++ solutionhttps://ide.geeksforgeeks.o... https://uploads.disquscdn.c..." }, { "code": null, "e": 3873, "s": 3871, "text": "0" }, { "code": null, "e": 3899, "s": 3873, "text": "Dhruv Bajoria9 months ago" }, { "code": null, "e": 3913, "s": 3899, "text": "Dhruv Bajoria" }, { "code": null, "e": 4262, "s": 3913, "text": "void rotatea(vector<vector<int> >& matrix){ int n=matrix.size(); for(int i=0;i<n;i++) reverse(matrix[i].begin(),matrix[i].end());=\"\" for(int=\"\" i=\"0;i&lt;n;i++)\" {=\"\" for(int=\"\" j=\"0;j&lt;i;j++)\" swap(matrix[i][j],matrix[j][i]);=\"\" }=\"\" }=\"\" void=\"\" rotate(vector<vector<int=\"\"> >& matrix) { rotatea(matrix); rotatea(matrix); }" }, { "code": null, "e": 4264, "s": 4262, "text": "0" }, { "code": null, "e": 4278, "s": 4264, "text": "Dhruv Bajoria" }, { "code": null, "e": 4304, "s": 4278, "text": "This comment was deleted." }, { "code": null, "e": 4306, "s": 4304, "text": "0" }, { "code": null, "e": 4330, "s": 4306, "text": "ANKIT SINHA9 months ago" }, { "code": null, "e": 4342, "s": 4330, "text": "ANKIT SINHA" }, { "code": null, "e": 4373, "s": 4342, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 4519, "s": 4373, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4555, "s": 4519, "text": " Login to access your submissions. " }, { "code": null, "e": 4565, "s": 4555, "text": "\nProblem\n" }, { "code": null, "e": 4575, "s": 4565, "text": "\nContest\n" }, { "code": null, "e": 4638, "s": 4575, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4786, "s": 4638, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4994, "s": 4786, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 5100, "s": 4994, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to Create Wave Loader using CSS? - GeeksforGeeks
17 Jul, 2020 A Wave Loader can be used in websites when something is loading it will provide better user experience, The wave loader can be easily created using HTML and CSS. HTML Code: In this section, we will create a basic div tag which consists of various span tags inside of it. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Wave Loader</title></head><body> <div> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div></body></html> CSS Code: In this section, we will first design the span element using some basic CSS properties, then we will use the nth-child() Selector to select every span element i.e the nth child and then we will create the loading animation using @keyframes rule. <style> *{ margin: 0; padding: 0; } div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } span{ height: 30px; width: 7px; margin-right: 10px; background-color: green; animation: loading 1s linear infinite; } span:nth-child(1){ animation-delay: 0.1s; } span:nth-child(2){ animation-delay: 0.2s; } span:nth-child(3){ animation-delay: 0.3s; } span:nth-child(4){ animation-delay: 0.4s; } span:nth-child(5){ animation-delay: 0.5s; }// @keyframes for animation @keyframes loading { 0%{ height: 0; } 25%{ height: 25px; } 50%{ height: 50px; } 100%{ height: 0; } } </style> Final Code: It is the combination of the above two code sections. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Wave Loader</title></head><style> *{ margin: 0; padding: 0; } div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } span{ height: 30px; width: 7px; margin-right: 10px; background-color: green; animation: loading 1s linear infinite; } span:nth-child(1){ animation-delay: 0.1s; } span:nth-child(2){ animation-delay: 0.2s; } span:nth-child(3){ animation-delay: 0.3s; } span:nth-child(4){ animation-delay: 0.4s; } span:nth-child(5){ animation-delay: 0.5s; } @keyframes loading { 0%{ height: 0; } 25%{ height: 25px; } 50%{ height: 50px; } 100%{ height: 0; } } </style><body> <div> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div></body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS Making a div vertically scrollable using CSS How to set fixed width for <td> in a table ? How to set div width to fit content 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": 24876, "s": 24848, "text": "\n17 Jul, 2020" }, { "code": null, "e": 25038, "s": 24876, "text": "A Wave Loader can be used in websites when something is loading it will provide better user experience, The wave loader can be easily created using HTML and CSS." }, { "code": null, "e": 25147, "s": 25038, "text": "HTML Code: In this section, we will create a basic div tag which consists of various span tags inside of it." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Wave Loader</title></head><body> <div> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div></body></html>", "e": 25478, "s": 25147, "text": null }, { "code": null, "e": 25734, "s": 25478, "text": "CSS Code: In this section, we will first design the span element using some basic CSS properties, then we will use the nth-child() Selector to select every span element i.e the nth child and then we will create the loading animation using @keyframes rule." }, { "code": "<style> *{ margin: 0; padding: 0; } div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } span{ height: 30px; width: 7px; margin-right: 10px; background-color: green; animation: loading 1s linear infinite; } span:nth-child(1){ animation-delay: 0.1s; } span:nth-child(2){ animation-delay: 0.2s; } span:nth-child(3){ animation-delay: 0.3s; } span:nth-child(4){ animation-delay: 0.4s; } span:nth-child(5){ animation-delay: 0.5s; }// @keyframes for animation @keyframes loading { 0%{ height: 0; } 25%{ height: 25px; } 50%{ height: 50px; } 100%{ height: 0; } } </style>", "e": 26485, "s": 25734, "text": null }, { "code": null, "e": 26551, "s": 26485, "text": "Final Code: It is the combination of the above two code sections." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Wave Loader</title></head><style> *{ margin: 0; padding: 0; } div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } span{ height: 30px; width: 7px; margin-right: 10px; background-color: green; animation: loading 1s linear infinite; } span:nth-child(1){ animation-delay: 0.1s; } span:nth-child(2){ animation-delay: 0.2s; } span:nth-child(3){ animation-delay: 0.3s; } span:nth-child(4){ animation-delay: 0.4s; } span:nth-child(5){ animation-delay: 0.5s; } @keyframes loading { 0%{ height: 0; } 25%{ height: 25px; } 50%{ height: 50px; } 100%{ height: 0; } } </style><body> <div> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div></body></html>", "e": 27659, "s": 26551, "text": null }, { "code": null, "e": 27667, "s": 27659, "text": "Output:" }, { "code": null, "e": 27804, "s": 27667, "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": 27813, "s": 27804, "text": "CSS-Misc" }, { "code": null, "e": 27817, "s": 27813, "text": "CSS" }, { "code": null, "e": 27822, "s": 27817, "text": "HTML" }, { "code": null, "e": 27839, "s": 27822, "text": "Web Technologies" }, { "code": null, "e": 27844, "s": 27839, "text": "HTML" }, { "code": null, "e": 27942, "s": 27844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27983, "s": 27942, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28020, "s": 27983, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28065, "s": 28020, "text": "Making a div vertically scrollable using CSS" }, { "code": null, "e": 28110, "s": 28065, "text": "How to set fixed width for <td> in a table ?" }, { "code": null, "e": 28158, "s": 28110, "text": "How to set div width to fit content using CSS ?" }, { "code": null, "e": 28218, "s": 28158, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28279, "s": 28218, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28332, "s": 28279, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28382, "s": 28332, "text": "How to Insert Form Data into Database using PHP ?" } ]
How to delete rows of an R data frame based on string match?
Often, we need to subset our data frame and sometimes this subsetting is based on strings. If we have a character column or a factor column then we might be having its values as a string and we can subset the whole data frame by deleting rows that contain a value or part of a value, for example, we can get rid of all rows that contain set or setosa word in Species column. Consider the below data frame − Character<-c("Andy","Amy","Carolina","Stone","Sam","Carriph","Selcan","Toni","Andrew","Samuel","Samreen","Erturul","Engjin","Engeline","Andreas","Sofia","Yannis","Salvador","Bahattin","Samsa","Orgopolos","Dragos") ID<-1:22 df<-data.frame(ID,Character) df ID Character 1 1 Andy 2 2 Amy 3 3 Carolina 4 4 Stone 5 5 Sam 6 6 Carriph 7 7 Selcan 8 8 Toni 9 9 Andrew 10 10 Samuel 11 11 Samreen 12 12 Erturul 13 13 Engjin 14 14 Engeline 15 15 Andreas 16 16 Sofia 17 17 Yannis 18 18 Salvador 19 19 Bahattin 20 20 Samsa 21 21 Orgopolos 22 22 Dragos df[!grepl("An",df$Character),] ID Character 2 2 Amy 3 3 Carolina 4 4 Stone 5 5 Sam 6 6 Carriph 7 7 Selcan 8 8 Toni 10 10 Samuel 11 11 Samreen 12 12 Erturul 13 13 Engjin 14 14 Engeline 16 16 Sofia 17 17 Yannis 18 18 Salvador 19 19 Bahattin 20 20 Samsa 21 21 Orgopolos 22 22 Dragos df[!grepl("os",df$Character),] ID Character 1 1 Andy 2 2 Amy 3 3 Carolina 4 4 Stone 5 5 Sam 6 6 Carriph 7 7 Selcan 8 8 Toni 9 9 Andrew 10 10 Samuel 11 11 Samreen 12 12 Erturul 13 13 Engjin 14 14 Engeline 15 15 Andreas 16 16 Sofia 17 17 Yannis 18 18 Salvador 19 19 Bahattin 20 20 Samsa df[!grepl("Sam",df$Character),] ID Character 1 1 Andy 2 2 Amy 3 3 Carolina 4 4 Stone 6 6 Carriph 7 7 Selcan 8 8 Toni 9 9 Andrew 12 12 Erturul 13 13 Engjin 14 14 Engeline 15 15 Andreas 16 16 Sofia 17 17 Yannis 18 18 Salvador 19 19 Bahattin 21 21 Orgopolos 22 22 Dragos df[!grepl("on",df$Character),] ID Character 1 1 Andy 2 2 Amy 3 3 Carolina 5 5 Sam 6 6 Carriph 7 7 Selcan 9 9 Andrew 10 10 Samuel 11 11 Samreen 12 12 Erturul 13 13 Engjin 14 14 Engeline 15 15 Andreas 16 16 Sofia 17 17 Yannis 18 18 Salvador 19 19 Bahattin 20 20 Samsa 21 21 Orgopolos 22 22 Dragos df[!grepl("ra",df$Character),] ID Character 1 1 Andy 2 2 Amy 3 3 Carolina 4 4 Stone 5 5 Sam 6 6 Carriph 7 7 Selcan 8 8 Toni 9 9 Andrew 10 10 Samuel 11 11 Samreen 12 12 Erturul 13 13 Engjin 14 14 Engeline 15 15 Andreas 16 16 Sofia 17 17 Yannis 18 18 Salvador 19 19 Bahattin 20 20 Samsa 21 21 Orgopolos Let’s have a look at an example using iris data − head(iris) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa iris[!grepl("set",iris$Species),] Sepal.Length Sepal.Width Petal.Length Petal.Width Species 51 7.0 3.2 4.7 1.4 versicolor 52 6.4 3.2 4.5 1.5 versicolor 53 6.9 3.1 4.9 1.5 versicolor 54 5.5 2.3 4.0 1.3 versicolor 55 6.5 2.8 4.6 1.5 versicolor 56 5.7 2.8 4.5 1.3 versicolor 57 6.3 3.3 4.7 1.6 versicolor 58 4.9 2.4 3.3 1.0 versicolor 59 6.6 2.9 4.6 1.3 versicolor 60 5.2 2.7 3.9 1.4 versicolor 61 5.0 2.0 3.5 1.0 versicolor 62 5.9 3.0 4.2 1.5 versicolor 63 6.0 2.2 4.0 1.0 versicolor 64 6.1 2.9 4.7 1.4 versicolor 65 5.6 2.9 3.6 1.3 versicolor 66 6.7 3.1 4.4 1.4 versicolor 67 5.6 3.0 4.5 1.5 versicolor 68 5.8 2.7 4.1 1.0 versicolor 69 6.2 2.2 4.5 1.5 versicolor 70 5.6 2.5 3.9 1.1 versicolor 71 5.9 3.2 4.8 1.8 versicolor 72 6.1 2.8 4.0 1.3 versicolor 73 6.3 2.5 4.9 1.5 versicolor 74 6.1 2.8 4.7 1.2 versicolor 75 6.4 2.9 4.3 1.3 versicolor 76 6.6 3.0 4.4 1.4 versicolor 77 6.8 2.8 4.8 1.4 versicolor 78 6.7 3.0 5.0 1.7 versicolor 79 6.0 2.9 4.5 1.5 versicolor 80 5.7 2.6 3.5 1.0 versicolor 81 5.5 2.4 3.8 1.1 versicolor 82 5.5 2.4 3.7 1.0 versicolor 83 5.8 2.7 3.9 1.2 versicolor 84 6.0 2.7 5.1 1.6 versicolor 85 5.4 3.0 4.5 1.5 versicolor 86 6.0 3.4 4.5 1.6 versicolor 87 6.7 3.1 4.7 1.5 versicolor 88 6.3 2.3 4.4 1.3 versicolor 89 5.6 3.0 4.1 1.3 versicolor 90 5.5 2.5 4.0 1.3 versicolor 91 5.5 2.6 4.4 1.2 versicolor 92 6.1 3.0 4.6 1.4 versicolor 93 5.8 2.6 4.0 1.2 versicolor 94 5.0 2.3 3.3 1.0 versicolor 95 5.6 2.7 4.2 1.3 versicolor 96 5.7 3.0 4.2 1.2 versicolor 97 5.7 2.9 4.2 1.3 versicolor 98 6.2 2.9 4.3 1.3 versicolor 99 5.1 2.5 3.0 1.1 versicolor 100 5.7 2.8 4.1 1.3 versicolor 101 6.3 3.3 6.0 2.5 virginica 102 5.8 2.7 5.1 1.9 virginica 103 7.1 3.0 5.9 2.1 virginica 104 6.3 2.9 5.6 1.8 virginica 105 6.5 3.0 5.8 2.2 virginica 106 7.6 3.0 6.6 2.1 virginica 107 4.9 2.5 4.5 1.7 virginica 108 7.3 2.9 6.3 1.8 virginica 109 6.7 2.5 5.8 1.8 virginica 110 7.2 3.6 6.1 2.5 virginica 111 6.5 3.2 5.1 2.0 virginica 112 6.4 2.7 5.3 1.9 virginica 113 6.8 3.0 5.5 2.1 virginica 114 5.7 2.5 5.0 2.0 virginica 115 5.8 2.8 5.1 2.4 virginica 116 6.4 3.2 5.3 2.3 virginica 117 6.5 3.0 5.5 1.8 virginica 118 7.7 3.8 6.7 2.2 virginica 119 7.7 2.6 6.9 2.3 virginica 120 6.0 2.2 5.0 1.5 virginica 121 6.9 3.2 5.7 2.3 virginica 122 5.6 2.8 4.9 2.0 virginica 123 7.7 2.8 6.7 2.0 virginica 124 6.3 2.7 4.9 1.8 virginica 125 6.7 3.3 5.7 2.1 virginica 126 7.2 3.2 6.0 1.8 virginica 127 6.2 2.8 4.8 1.8 virginica 128 6.1 3.0 4.9 1.8 virginica 129 6.4 2.8 5.6 2.1 virginica 130 7.2 3.0 5.8 1.6 virginica 131 7.4 2.8 6.1 1.9 virginica 132 7.9 3.8 6.4 2.0 virginica 133 6.4 2.8 5.6 2.2 virginica 134 6.3 2.8 5.1 1.5 virginica 135 6.1 2.6 5.6 1.4 virginica 136 7.7 3.0 6.1 2.3 virginica 137 6.3 3.4 5.6 2.4 virginica 138 6.4 3.1 5.5 1.8 virginica 139 6.0 3.0 4.8 1.8 virginica 140 6.9 3.1 5.4 2.1 virginica 141 6.7 3.1 5.6 2.4 virginica 142 6.9 3.1 5.1 2.3 virginica 143 5.8 2.7 5.1 1.9 virginica 144 6.8 3.2 5.9 2.3 virginica 145 6.7 3.3 5.7 2.5 virginica 146 6.7 3.0 5.2 2.3 virginica 147 6.3 2.5 5.0 1.9 virginica 148 6.5 3.0 5.2 2.0 virginica 149 6.2 3.4 5.4 2.3 virginica 150 5.9 3.0 5.1 1.8 virginica
[ { "code": null, "e": 1437, "s": 1062, "text": "Often, we need to subset our data frame and sometimes this subsetting is based on strings. If we have a character column or a factor column then we might be having its values as a string and we can subset the whole data frame by deleting rows that contain a value or part of a value, for example, we can get rid of all rows that contain set or setosa word in Species column." }, { "code": null, "e": 1469, "s": 1437, "text": "Consider the below data frame −" }, { "code": null, "e": 1724, "s": 1469, "text": "Character<-c(\"Andy\",\"Amy\",\"Carolina\",\"Stone\",\"Sam\",\"Carriph\",\"Selcan\",\"Toni\",\"Andrew\",\"Samuel\",\"Samreen\",\"Erturul\",\"Engjin\",\"Engeline\",\"Andreas\",\"Sofia\",\"Yannis\",\"Salvador\",\"Bahattin\",\"Samsa\",\"Orgopolos\",\"Dragos\")\nID<-1:22\ndf<-data.frame(ID,Character)\ndf" }, { "code": null, "e": 2007, "s": 1724, "text": "ID Character\n1 1 Andy\n2 2 Amy\n3 3 Carolina\n4 4 Stone\n5 5 Sam\n6 6 Carriph\n7 7 Selcan\n8 8 Toni\n9 9 Andrew\n10 10 Samuel\n11 11 Samreen\n12 12 Erturul\n13 13 Engjin\n14 14 Engeline\n15 15 Andreas\n16 16 Sofia\n17 17 Yannis\n18 18 Salvador\n19 19 Bahattin\n20 20 Samsa\n21 21 Orgopolos\n22 22 Dragos" }, { "code": null, "e": 2038, "s": 2007, "text": "df[!grepl(\"An\",df$Character),]" }, { "code": null, "e": 2287, "s": 2038, "text": "ID Character\n2 2 Amy\n3 3 Carolina\n4 4 Stone\n5 5 Sam\n6 6 Carriph\n7 7 Selcan\n8 8 Toni\n10 10 Samuel\n11 11 Samreen\n12 12 Erturul\n13 13 Engjin\n14 14 Engeline\n16 16 Sofia\n17 17 Yannis\n18 18 Salvador\n19 19 Bahattin\n20 20 Samsa\n21 21 Orgopolos\n22 22 Dragos" }, { "code": null, "e": 2318, "s": 2287, "text": "df[!grepl(\"os\",df$Character),]" }, { "code": null, "e": 2572, "s": 2318, "text": "ID Character\n1 1 Andy\n2 2 Amy\n3 3 Carolina\n4 4 Stone\n5 5 Sam\n6 6 Carriph\n7 7 Selcan\n8 8 Toni\n9 9 Andrew\n10 10 Samuel\n11 11 Samreen\n12 12 Erturul\n13 13 Engjin\n14 14 Engeline\n15 15 Andreas\n16 16 Sofia\n17 17 Yannis\n18 18 Salvador\n19 19 Bahattin\n20 20 Samsa" }, { "code": null, "e": 2604, "s": 2572, "text": "df[!grepl(\"Sam\",df$Character),]" }, { "code": null, "e": 2840, "s": 2604, "text": "ID Character\n1 1 Andy\n2 2 Amy\n3 3 Carolina\n4 4 Stone\n6 6 Carriph\n7 7 Selcan\n8 8 Toni\n9 9 Andrew\n12 12 Erturul\n13 13 Engjin\n14 14 Engeline\n15 15 Andreas\n16 16 Sofia\n17 17 Yannis\n18 18 Salvador\n19 19 Bahattin\n21 21 Orgopolos\n22 22 Dragos" }, { "code": null, "e": 2871, "s": 2840, "text": "df[!grepl(\"on\",df$Character),]" }, { "code": null, "e": 3135, "s": 2871, "text": "ID Character\n1 1 Andy\n2 2 Amy\n3 3 Carolina\n5 5 Sam\n6 6 Carriph\n7 7 Selcan\n9 9 Andrew\n10 10 Samuel\n11 11 Samreen\n12 12 Erturul\n13 13 Engjin\n14 14 Engeline\n15 15 Andreas\n16 16 Sofia\n17 17 Yannis\n18 18 Salvador\n19 19 Bahattin\n20 20 Samsa\n21 21 Orgopolos\n22 22 Dragos" }, { "code": null, "e": 3166, "s": 3135, "text": "df[!grepl(\"ra\",df$Character),]" }, { "code": null, "e": 3436, "s": 3166, "text": "ID Character\n1 1 Andy\n2 2 Amy\n3 3 Carolina\n4 4 Stone\n5 5 Sam\n6 6 Carriph\n7 7 Selcan\n8 8 Toni\n9 9 Andrew\n10 10 Samuel\n11 11 Samreen\n12 12 Erturul\n13 13 Engjin\n14 14 Engeline\n15 15 Andreas\n16 16 Sofia\n17 17 Yannis\n18 18 Salvador\n19 19 Bahattin\n20 20 Samsa\n21 21 Orgopolos" }, { "code": null, "e": 3486, "s": 3436, "text": "Let’s have a look at an example using iris data −" }, { "code": null, "e": 3497, "s": 3486, "text": "head(iris)" }, { "code": null, "e": 3705, "s": 3497, "text": "Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n1 5.1 3.5 1.4 0.2 setosa\n2 4.9 3.0 1.4 0.2 setosa\n3 4.7 3.2 1.3 0.2 setosa\n4 4.6 3.1 1.5 0.2 setosa\n5 5.0 3.6 1.4 0.2 setosa\n6 5.4 3.9 1.7 0.4 setosa" }, { "code": null, "e": 3739, "s": 3705, "text": "iris[!grepl(\"set\",iris$Species),]" }, { "code": null, "e": 6798, "s": 3739, "text": "Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n51 7.0 3.2 4.7 1.4 versicolor\n52 6.4 3.2 4.5 1.5 versicolor\n53 6.9 3.1 4.9 1.5 versicolor\n54 5.5 2.3 4.0 1.3 versicolor\n55 6.5 2.8 4.6 1.5 versicolor\n56 5.7 2.8 4.5 1.3 versicolor\n57 6.3 3.3 4.7 1.6 versicolor\n58 4.9 2.4 3.3 1.0 versicolor\n59 6.6 2.9 4.6 1.3 versicolor\n60 5.2 2.7 3.9 1.4 versicolor\n61 5.0 2.0 3.5 1.0 versicolor\n62 5.9 3.0 4.2 1.5 versicolor\n63 6.0 2.2 4.0 1.0 versicolor\n64 6.1 2.9 4.7 1.4 versicolor\n65 5.6 2.9 3.6 1.3 versicolor\n66 6.7 3.1 4.4 1.4 versicolor\n67 5.6 3.0 4.5 1.5 versicolor\n68 5.8 2.7 4.1 1.0 versicolor\n69 6.2 2.2 4.5 1.5 versicolor\n70 5.6 2.5 3.9 1.1 versicolor\n71 5.9 3.2 4.8 1.8 versicolor\n72 6.1 2.8 4.0 1.3 versicolor\n73 6.3 2.5 4.9 1.5 versicolor\n74 6.1 2.8 4.7 1.2 versicolor\n75 6.4 2.9 4.3 1.3 versicolor\n76 6.6 3.0 4.4 1.4 versicolor\n77 6.8 2.8 4.8 1.4 versicolor\n78 6.7 3.0 5.0 1.7 versicolor\n79 6.0 2.9 4.5 1.5 versicolor\n80 5.7 2.6 3.5 1.0 versicolor\n81 5.5 2.4 3.8 1.1 versicolor\n82 5.5 2.4 3.7 1.0 versicolor\n83 5.8 2.7 3.9 1.2 versicolor\n84 6.0 2.7 5.1 1.6 versicolor\n85 5.4 3.0 4.5 1.5 versicolor\n86 6.0 3.4 4.5 1.6 versicolor\n87 6.7 3.1 4.7 1.5 versicolor\n88 6.3 2.3 4.4 1.3 versicolor\n89 5.6 3.0 4.1 1.3 versicolor\n90 5.5 2.5 4.0 1.3 versicolor\n91 5.5 2.6 4.4 1.2 versicolor\n92 6.1 3.0 4.6 1.4 versicolor\n93 5.8 2.6 4.0 1.2 versicolor\n94 5.0 2.3 3.3 1.0 versicolor\n95 5.6 2.7 4.2 1.3 versicolor\n96 5.7 3.0 4.2 1.2 versicolor\n97 5.7 2.9 4.2 1.3 versicolor\n98 6.2 2.9 4.3 1.3 versicolor\n99 5.1 2.5 3.0 1.1 versicolor\n100 5.7 2.8 4.1 1.3 versicolor\n101 6.3 3.3 6.0 2.5 virginica\n102 5.8 2.7 5.1 1.9 virginica\n103 7.1 3.0 5.9 2.1 virginica\n104 6.3 2.9 5.6 1.8 virginica\n105 6.5 3.0 5.8 2.2 virginica\n106 7.6 3.0 6.6 2.1 virginica\n107 4.9 2.5 4.5 1.7 virginica\n108 7.3 2.9 6.3 1.8 virginica\n109 6.7 2.5 5.8 1.8 virginica\n110 7.2 3.6 6.1 2.5 virginica\n111 6.5 3.2 5.1 2.0 virginica\n112 6.4 2.7 5.3 1.9 virginica\n113 6.8 3.0 5.5 2.1 virginica\n114 5.7 2.5 5.0 2.0 virginica\n115 5.8 2.8 5.1 2.4 virginica\n116 6.4 3.2 5.3 2.3 virginica\n117 6.5 3.0 5.5 1.8 virginica\n118 7.7 3.8 6.7 2.2 virginica\n119 7.7 2.6 6.9 2.3 virginica\n120 6.0 2.2 5.0 1.5 virginica\n121 6.9 3.2 5.7 2.3 virginica\n122 5.6 2.8 4.9 2.0 virginica\n123 7.7 2.8 6.7 2.0 virginica\n124 6.3 2.7 4.9 1.8 virginica\n125 6.7 3.3 5.7 2.1 virginica\n126 7.2 3.2 6.0 1.8 virginica\n127 6.2 2.8 4.8 1.8 virginica\n128 6.1 3.0 4.9 1.8 virginica\n129 6.4 2.8 5.6 2.1 virginica\n130 7.2 3.0 5.8 1.6 virginica\n131 7.4 2.8 6.1 1.9 virginica\n132 7.9 3.8 6.4 2.0 virginica\n133 6.4 2.8 5.6 2.2 virginica\n134 6.3 2.8 5.1 1.5 virginica\n135 6.1 2.6 5.6 1.4 virginica\n136 7.7 3.0 6.1 2.3 virginica\n137 6.3 3.4 5.6 2.4 virginica\n138 6.4 3.1 5.5 1.8 virginica\n139 6.0 3.0 4.8 1.8 virginica\n140 6.9 3.1 5.4 2.1 virginica\n141 6.7 3.1 5.6 2.4 virginica\n142 6.9 3.1 5.1 2.3 virginica\n143 5.8 2.7 5.1 1.9 virginica\n144 6.8 3.2 5.9 2.3 virginica\n145 6.7 3.3 5.7 2.5 virginica\n146 6.7 3.0 5.2 2.3 virginica\n147 6.3 2.5 5.0 1.9 virginica\n148 6.5 3.0 5.2 2.0 virginica\n149 6.2 3.4 5.4 2.3 virginica\n150 5.9 3.0 5.1 1.8 virginica" } ]
Check if any permutation of a large number is divisible by 8 in Python
Suppose, we are provided with a huge number and we have to find out whether any permutation of the digits of the number is divisible by 8. The number is provided to us in string format. So, if the input is like: input_num = 4696984, then the output will be “Divisible by eight”. To solve this problem, we will check all the three-digit permutations possible with the digits of the number and see if they can occur in any all-digit permutation of the number. If a three-digit permutation divisible by eight occurs at the end of an all-digit permutation of the number, we will say that permutation is divisible by 8. To solve this, we will follow these steps − if length of input_num < 3, thenif input_num mod 8 is same as 0, thenreturn Trueinput_num := reverse of input_numif input_num mod 8 is same as 0, thenreturn Truereturn False if input_num mod 8 is same as 0, thenreturn True return True input_num := reverse of input_num if input_num mod 8 is same as 0, thenreturn True return True return False temp_arr := a new list of size 10 initialized by 0s. for count in range 0 to size of input_num, do temp_arr[input_num[count] - 0] := temp_arr[input_num[count] - 0] + 1 for count in range 104 to 999, increase by 8, dotemp := countoccurences := a new list of size 10 initialized by 0s.occurences[temp mod 10] := occurences[temp mod 10] + 1temp := temp / 10occurences[temp mod 10] := occurences[temp mod 10] + 1temp := temp / 10occurences[temp mod 10] := occurences[temp mod 10] + 1temp := countif occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iterationtemp := temp / 10if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iterationtemp := temp / 10if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iterationreturn True temp := count occurences := a new list of size 10 initialized by 0s. occurences[temp mod 10] := occurences[temp mod 10] + 1 temp := temp / 10 occurences[temp mod 10] := occurences[temp mod 10] + 1 temp := temp / 10 occurences[temp mod 10] := occurences[temp mod 10] + 1 temp := count if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iteration go for next iteration temp := temp / 10 if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iteration go for next iteration temp := temp / 10 if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iteration go for next iteration return True return False Let us see the following implementation to get better understanding − Live Demo def solve(input_num): if len(input_num) < 3: if int(input_num) % 8 == 0: return True input_num = input_num[::-1] if int(input_num) % 8 == 0: return True return False temp_arr = 10 * [0] for count in range(0, len(input_num)): temp_arr[int(input_num[count]) - 0] += 1 for count in range(104, 1000, 8): temp = count occurences = 10 * [0] occurences[int(temp % 10)] += 1 temp = temp / 10 occurences[int(temp % 10)] += 1 temp = temp / 10 occurences[int(temp % 10)] += 1 temp = count if (occurences[int(temp % 10)] > temp_arr[int(temp % 10)]): continue temp = temp / 10 if (occurences[int(temp % 10)] > temp_arr[int(temp % 10)]): continue temp = temp / 10 if (occurences[int(temp % 10)] > temp_arr[int(temp % 10)]): continue return True return False if solve("4696984"): print("Divisible by eight") else: print("Not divisible by eight") 4696984 Divisible by eight
[ { "code": null, "e": 1248, "s": 1062, "text": "Suppose, we are provided with a huge number and we have to find out whether any permutation of the digits of the number is divisible by 8. The number is provided to us in string format." }, { "code": null, "e": 1341, "s": 1248, "text": "So, if the input is like: input_num = 4696984, then the output will be “Divisible by eight”." }, { "code": null, "e": 1677, "s": 1341, "text": "To solve this problem, we will check all the three-digit permutations possible with the digits of the number and see if they can occur in any all-digit permutation of the number. If a three-digit permutation divisible by eight occurs at the end of an all-digit permutation of the number, we will say that permutation is divisible by 8." }, { "code": null, "e": 1721, "s": 1677, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1895, "s": 1721, "text": "if length of input_num < 3, thenif input_num mod 8 is same as 0, thenreturn Trueinput_num := reverse of input_numif input_num mod 8 is same as 0, thenreturn Truereturn False" }, { "code": null, "e": 1944, "s": 1895, "text": "if input_num mod 8 is same as 0, thenreturn True" }, { "code": null, "e": 1956, "s": 1944, "text": "return True" }, { "code": null, "e": 1990, "s": 1956, "text": "input_num := reverse of input_num" }, { "code": null, "e": 2039, "s": 1990, "text": "if input_num mod 8 is same as 0, thenreturn True" }, { "code": null, "e": 2051, "s": 2039, "text": "return True" }, { "code": null, "e": 2064, "s": 2051, "text": "return False" }, { "code": null, "e": 2117, "s": 2064, "text": "temp_arr := a new list of size 10 initialized by 0s." }, { "code": null, "e": 2163, "s": 2117, "text": "for count in range 0 to size of input_num, do" }, { "code": null, "e": 2232, "s": 2163, "text": "temp_arr[input_num[count] - 0] := temp_arr[input_num[count] - 0] + 1" }, { "code": null, "e": 2833, "s": 2232, "text": "for count in range 104 to 999, increase by 8, dotemp := countoccurences := a new list of size 10 initialized by 0s.occurences[temp mod 10] := occurences[temp mod 10] + 1temp := temp / 10occurences[temp mod 10] := occurences[temp mod 10] + 1temp := temp / 10occurences[temp mod 10] := occurences[temp mod 10] + 1temp := countif occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iterationtemp := temp / 10if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iterationtemp := temp / 10if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iterationreturn True" }, { "code": null, "e": 2847, "s": 2833, "text": "temp := count" }, { "code": null, "e": 2902, "s": 2847, "text": "occurences := a new list of size 10 initialized by 0s." }, { "code": null, "e": 2957, "s": 2902, "text": "occurences[temp mod 10] := occurences[temp mod 10] + 1" }, { "code": null, "e": 2975, "s": 2957, "text": "temp := temp / 10" }, { "code": null, "e": 3030, "s": 2975, "text": "occurences[temp mod 10] := occurences[temp mod 10] + 1" }, { "code": null, "e": 3048, "s": 3030, "text": "temp := temp / 10" }, { "code": null, "e": 3103, "s": 3048, "text": "occurences[temp mod 10] := occurences[temp mod 10] + 1" }, { "code": null, "e": 3117, "s": 3103, "text": "temp := count" }, { "code": null, "e": 3195, "s": 3117, "text": "if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iteration" }, { "code": null, "e": 3217, "s": 3195, "text": "go for next iteration" }, { "code": null, "e": 3235, "s": 3217, "text": "temp := temp / 10" }, { "code": null, "e": 3313, "s": 3235, "text": "if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iteration" }, { "code": null, "e": 3335, "s": 3313, "text": "go for next iteration" }, { "code": null, "e": 3353, "s": 3335, "text": "temp := temp / 10" }, { "code": null, "e": 3431, "s": 3353, "text": "if occurences[temp mod 10] > temp_arr[temp mod 10], thengo for next iteration" }, { "code": null, "e": 3453, "s": 3431, "text": "go for next iteration" }, { "code": null, "e": 3465, "s": 3453, "text": "return True" }, { "code": null, "e": 3478, "s": 3465, "text": "return False" }, { "code": null, "e": 3548, "s": 3478, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3559, "s": 3548, "text": " Live Demo" }, { "code": null, "e": 4603, "s": 3559, "text": "def solve(input_num):\n if len(input_num) < 3:\n if int(input_num) % 8 == 0:\n return True\n input_num = input_num[::-1]\n if int(input_num) % 8 == 0:\n return True\n return False\n temp_arr = 10 * [0]\n for count in range(0, len(input_num)):\n temp_arr[int(input_num[count]) - 0] += 1\n for count in range(104, 1000, 8):\n temp = count\n occurences = 10 * [0]\n occurences[int(temp % 10)] += 1\n temp = temp / 10\n occurences[int(temp % 10)] += 1\n temp = temp / 10\n occurences[int(temp % 10)] += 1\n temp = count\n if (occurences[int(temp % 10)] >\n temp_arr[int(temp % 10)]):\n continue\n temp = temp / 10\n if (occurences[int(temp % 10)] >\n temp_arr[int(temp % 10)]):\n continue\n temp = temp / 10\n if (occurences[int(temp % 10)] >\n temp_arr[int(temp % 10)]):\n continue\n return True\n return False\nif solve(\"4696984\"):\n print(\"Divisible by eight\")\nelse:\n print(\"Not divisible by eight\")" }, { "code": null, "e": 4611, "s": 4603, "text": "4696984" }, { "code": null, "e": 4630, "s": 4611, "text": "Divisible by eight" } ]
Creating a Telegram Chatbot Quiz with Python | by Beppe Catanese | Towards Data Science
One of the features that make Telegram a great Chatbot platform is the ability to create Polls. This was introduced in 2019, later improved by adding the Quiz mode and, most importantly, by making it available to the Telegram Chatbot API. It is possible to create a Poll directly in the Telegram application (without coding) but here we will explore how to develop from scratch a Telegram Chatbot quiz using the Python Telegram Bot library. First some warming up: play with a live example and test your knowledge of the world’s capitals 😎. Kick off the conversation with the /start command (*). t.me (*) Please be patient, it runs on-demand and might take few seconds to wake up and start chatting 😊 The setup involves 3 steps: talk the BotFather to create a new chatbot and obtain the authorization Token configure the Updater object and the method handlers start the chatbot (in Polling mode in this example, but a Webhook could be used instead) def main(): updater = Updater('secret token', use_context=True) dp = updater.dispatcher # command handlers dp.add_handler(CommandHandler("help", help_command_handler)) # message handler dp.add_handler(MessageHandler(Filters.text, main_handler)) # quiz handler dp.add_handler(PollHandler(poll_handler, pass_chat_data=True, pass_user_data=True)) # start updater.start_polling() updater.idle() It is important to understand that the handlers defined above are responsible for processing the ‘help’ Command, simple text messages and Poll answers. We are going first to create a helper method to grab the Chat id: this is going to be very useful in this tutorial, but also if you develop other Telegram Chatbots. # extract chat_id based on the incoming objectdef get_chat_id(update, context): chat_id = -1 if update.message is not None: chat_id = update.message.chat.id elif update.callback_query is not None: chat_id = update.callback_query.message.chat.id elif update.poll is not None: chat_id = context.bot_data[update.poll.id] return chat_id Creating a Quiz answer can be done using the send_poll method c_id = get_chat_id(update, context)q = 'What is the capital of Italy?'answers = ['Rome', 'London', 'Amsterdam']message = context.bot.send_poll(chat_id=c_id, question=q, options=answers, type=Poll.QUIZ, correct_option_id=0) The type must be Poll.QUIZ to trigger the Quiz effects (confetti upon choosing the right answer) and thecorrect_option_id must match (positionally) the correct option in the provided list of answers. Let’s not stop at the basics but make the Quiz a little bit fancier. It is possible to add a countdown to make it more exciting: message = context.bot.send_poll(chat_id=c_id, question=q, options=answers, type=Poll.QUIZ, correct_option_id=0, open_period=5) An additional explanation can be included to provide extra information after the user has answered: notice the lamp icon available to the user. message = context.bot.send_poll(chat_id=c_id, question=q, options=answers, type=Poll.QUIZ, correct_option_id=0, explanation= 'Well, honestly that depends on what you eat', explanation_parse_mode = telegram.ParseMode.MARKDOWN_V2) It is important to understand how to process the user answers. The Telegram BOT API provides the methods and objects to render a nice interface as well as celebrating the correct answer (or marking a wrong response). However, the developer needs to track the successful answers and build the necessary logic, like for example calculating a score, increasing the complexity of the following question, etc... All quiz answers are sent to the PollHandler where the update object will carry the payload with all necessary information # handling Poll answersdef poll_handler(update, context): # Quiz question question = update.poll.question # position of correct answer correct_answer = update.poll.correct_option_id # first option (text and voted yes|no) option_1_text = update.poll.options[0].text option_1_vote = update.poll.options[0].voter_count Each option in the payload indicates if it has been voted or not (voter_count equal to 1). # find the answer chosen by the userdef get_answer(update): answers = update.poll.options ret = "" for answer in answers: if answer.voter_count == 1: # found it ret = answer.text break return ret Using the correct_option_id it is possible to establish whether the answer given by the user is correct or not. # determine if user answer is correctdef is_answer_correct(update): answers = update.poll.options ret = False counter = 0 for answer in answers: if answer.voter_count == 1 and \ update.poll.correct_option_id == counter: ret = True break counter = counter + 1 return ret It is possible to create a Regular Poll instead of a Quiz: the logic and code are the same, however, there are some differences that make the standard Poll more suitable for surveys and questionnaires: no confetti celebration allowing multiple answers make results visible to the users message = context.bot.send_poll(chat_id=cid, question=q, options=answers, type=Poll.REGULAR, allows_multiple_answers=True,is_anonymous=False) We have introduced all key concepts of developing a Quiz on Telegram, check out the Github repo to start from a base Quiz implementation with the code snippets presented in the article. If you are developing Telegram chatbots you might find this useful: towardsdatascience.com Find me on Twitter for questions and suggestions and, if you create a Telegram Quiz chatbot, share it with me!
[ { "code": null, "e": 411, "s": 172, "text": "One of the features that make Telegram a great Chatbot platform is the ability to create Polls. This was introduced in 2019, later improved by adding the Quiz mode and, most importantly, by making it available to the Telegram Chatbot API." }, { "code": null, "e": 613, "s": 411, "text": "It is possible to create a Poll directly in the Telegram application (without coding) but here we will explore how to develop from scratch a Telegram Chatbot quiz using the Python Telegram Bot library." }, { "code": null, "e": 767, "s": 613, "text": "First some warming up: play with a live example and test your knowledge of the world’s capitals 😎. Kick off the conversation with the /start command (*)." }, { "code": null, "e": 772, "s": 767, "text": "t.me" }, { "code": null, "e": 872, "s": 772, "text": "(*) Please be patient, it runs on-demand and might take few seconds to wake up and start chatting 😊" }, { "code": null, "e": 900, "s": 872, "text": "The setup involves 3 steps:" }, { "code": null, "e": 978, "s": 900, "text": "talk the BotFather to create a new chatbot and obtain the authorization Token" }, { "code": null, "e": 1031, "s": 978, "text": "configure the Updater object and the method handlers" }, { "code": null, "e": 1120, "s": 1031, "text": "start the chatbot (in Polling mode in this example, but a Webhook could be used instead)" }, { "code": null, "e": 1522, "s": 1120, "text": "def main(): updater = Updater('secret token', use_context=True) dp = updater.dispatcher # command handlers dp.add_handler(CommandHandler(\"help\", help_command_handler)) # message handler dp.add_handler(MessageHandler(Filters.text, main_handler)) # quiz handler dp.add_handler(PollHandler(poll_handler, pass_chat_data=True, pass_user_data=True)) # start updater.start_polling() updater.idle()" }, { "code": null, "e": 1674, "s": 1522, "text": "It is important to understand that the handlers defined above are responsible for processing the ‘help’ Command, simple text messages and Poll answers." }, { "code": null, "e": 1839, "s": 1674, "text": "We are going first to create a helper method to grab the Chat id: this is going to be very useful in this tutorial, but also if you develop other Telegram Chatbots." }, { "code": null, "e": 2186, "s": 1839, "text": "# extract chat_id based on the incoming objectdef get_chat_id(update, context): chat_id = -1 if update.message is not None: chat_id = update.message.chat.id elif update.callback_query is not None: chat_id = update.callback_query.message.chat.id elif update.poll is not None: chat_id = context.bot_data[update.poll.id] return chat_id" }, { "code": null, "e": 2248, "s": 2186, "text": "Creating a Quiz answer can be done using the send_poll method" }, { "code": null, "e": 2471, "s": 2248, "text": "c_id = get_chat_id(update, context)q = 'What is the capital of Italy?'answers = ['Rome', 'London', 'Amsterdam']message = context.bot.send_poll(chat_id=c_id, question=q, options=answers, type=Poll.QUIZ, correct_option_id=0)" }, { "code": null, "e": 2671, "s": 2471, "text": "The type must be Poll.QUIZ to trigger the Quiz effects (confetti upon choosing the right answer) and thecorrect_option_id must match (positionally) the correct option in the provided list of answers." }, { "code": null, "e": 2740, "s": 2671, "text": "Let’s not stop at the basics but make the Quiz a little bit fancier." }, { "code": null, "e": 2800, "s": 2740, "text": "It is possible to add a countdown to make it more exciting:" }, { "code": null, "e": 2927, "s": 2800, "text": "message = context.bot.send_poll(chat_id=c_id, question=q, options=answers, type=Poll.QUIZ, correct_option_id=0, open_period=5)" }, { "code": null, "e": 3071, "s": 2927, "text": "An additional explanation can be included to provide extra information after the user has answered: notice the lamp icon available to the user." }, { "code": null, "e": 3300, "s": 3071, "text": "message = context.bot.send_poll(chat_id=c_id, question=q, options=answers, type=Poll.QUIZ, correct_option_id=0, explanation= 'Well, honestly that depends on what you eat', explanation_parse_mode = telegram.ParseMode.MARKDOWN_V2)" }, { "code": null, "e": 3363, "s": 3300, "text": "It is important to understand how to process the user answers." }, { "code": null, "e": 3707, "s": 3363, "text": "The Telegram BOT API provides the methods and objects to render a nice interface as well as celebrating the correct answer (or marking a wrong response). However, the developer needs to track the successful answers and build the necessary logic, like for example calculating a score, increasing the complexity of the following question, etc..." }, { "code": null, "e": 3830, "s": 3707, "text": "All quiz answers are sent to the PollHandler where the update object will carry the payload with all necessary information" }, { "code": null, "e": 4153, "s": 3830, "text": "# handling Poll answersdef poll_handler(update, context): # Quiz question question = update.poll.question # position of correct answer correct_answer = update.poll.correct_option_id # first option (text and voted yes|no) option_1_text = update.poll.options[0].text option_1_vote = update.poll.options[0].voter_count" }, { "code": null, "e": 4244, "s": 4153, "text": "Each option in the payload indicates if it has been voted or not (voter_count equal to 1)." }, { "code": null, "e": 4462, "s": 4244, "text": "# find the answer chosen by the userdef get_answer(update): answers = update.poll.options ret = \"\" for answer in answers: if answer.voter_count == 1: # found it ret = answer.text break return ret" }, { "code": null, "e": 4574, "s": 4462, "text": "Using the correct_option_id it is possible to establish whether the answer given by the user is correct or not." }, { "code": null, "e": 4884, "s": 4574, "text": "# determine if user answer is correctdef is_answer_correct(update): answers = update.poll.options ret = False counter = 0 for answer in answers: if answer.voter_count == 1 and \\ update.poll.correct_option_id == counter: ret = True break counter = counter + 1 return ret" }, { "code": null, "e": 5086, "s": 4884, "text": "It is possible to create a Regular Poll instead of a Quiz: the logic and code are the same, however, there are some differences that make the standard Poll more suitable for surveys and questionnaires:" }, { "code": null, "e": 5110, "s": 5086, "text": "no confetti celebration" }, { "code": null, "e": 5136, "s": 5110, "text": "allowing multiple answers" }, { "code": null, "e": 5170, "s": 5136, "text": "make results visible to the users" }, { "code": null, "e": 5312, "s": 5170, "text": "message = context.bot.send_poll(chat_id=cid, question=q, options=answers, type=Poll.REGULAR, allows_multiple_answers=True,is_anonymous=False)" }, { "code": null, "e": 5498, "s": 5312, "text": "We have introduced all key concepts of developing a Quiz on Telegram, check out the Github repo to start from a base Quiz implementation with the code snippets presented in the article." }, { "code": null, "e": 5566, "s": 5498, "text": "If you are developing Telegram chatbots you might find this useful:" }, { "code": null, "e": 5589, "s": 5566, "text": "towardsdatascience.com" } ]
What are unchecked exceptions in Java?
An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. If you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs. Live Demo public class Unchecked_Demo { public static void main(String args[]) { int num[] = {1, 2, 3, 4}; System.out.println(num[5]); } } Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
[ { "code": null, "e": 1320, "s": 1062, "text": "An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. " }, { "code": null, "e": 1481, "s": 1320, "text": "If you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs." }, { "code": null, "e": 1491, "s": 1481, "text": "Live Demo" }, { "code": null, "e": 1638, "s": 1491, "text": "public class Unchecked_Demo {\n public static void main(String args[]) {\n int num[] = {1, 2, 3, 4};\n System.out.println(num[5]);\n }\n}" }, { "code": null, "e": 1769, "s": 1638, "text": "Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 5\n at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)" } ]
How to read data from JSON array using JavaScript?
Following is the code to read data from JSON array using JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample,.result { font-size: 18px; font-weight: 500; color: red; } </style> </head> <body> <h1>Read data from JSON array using JavaScript</h1> <div class="sample"> [{"name":"Rohan","age":22}, {"name":"Shawn","age":12} ,{"name":"Michael","age":21}] </div> <div class="result" style="color: green;"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to read data from above JSON array</h3> <script> let sampleEle = document.querySelector(".sample"); let resultEle = document.querySelector(".result"); let parsedJson = JSON.parse(sampleEle.innerHTML); document.querySelector(".Btn").addEventListener("click", () => { parsedJson.forEach((item) => { resultEle.innerHTML += "Name = " + item.name + ""; resultEle.innerHTML += "Age = " + item.age + ""; }); }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1132, "s": 1062, "text": "Following is the code to read data from JSON array using JavaScript −" }, { "code": null, "e": 1143, "s": 1132, "text": " Live Demo" }, { "code": null, "e": 2270, "s": 1143, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .sample,.result {\n font-size: 18px;\n font-weight: 500;\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>Read data from JSON array using JavaScript</h1>\n<div class=\"sample\">\n[{\"name\":\"Rohan\",\"age\":22}, {\"name\":\"Shawn\",\"age\":12} ,{\"name\":\"Michael\",\"age\":21}]\n</div>\n<div class=\"result\" style=\"color: green;\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to read data from above JSON array</h3>\n<script>\n let sampleEle = document.querySelector(\".sample\");\n let resultEle = document.querySelector(\".result\");\n let parsedJson = JSON.parse(sampleEle.innerHTML);\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n parsedJson.forEach((item) => {\n resultEle.innerHTML += \"Name = \" + item.name + \"\";\n resultEle.innerHTML += \"Age = \" + item.age + \"\";\n });\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2321, "s": 2270, "text": "The above code will produce the following output −" }, { "code": null, "e": 2359, "s": 2321, "text": "On clicking the ‘CLICK HERE’ button −" } ]
Retrieving And Updating Data Contained in Shelve in Python - GeeksforGeeks
06 Jan, 2019 In Python shelve you access the keys randomly. In order to access the keys randomly in python shelve we use open() function. This function works a lot like the file open() function in File handling. Syntax for open the file using Python shelve shelve.open(filename, flag='c' , writeback=True) In Order to access the keys randomly in shelve in Python, we have to take three steps: Storing Python shelve data Retrieving Python shelve data Updating Python shelve data Storing Python shelve data :In order to store python shelve data, we have to create a file with full of datasets and open them with a open() function this function open a file which we have created. # At first, we have to import the 'Shelve' module.import shelve # In this step, we create a shelf file.shfile = shelve.open("shelf_file") # we create a data object which in this case is a book_list.my_book_list =['bared_to_you', 'The_fault_in_our_stars', 'The_boy_who_never_let_her_go'] # we are assigning a dictionary key to the list # which we will want to retrieveshfile['book_list']= my_book_list # now, we simply close the shelf file.shfile.close() Retrieving Python shelve data :After storing a shelve data, we have to retrieve some data from a file in order to do that we use index operator [] as we do in lists and in many other data types. # At first, we import the 'Shelve' module.import shelve # In this step, we create a shelf file.var = shelve.open("shelf_file") # Now, this 'var' variable points to all the # data objects in the file 'shelf_file'.print(var['book_list']) # now, we simply close the file 'shelf_file'.var.close() Output : ['bared_to_you', 'The_fault_in_our_stars', 'The_boy_who_never_let_her_go'] Note : Output will be depend on what you have store in a file Updating Python shelve data :In order to update a python shelve data, we use append() function or we can easily update as we do in lists and in other data types. In order to make our changes permanent we use sync() function. # At first, we have to import the 'Shelve' module.import shelve # In this step, we create a shelf file.var = shelve.open("shelf_file", writeback = True) # inputting total values we want to add # to the already existing list in shelf_file.val1 = int(input("Enter the number of values ")) for x in range(val1): val = input("\n Enter the value\t") var['book_list'].append(val) # Now, this 'var' variable will help in printing# the data objects in the file 'shelf_file'.print(var['book_list']) # to make our changes permanent, we use # synchronize function.var.sync() # now, we simply close the file 'shelf_file'.var.close() Input : Enter the number of values 5 Enter the value Who moved my cheese? Enter the value Our impossible love Enter the value Bourne Identity Enter the value Hush Enter the value Knock-Knock Output : ['bared_to_you', 'The_fault_in_our_stars', 'The_boy_who_never_let_her_go', 'Who moved my cheese?', 'Our impossible love', 'Bourne Identity', 'Hush', 'Knock-Knock'] Note : Input and Output depend upon user, user can update anything in a file which user want according to user input, output will be changed. Python-Library python-object 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() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n06 Jan, 2019" }, { "code": null, "e": 24145, "s": 23901, "text": "In Python shelve you access the keys randomly. In order to access the keys randomly in python shelve we use open() function. This function works a lot like the file open() function in File handling. Syntax for open the file using Python shelve" }, { "code": null, "e": 24195, "s": 24145, "text": "shelve.open(filename, flag='c' , writeback=True)\n" }, { "code": null, "e": 24282, "s": 24195, "text": "In Order to access the keys randomly in shelve in Python, we have to take three steps:" }, { "code": null, "e": 24309, "s": 24282, "text": "Storing Python shelve data" }, { "code": null, "e": 24339, "s": 24309, "text": "Retrieving Python shelve data" }, { "code": null, "e": 24367, "s": 24339, "text": "Updating Python shelve data" }, { "code": null, "e": 24566, "s": 24367, "text": "Storing Python shelve data :In order to store python shelve data, we have to create a file with full of datasets and open them with a open() function this function open a file which we have created." }, { "code": "# At first, we have to import the 'Shelve' module.import shelve # In this step, we create a shelf file.shfile = shelve.open(\"shelf_file\") # we create a data object which in this case is a book_list.my_book_list =['bared_to_you', 'The_fault_in_our_stars', 'The_boy_who_never_let_her_go'] # we are assigning a dictionary key to the list # which we will want to retrieveshfile['book_list']= my_book_list # now, we simply close the shelf file.shfile.close()", "e": 25037, "s": 24566, "text": null }, { "code": null, "e": 25233, "s": 25037, "text": " Retrieving Python shelve data :After storing a shelve data, we have to retrieve some data from a file in order to do that we use index operator [] as we do in lists and in many other data types." }, { "code": "# At first, we import the 'Shelve' module.import shelve # In this step, we create a shelf file.var = shelve.open(\"shelf_file\") # Now, this 'var' variable points to all the # data objects in the file 'shelf_file'.print(var['book_list']) # now, we simply close the file 'shelf_file'.var.close()", "e": 25529, "s": 25233, "text": null }, { "code": null, "e": 25538, "s": 25529, "text": "Output :" }, { "code": null, "e": 25614, "s": 25538, "text": "['bared_to_you', 'The_fault_in_our_stars', 'The_boy_who_never_let_her_go']\n" }, { "code": null, "e": 25901, "s": 25614, "text": "Note : Output will be depend on what you have store in a file Updating Python shelve data :In order to update a python shelve data, we use append() function or we can easily update as we do in lists and in other data types. In order to make our changes permanent we use sync() function." }, { "code": "# At first, we have to import the 'Shelve' module.import shelve # In this step, we create a shelf file.var = shelve.open(\"shelf_file\", writeback = True) # inputting total values we want to add # to the already existing list in shelf_file.val1 = int(input(\"Enter the number of values \")) for x in range(val1): val = input(\"\\n Enter the value\\t\") var['book_list'].append(val) # Now, this 'var' variable will help in printing# the data objects in the file 'shelf_file'.print(var['book_list']) # to make our changes permanent, we use # synchronize function.var.sync() # now, we simply close the file 'shelf_file'.var.close()", "e": 26543, "s": 25901, "text": null }, { "code": null, "e": 26551, "s": 26543, "text": "Input :" }, { "code": null, "e": 26755, "s": 26551, "text": " Enter the number of values 5\n Enter the value Who moved my cheese?\n Enter the value Our impossible love\n Enter the value Bourne Identity\n Enter the value Hush\n Enter the value Knock-Knock" }, { "code": null, "e": 26764, "s": 26755, "text": "Output :" }, { "code": null, "e": 26931, "s": 26764, "text": "['bared_to_you', 'The_fault_in_our_stars', 'The_boy_who_never_let_her_go',\n 'Who moved my cheese?', 'Our impossible love', 'Bourne Identity', \n 'Hush', 'Knock-Knock']" }, { "code": null, "e": 27073, "s": 26931, "text": "Note : Input and Output depend upon user, user can update anything in a file which user want according to user input, output will be changed." }, { "code": null, "e": 27088, "s": 27073, "text": "Python-Library" }, { "code": null, "e": 27102, "s": 27088, "text": "python-object" }, { "code": null, "e": 27109, "s": 27102, "text": "Python" }, { "code": null, "e": 27207, "s": 27109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27216, "s": 27207, "text": "Comments" }, { "code": null, "e": 27229, "s": 27216, "text": "Old Comments" }, { "code": null, "e": 27261, "s": 27229, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27317, "s": 27261, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27359, "s": 27317, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27401, "s": 27359, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27437, "s": 27401, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27476, "s": 27437, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27498, "s": 27476, "text": "Defaultdict in Python" }, { "code": null, "e": 27529, "s": 27498, "text": "Python | os.path.join() method" }, { "code": null, "e": 27556, "s": 27529, "text": "Python Classes and Objects" } ]
Java program to find a cube of a given number
Cube of a value is simply three times multiplication of the value with self. For example, cube of 2 is (2*2*2) = 8. Take integer variable A. Multiply A three times. Display result as Cube. import java.util.Scanner; public class FindingCube { public static void main(String args[]){ int n = 5; System.out.println("Enter a number ::"); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); System.out.println("Cube of the given number is "+(num*num*num)); } } Enter a number :: 5 Cube of the given number is 125
[ { "code": null, "e": 1139, "s": 1062, "text": "Cube of a value is simply three times multiplication of the value with self." }, { "code": null, "e": 1178, "s": 1139, "text": "For example, cube of 2 is (2*2*2) = 8." }, { "code": null, "e": 1203, "s": 1178, "text": "Take integer variable A." }, { "code": null, "e": 1227, "s": 1203, "text": "Multiply A three times." }, { "code": null, "e": 1251, "s": 1227, "text": "Display result as Cube." }, { "code": null, "e": 1564, "s": 1251, "text": "import java.util.Scanner;\n\npublic class FindingCube {\n public static void main(String args[]){\n int n = 5;\n System.out.println(\"Enter a number ::\");\n Scanner sc = new Scanner(System.in);\n int num = sc.nextInt();\n System.out.println(\"Cube of the given number is \"+(num*num*num));\n }\n}" }, { "code": null, "e": 1616, "s": 1564, "text": "Enter a number ::\n5\nCube of the given number is 125" } ]
What is the difference between “screen” and “only screen” in media queries? - GeeksforGeeks
07 Mar, 2019 Media query is used to create responsive web design. It means that the view of web page differ from system to system based on screen or media types.screen: It is used to set the screen size of media query. The screen size can be set by using max-width and min-width. The screen size is differ from screen to screen. Syntax: @media screen and (max-width: width) Example: This example use media query which works when the maximum width of display area is 400px. It is specifying screen as opposed to the other available media types the most common other one being print. <!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- CSS property to set style --> <style> body { background-color: lightgreen; } /* Media query */ @media screen and (max-width: 400px) { body { background-color: green; color:white; } } </style></head> <body> <h1>The @media Rule</h1> <p> Resize the browser window. When the width of this document is 400 pixels or less, the background-color is "green", otherwise it is "lightblue". </p></body> </html> Output:Screen size greater then 400px:Screen size less then 400px: only screen: The only keyword is used to prevent older browsers that do not support media queries with media features from applying the specified styles. Syntax: @media only screen and (max-width: width) Example 2 <!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- CSS property to set style --> <style> body { background-color: lightgreen; } /* Media query */ @media only screen and (max-width: 400px) { body { background-color: green; } } </style></head> <body> <h1>The @media Rule</h1> <p> Resize the browser window. When the width of this document is 400 pixels or less, the background-color is "green", otherwise it is "lightblue". </p></body> </html> Output:Screen size greater then 400px:Screen size less then 400px: Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Responsive Navbar using ReactJS How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set div width to fit content using CSS ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24596, "s": 24568, "text": "\n07 Mar, 2019" }, { "code": null, "e": 24912, "s": 24596, "text": "Media query is used to create responsive web design. It means that the view of web page differ from system to system based on screen or media types.screen: It is used to set the screen size of media query. The screen size can be set by using max-width and min-width. The screen size is differ from screen to screen." }, { "code": null, "e": 24920, "s": 24912, "text": "Syntax:" }, { "code": null, "e": 24957, "s": 24920, "text": "@media screen and (max-width: width)" }, { "code": null, "e": 25165, "s": 24957, "text": "Example: This example use media query which works when the maximum width of display area is 400px. It is specifying screen as opposed to the other available media types the most common other one being print." }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- CSS property to set style --> <style> body { background-color: lightgreen; } /* Media query */ @media screen and (max-width: 400px) { body { background-color: green; color:white; } } </style></head> <body> <h1>The @media Rule</h1> <p> Resize the browser window. When the width of this document is 400 pixels or less, the background-color is \"green\", otherwise it is \"lightblue\". </p></body> </html> ", "e": 25878, "s": 25165, "text": null }, { "code": null, "e": 25945, "s": 25878, "text": "Output:Screen size greater then 400px:Screen size less then 400px:" }, { "code": null, "e": 26099, "s": 25945, "text": "only screen: The only keyword is used to prevent older browsers that do not support media queries with media features from applying the specified styles." }, { "code": null, "e": 26107, "s": 26099, "text": "Syntax:" }, { "code": null, "e": 26150, "s": 26107, "text": "@media only screen and (max-width: width) " }, { "code": null, "e": 26160, "s": 26150, "text": "Example 2" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- CSS property to set style --> <style> body { background-color: lightgreen; } /* Media query */ @media only screen and (max-width: 400px) { body { background-color: green; } } </style></head> <body> <h1>The @media Rule</h1> <p> Resize the browser window. When the width of this document is 400 pixels or less, the background-color is \"green\", otherwise it is \"lightblue\". </p></body> </html> ", "e": 26850, "s": 26160, "text": null }, { "code": null, "e": 26917, "s": 26850, "text": "Output:Screen size greater then 400px:Screen size less then 400px:" }, { "code": null, "e": 26924, "s": 26917, "text": "Picked" }, { "code": null, "e": 26928, "s": 26924, "text": "CSS" }, { "code": null, "e": 26945, "s": 26928, "text": "Web Technologies" }, { "code": null, "e": 27043, "s": 26945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27052, "s": 27043, "text": "Comments" }, { "code": null, "e": 27065, "s": 27052, "text": "Old Comments" }, { "code": null, "e": 27106, "s": 27065, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 27170, "s": 27106, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27207, "s": 27170, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27268, "s": 27207, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27316, "s": 27268, "text": "How to set div width to fit content using CSS ?" }, { "code": null, "e": 27358, "s": 27316, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27391, "s": 27358, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27434, "s": 27391, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27479, "s": 27434, "text": "Convert a string to an integer in JavaScript" } ]
What does DELIMITER // do in a Trigger in MySQL?
The DELIMITER // can be used to change the statement from semicolon (;) to //. Now you can write multiple statements with semi-colon in a trigger. Here is the demo of triggers. In this example whenever you enter the EmployeeSalary less than 1000 then it will by default set to 10000. Firstly, let us create a table. The query to create a table is as follows - mysql> create table EmployeeTable -> ( -> EmployeeId int, -> EmployeeName varchar(100), -> EmployeeSalary float -> ); Query OK, 0 rows affected (0.76 sec) After creating a table, you need to create a trigger on insert command. The query to create a trigger is as follows. mysql> delimiter // mysql> create trigger CheckSalary before insert on EmployeeTable -> for each row if new.EmployeeSalary < 1000 then set -> new.EmployeeSalary=10000; -> end if; -> // Query OK, 0 rows affected (0.40 sec) mysql> delimiter ; Now you can check the trigger using insert command. If you insert EmployeeSalary less than 1000, then it does not give any error but it will store a default value which I have given 10000. The query to insert record is as follows - mysql> insert into EmployeeTable values(1,'Carol',500); Query OK, 1 row affected (0.25 sec) Now check all the records from the table using select statement. The query is as follows. mysql> select *from EmployeeTable; The following is the output. +------------+--------------+----------------+ | EmployeeId | EmployeeName | EmployeeSalary | +------------+--------------+----------------+ | 1 | Carol | 10000 | +------------+--------------+----------------+ 1 row in set (0.00 sec) If you insert 1000 or greater than 1000 then it will show your number only. I have deleted the previous record from the table using truncate command. mysql> truncate table EmployeeTable; Query OK, 0 rows affected (1.44 sec) The query to insert records in the table. mysql> insert into EmployeeTable values(2,'Bob',1000); Query OK, 1 row affected (0.14 sec) mysql> insert into EmployeeTable values(3,'Carol',2500); Query OK, 1 row affected (0.19 sec) Here is the query to check all records from the table using select statement. mysql> select *from EmployeeTable; The following is the output. +------------+--------------+----------------+ | EmployeeId | EmployeeName | EmployeeSalary | +------------+--------------+----------------+ | 2 | Bob | 1000 | | 3 | Carol | 2500 | +------------+--------------+----------------+ 2 rows in set (0.00 sec) Look at the above sample output, EmployeeSalary is greater than or equal to 1000. This will give your salary. Remember, if it is less than 1000 then the default value is set to 10000.
[ { "code": null, "e": 1209, "s": 1062, "text": "The DELIMITER // can be used to change the statement from semicolon (;) to //. Now you can write multiple statements with semi-colon in a trigger." }, { "code": null, "e": 1346, "s": 1209, "text": "Here is the demo of triggers. In this example whenever you enter the EmployeeSalary less than 1000 then it will by default set to 10000." }, { "code": null, "e": 1422, "s": 1346, "text": "Firstly, let us create a table. The query to create a table is as follows -" }, { "code": null, "e": 1577, "s": 1422, "text": "mysql> create table EmployeeTable\n-> (\n-> EmployeeId int,\n-> EmployeeName varchar(100),\n-> EmployeeSalary float\n-> );\nQuery OK, 0 rows affected (0.76 sec)" }, { "code": null, "e": 1694, "s": 1577, "text": "After creating a table, you need to create a trigger on insert command. The query to create a trigger is as follows." }, { "code": null, "e": 1935, "s": 1694, "text": "mysql> delimiter //\nmysql> create trigger CheckSalary before insert on EmployeeTable\n-> for each row if new.EmployeeSalary < 1000 then set\n-> new.EmployeeSalary=10000;\n-> end if;\n-> //\nQuery OK, 0 rows affected (0.40 sec)\nmysql> delimiter ;" }, { "code": null, "e": 2124, "s": 1935, "text": "Now you can check the trigger using insert command. If you insert EmployeeSalary less than 1000, then it does not give any error but it will store a default value which I have given 10000." }, { "code": null, "e": 2167, "s": 2124, "text": "The query to insert record is as follows -" }, { "code": null, "e": 2259, "s": 2167, "text": "mysql> insert into EmployeeTable values(1,'Carol',500);\nQuery OK, 1 row affected (0.25 sec)" }, { "code": null, "e": 2349, "s": 2259, "text": "Now check all the records from the table using select statement. The query is as follows." }, { "code": null, "e": 2384, "s": 2349, "text": "mysql> select *from EmployeeTable;" }, { "code": null, "e": 2413, "s": 2384, "text": "The following is the output." }, { "code": null, "e": 2672, "s": 2413, "text": "+------------+--------------+----------------+\n| EmployeeId | EmployeeName | EmployeeSalary |\n+------------+--------------+----------------+\n| 1 | Carol | 10000 |\n+------------+--------------+----------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2822, "s": 2672, "text": "If you insert 1000 or greater than 1000 then it will show your number only. I have deleted the previous record from the table using truncate command." }, { "code": null, "e": 2896, "s": 2822, "text": "mysql> truncate table EmployeeTable;\nQuery OK, 0 rows affected (1.44 sec)" }, { "code": null, "e": 2938, "s": 2896, "text": "The query to insert records in the table." }, { "code": null, "e": 3123, "s": 2938, "text": "mysql> insert into EmployeeTable values(2,'Bob',1000);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into EmployeeTable values(3,'Carol',2500);\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 3201, "s": 3123, "text": "Here is the query to check all records from the table using select statement." }, { "code": null, "e": 3236, "s": 3201, "text": "mysql> select *from EmployeeTable;" }, { "code": null, "e": 3265, "s": 3236, "text": "The following is the output." }, { "code": null, "e": 3572, "s": 3265, "text": "+------------+--------------+----------------+\n| EmployeeId | EmployeeName | EmployeeSalary |\n+------------+--------------+----------------+\n| 2 | Bob | 1000 |\n| 3 | Carol | 2500 |\n+------------+--------------+----------------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 3756, "s": 3572, "text": "Look at the above sample output, EmployeeSalary is greater than or equal to 1000. This will give your salary. Remember, if it is less than 1000 then the default value is set to 10000." } ]
Can we have a return statement in a JavaScript switch statement?
The JavaScript switch statement can contain return statements if it is present inside a function. The function will return the value in the switch statement and the code after the switch statement will not be executed. Following is the code to have return statements in JavaScript switch statement − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Return statement in JavaScript switch</h1> Enter day 1-7<input type="text" class="day" /><button class="Btn"> CHECK </button> <div style="color: green;" class="result"></div> <h3> Click on the above button to check which day it is </h3> <script> let dayVal = document.querySelector(".day"); let resEle = document.querySelector(".result"); function returnDay(val) { switch (val) { case 1: return "It's monday"; case 2: return "It's tuesday"; case 3: return "It's wednesday"; case 4: return "It's thursday"; case 5: return "It's friday"; case 6: return "It's saturday"; case 7: return "It's sunday"; default: return "Enter a value between 1 - 7"; } } document.querySelector(".Btn").addEventListener("click", () => { resEle.innerHTML = returnDay(parseInt(dayVal.value)); }); </script> </body> </html> The above code will produce the following output − On entering a number between 1-7 and clicking on CHECK −
[ { "code": null, "e": 1281, "s": 1062, "text": "The JavaScript switch statement can contain return statements if it is present inside a function. The function will return the value in the switch statement and the code after the switch statement will not be executed." }, { "code": null, "e": 1362, "s": 1281, "text": "Following is the code to have return statements in JavaScript switch statement −" }, { "code": null, "e": 1373, "s": 1362, "text": " Live Demo" }, { "code": null, "e": 2721, "s": 1373, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Return statement in JavaScript switch</h1>\nEnter day 1-7<input type=\"text\" class=\"day\" /><button class=\"Btn\">\nCHECK\n</button>\n<div style=\"color: green;\" class=\"result\"></div>\n<h3>\nClick on the above button to check which day it is\n</h3>\n<script>\n let dayVal = document.querySelector(\".day\");\n let resEle = document.querySelector(\".result\");\n function returnDay(val) {\n switch (val) {\n case 1:\n return \"It's monday\";\n case 2:\n return \"It's tuesday\";\n case 3:\n return \"It's wednesday\";\n case 4:\n return \"It's thursday\";\n case 5:\n return \"It's friday\";\n case 6:\n return \"It's saturday\";\n case 7:\n return \"It's sunday\";\n default:\n return \"Enter a value between 1 - 7\";\n }\n }\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n resEle.innerHTML = returnDay(parseInt(dayVal.value));\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2772, "s": 2721, "text": "The above code will produce the following output −" }, { "code": null, "e": 2829, "s": 2772, "text": "On entering a number between 1-7 and clicking on CHECK −" } ]
Java Program to Find the K-th Largest Sum Contiguous Subarray - GeeksforGeeks
28 Feb, 2022 Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers. Examples: Input: a[] = {20, -5, -1} k = 3 Output: 14 Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so the 3rd largest sum is 14. Input: a[] = {10, -10, 20, -40} k = 6 Output: -10 Explanation: The 6th largest sum among sum of all contiguous subarrays is -10. A brute force approach is to store all the contiguous sums in another array and sort it and print the k-th largest. But in the case of the number of elements being large, the array in which we store the contiguous sums will run out of memory as the number of contiguous subarrays will be large (quadratic order) An efficient approach is to store the pre-sum of the array in a sum[] array. We can find sum of contiguous subarray from index i to j as sum[j]-sum[i-1] Now for storing the Kth largest sum, use a min heap (priority queue) in which we push the contiguous sums till we get K elements, once we have our K elements, check if the element is greater than the Kth element it is inserted to the min heap with popping out the top element in the min-heap, else not inserted. In the end, the top element in the min-heap will be your answer. Below is the implementation of the above approach. Java // Java program to find the k-th// largest sum of subarrayimport java.util.*; class KthLargestSumSubArray{ // function to calculate kth largest // element in contiguous subarray sum static int kthLargestSum(int arr[], int n, int k) { // array to store predix sums int sum[] = new int[n + 1]; sum[0] = 0; sum[1] = arr[0]; for (int i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap PriorityQueue<Integer> Q = new PriorityQueue<Integer> (); // loop to calculate the contiguous subarray // sum position-wise for (int i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (int j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index int x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.size() < k) Q.add(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use if (Q.peek() < x) { Q.poll(); Q.add(x); } } } } // the top element will be then kth // largest element return Q.poll(); } // Driver Code public static void main(String[] args) { int a[] = new int[]{ 10, -10, 20, -40 }; int n = a.length; int k = 6; // calls the function to find out the // k-th largest sum System.out.println(kthLargestSum(a, n, k)); }} /* This code is contributed by Danish Kaleem */ Output: -10 Time complexity: O(n^2 log (k)) Auxiliary Space : O(k) for min-heap and we can store the sum array in the array itself as it is of no use. Please refer complete article on K-th Largest Sum Contiguous Subarray for more details! nikhatkhan11 Order-Statistics subarray subarray-sum Arrays Heap Java Java Programs Arrays Java Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation HeapSort Binary Heap Huffman Coding | Greedy Algo-3 Building Heap from Array Sliding Window Maximum (Maximum of all subarrays of size k)
[ { "code": null, "e": 24431, "s": 24403, "text": "\n28 Feb, 2022" }, { "code": null, "e": 24596, "s": 24431, "text": "Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers." }, { "code": null, "e": 24607, "s": 24596, "text": "Examples: " }, { "code": null, "e": 24908, "s": 24607, "text": "Input: a[] = {20, -5, -1} \n k = 3\nOutput: 14\nExplanation: All sum of contiguous \nsubarrays are (20, 15, 14, -5, -6, -1) \nso the 3rd largest sum is 14.\n\nInput: a[] = {10, -10, 20, -40} \n k = 6\nOutput: -10 \nExplanation: The 6th largest sum among \nsum of all contiguous subarrays is -10." }, { "code": null, "e": 25220, "s": 24908, "text": "A brute force approach is to store all the contiguous sums in another array and sort it and print the k-th largest. But in the case of the number of elements being large, the array in which we store the contiguous sums will run out of memory as the number of contiguous subarrays will be large (quadratic order)" }, { "code": null, "e": 25374, "s": 25220, "text": "An efficient approach is to store the pre-sum of the array in a sum[] array. We can find sum of contiguous subarray from index i to j as sum[j]-sum[i-1] " }, { "code": null, "e": 25751, "s": 25374, "text": "Now for storing the Kth largest sum, use a min heap (priority queue) in which we push the contiguous sums till we get K elements, once we have our K elements, check if the element is greater than the Kth element it is inserted to the min heap with popping out the top element in the min-heap, else not inserted. In the end, the top element in the min-heap will be your answer." }, { "code": null, "e": 25804, "s": 25751, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 25809, "s": 25804, "text": "Java" }, { "code": "// Java program to find the k-th// largest sum of subarrayimport java.util.*; class KthLargestSumSubArray{ // function to calculate kth largest // element in contiguous subarray sum static int kthLargestSum(int arr[], int n, int k) { // array to store predix sums int sum[] = new int[n + 1]; sum[0] = 0; sum[1] = arr[0]; for (int i = 2; i <= n; i++) sum[i] = sum[i - 1] + arr[i - 1]; // priority_queue of min heap PriorityQueue<Integer> Q = new PriorityQueue<Integer> (); // loop to calculate the contiguous subarray // sum position-wise for (int i = 1; i <= n; i++) { // loop to traverse all positions that // form contiguous subarray for (int j = i; j <= n; j++) { // calculates the contiguous subarray // sum from j to i index int x = sum[j] - sum[i - 1]; // if queue has less then k elements, // then simply push it if (Q.size() < k) Q.add(x); else { // it the min heap has equal to // k elements then just check // if the largest kth element is // smaller than x then insert // else its of no use if (Q.peek() < x) { Q.poll(); Q.add(x); } } } } // the top element will be then kth // largest element return Q.poll(); } // Driver Code public static void main(String[] args) { int a[] = new int[]{ 10, -10, 20, -40 }; int n = a.length; int k = 6; // calls the function to find out the // k-th largest sum System.out.println(kthLargestSum(a, n, k)); }} /* This code is contributed by Danish Kaleem */", "e": 27852, "s": 25809, "text": null }, { "code": null, "e": 27860, "s": 27852, "text": "Output:" }, { "code": null, "e": 27864, "s": 27860, "text": "-10" }, { "code": null, "e": 28092, "s": 27864, "text": "Time complexity: O(n^2 log (k)) Auxiliary Space : O(k) for min-heap and we can store the sum array in the array itself as it is of no use. Please refer complete article on K-th Largest Sum Contiguous Subarray for more details! " }, { "code": null, "e": 28105, "s": 28092, "text": "nikhatkhan11" }, { "code": null, "e": 28122, "s": 28105, "text": "Order-Statistics" }, { "code": null, "e": 28131, "s": 28122, "text": "subarray" }, { "code": null, "e": 28144, "s": 28131, "text": "subarray-sum" }, { "code": null, "e": 28151, "s": 28144, "text": "Arrays" }, { "code": null, "e": 28156, "s": 28151, "text": "Heap" }, { "code": null, "e": 28161, "s": 28156, "text": "Java" }, { "code": null, "e": 28175, "s": 28161, "text": "Java Programs" }, { "code": null, "e": 28182, "s": 28175, "text": "Arrays" }, { "code": null, "e": 28187, "s": 28182, "text": "Java" }, { "code": null, "e": 28192, "s": 28187, "text": "Heap" }, { "code": null, "e": 28290, "s": 28192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28299, "s": 28290, "text": "Comments" }, { "code": null, "e": 28312, "s": 28299, "text": "Old Comments" }, { "code": null, "e": 28333, "s": 28312, "text": "Next Greater Element" }, { "code": null, "e": 28358, "s": 28333, "text": "Window Sliding Technique" }, { "code": null, "e": 28385, "s": 28358, "text": "Count pairs with given sum" }, { "code": null, "e": 28434, "s": 28385, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 28472, "s": 28434, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 28481, "s": 28472, "text": "HeapSort" }, { "code": null, "e": 28493, "s": 28481, "text": "Binary Heap" }, { "code": null, "e": 28524, "s": 28493, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 28549, "s": 28524, "text": "Building Heap from Array" } ]
How to bind all the number keys in Tkinter?
While developing a Tkinter application, we often encounter cases where we have to perform some specific operation or event with the keystrokes (on keyboard). Tkinter provides a mechanism to deal with such events. You can use bind(<Key>, callback) function for each widget that you want to bind in order to perform a certain type of event. Whenever we bind a key with an event, the callback event occurs whenever a corresponding key is pressed. Let's consider an example. Using the bind("", callback) function, we can also bind all the number keys to display a message on the screen such that whenever a user presses a key (1-9), a message will appear on the screen. # Import required libraries from tkinter import * # Create an instance of tkinter window win = Tk() win.geometry("700x300") # Function to display a message whenever a key is pressed def add_label(e): Label(win, text="You have pressed: " + e.char, font='Arial 16 bold').pack() # Create a label widget label=Label(win, text="Press any key in the range 0-9") label.pack(pady=20) label.config(font='Courier 18 bold') # Bind all the number keys with the callback function for i in range(10): win.bind(str(i), add_label) win.mainloop() Running the above code snippet will display a window with a Label widget. Whenever you press a key in the range (0-9), it will display a message on the screen.
[ { "code": null, "e": 1275, "s": 1062, "text": "While developing a Tkinter application, we often encounter cases where we have to perform some specific operation or event with the keystrokes (on keyboard). Tkinter provides a mechanism to deal with such events." }, { "code": null, "e": 1506, "s": 1275, "text": "You can use bind(<Key>, callback) function for each widget that you want to bind in order to perform a certain type of event. Whenever we bind a key with an event, the callback event occurs whenever a corresponding key is pressed." }, { "code": null, "e": 1728, "s": 1506, "text": "Let's consider an example. Using the bind(\"\", callback) function, we can also bind all the number keys to display a message on the screen such that whenever a user presses a key (1-9), a message will appear on the screen." }, { "code": null, "e": 2269, "s": 1728, "text": "# Import required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter window\nwin = Tk()\nwin.geometry(\"700x300\")\n\n# Function to display a message whenever a key is pressed\ndef add_label(e):\n Label(win, text=\"You have pressed: \" + e.char, font='Arial 16 bold').pack()\n\n# Create a label widget\nlabel=Label(win, text=\"Press any key in the range 0-9\")\nlabel.pack(pady=20)\nlabel.config(font='Courier 18 bold')\n\n# Bind all the number keys with the callback function\nfor i in range(10):\n win.bind(str(i), add_label)\n\nwin.mainloop()" }, { "code": null, "e": 2343, "s": 2269, "text": "Running the above code snippet will display a window with a Label widget." }, { "code": null, "e": 2429, "s": 2343, "text": "Whenever you press a key in the range (0-9), it will display a message on the screen." } ]
Fetch datetime row from exactly past 7 days records in MySQL
For this, you can use the INTERVAL 7 day concept. Let us first create a table − mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, AdmissionDate datetime ); Query OK, 0 rows affected (0.83 sec) Note − Let’s say the current date is 2019-08-23. Insert some records in the table using insert command − mysql> insert into DemoTable(AdmissionDate) values('2019-01-23'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(AdmissionDate) values('2019-08-15'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable(AdmissionDate) values('2019-08-16'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(AdmissionDate) values('2019-08-24'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----+---------------------+ | Id | AdmissionDate | +----+---------------------+ | 1 | 2019-01-23 00:00:00 | | 2 | 2019-08-15 00:00:00 | | 3 | 2019-08-16 00:00:00 | | 4 | 2019-08-24 00:00:00 | +----+---------------------+ 4 rows in set (0.00 sec) Here is the query to fetch DateTime row from exactly past 7 days records − mysql> select *from DemoTable where date(AdmissionDate)=CURDATE() - interval 7 day; This will produce the following output − +----+---------------------+ | Id | AdmissionDate | +----+---------------------+ | 3 | 2019-08-16 00:00:00 | +----+---------------------+ 1 row in set (0.04 sec)
[ { "code": null, "e": 1142, "s": 1062, "text": "For this, you can use the INTERVAL 7 day concept. Let us first create a table −" }, { "code": null, "e": 1287, "s": 1142, "text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n AdmissionDate datetime\n);\nQuery OK, 0 rows affected (0.83 sec)" }, { "code": null, "e": 1336, "s": 1287, "text": "Note − Let’s say the current date is 2019-08-23." }, { "code": null, "e": 1392, "s": 1336, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1800, "s": 1392, "text": "mysql> insert into DemoTable(AdmissionDate) values('2019-01-23');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable(AdmissionDate) values('2019-08-15');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable(AdmissionDate) values('2019-08-16');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable(AdmissionDate) values('2019-08-24');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1860, "s": 1800, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1891, "s": 1860, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1932, "s": 1891, "text": "This will produce the following output −" }, { "code": null, "e": 2189, "s": 1932, "text": "+----+---------------------+\n| Id | AdmissionDate |\n+----+---------------------+\n| 1 | 2019-01-23 00:00:00 |\n| 2 | 2019-08-15 00:00:00 |\n| 3 | 2019-08-16 00:00:00 |\n| 4 | 2019-08-24 00:00:00 |\n+----+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2264, "s": 2189, "text": "Here is the query to fetch DateTime row from exactly past 7 days records −" }, { "code": null, "e": 2348, "s": 2264, "text": "mysql> select *from DemoTable where date(AdmissionDate)=CURDATE() - interval 7 day;" }, { "code": null, "e": 2389, "s": 2348, "text": "This will produce the following output −" }, { "code": null, "e": 2558, "s": 2389, "text": "+----+---------------------+\n| Id | AdmissionDate |\n+----+---------------------+\n| 3 | 2019-08-16 00:00:00 |\n+----+---------------------+\n1 row in set (0.04 sec)" } ]
Update multiple rows in a single MongoDB query?
Use the concept of initializeUnorderedBulkOp(). Let us first create a collection with documents − >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"John","CustomerPurchaseAmount":500}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb06d78f205348bc626") } >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Chris","CustomerPurchaseAmount":700}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb26d78f205348bc627") } >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"David","CustomerPurchaseAmount":50}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb36d78f205348bc628") } >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Larry","CustomerPurchaseAmount":1900}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb46d78f205348bc629") } Following is the query to display all documents from a collection with the help of find() method − > db.upDateMultipleRowsDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cd6ceb06d78f205348bc626"), "CustomerName" : "John", "CustomerPurchaseAmount" : 500 } { "_id" : ObjectId("5cd6ceb26d78f205348bc627"), "CustomerName" : "Chris", "CustomerPurchaseAmount" : 700 } { "_id" : ObjectId("5cd6ceb36d78f205348bc628"), "CustomerName" : "David", "CustomerPurchaseAmount" : 50 } { "_id" : ObjectId("5cd6ceb46d78f205348bc629"), "CustomerName" : "Larry", "CustomerPurchaseAmount" : 1900 } Following is the query to update multiple rows in a single query − > var manyUpdateValue = db.upDateMultipleRowsDemo.initializeUnorderedBulkOp(); > manyUpdateValue.find({ _id: ObjectId("5cd6ceb06d78f205348bc626")}).updateOne({$set:{"CustomerName":"Bob" }}); > manyUpdateValue.find({ _id: ObjectId("5cd6ceb36d78f205348bc628")}).updateOne({$set:{"CustomerPurchaseAmount":56544444}}); > manyUpdateValue.execute(); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 0, "nUpserted" : 0, "nMatched" : 2, "nModified" : 2, "nRemoved" : 0, "upserted" : [ ] }) Let us check all the documents once again − > db.upDateMultipleRowsDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cd6ceb06d78f205348bc626"), "CustomerName" : "Bob", "CustomerPurchaseAmount" : 500 } { "_id" : ObjectId("5cd6ceb26d78f205348bc627"), "CustomerName" : "Chris", "CustomerPurchaseAmount" : 700 } { "_id" : ObjectId("5cd6ceb36d78f205348bc628"), "CustomerName" : "David", "CustomerPurchaseAmount" : 56544444 } { "_id" : ObjectId("5cd6ceb46d78f205348bc629"), "CustomerName" : "Larry", "CustomerPurchaseAmount" : 1900 }
[ { "code": null, "e": 1160, "s": 1062, "text": "Use the concept of initializeUnorderedBulkOp(). Let us first create a collection with documents −" }, { "code": null, "e": 1871, "s": 1160, "text": ">db.upDateMultipleRowsDemo.insertOne({\"CustomerName\":\"John\",\"CustomerPurchaseAmount\":500});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd6ceb06d78f205348bc626\")\n}\n>db.upDateMultipleRowsDemo.insertOne({\"CustomerName\":\"Chris\",\"CustomerPurchaseAmount\":700});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd6ceb26d78f205348bc627\")\n}\n>db.upDateMultipleRowsDemo.insertOne({\"CustomerName\":\"David\",\"CustomerPurchaseAmount\":50});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd6ceb36d78f205348bc628\")\n}\n>db.upDateMultipleRowsDemo.insertOne({\"CustomerName\":\"Larry\",\"CustomerPurchaseAmount\":1900});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd6ceb46d78f205348bc629\")\n}" }, { "code": null, "e": 1970, "s": 1871, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2015, "s": 1970, "text": "> db.upDateMultipleRowsDemo.find().pretty();" }, { "code": null, "e": 2056, "s": 2015, "text": "This will produce the following output −" }, { "code": null, "e": 2519, "s": 2056, "text": "{\n \"_id\" : ObjectId(\"5cd6ceb06d78f205348bc626\"),\n \"CustomerName\" : \"John\",\n \"CustomerPurchaseAmount\" : 500\n}\n{\n \"_id\" : ObjectId(\"5cd6ceb26d78f205348bc627\"),\n \"CustomerName\" : \"Chris\",\n \"CustomerPurchaseAmount\" : 700\n}\n{\n \"_id\" : ObjectId(\"5cd6ceb36d78f205348bc628\"),\n \"CustomerName\" : \"David\",\n \"CustomerPurchaseAmount\" : 50\n}\n{\n \"_id\" : ObjectId(\"5cd6ceb46d78f205348bc629\"),\n \"CustomerName\" : \"Larry\",\n \"CustomerPurchaseAmount\" : 1900\n}" }, { "code": null, "e": 2586, "s": 2519, "text": "Following is the query to update multiple rows in a single query −" }, { "code": null, "e": 3127, "s": 2586, "text": "> var manyUpdateValue = db.upDateMultipleRowsDemo.initializeUnorderedBulkOp();\n\n> manyUpdateValue.find({ _id: ObjectId(\"5cd6ceb06d78f205348bc626\")}).updateOne({$set:{\"CustomerName\":\"Bob\" }});\n\n> manyUpdateValue.find({ _id: ObjectId(\"5cd6ceb36d78f205348bc628\")}).updateOne({$set:{\"CustomerPurchaseAmount\":56544444}});\n\n> manyUpdateValue.execute();\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 0,\n \"nUpserted\" : 0,\n \"nMatched\" : 2,\n \"nModified\" : 2,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})" }, { "code": null, "e": 3171, "s": 3127, "text": "Let us check all the documents once again −" }, { "code": null, "e": 3216, "s": 3171, "text": "> db.upDateMultipleRowsDemo.find().pretty();" }, { "code": null, "e": 3257, "s": 3216, "text": "This will produce the following output −" }, { "code": null, "e": 3725, "s": 3257, "text": "{\n \"_id\" : ObjectId(\"5cd6ceb06d78f205348bc626\"),\n \"CustomerName\" : \"Bob\",\n \"CustomerPurchaseAmount\" : 500\n}\n{\n \"_id\" : ObjectId(\"5cd6ceb26d78f205348bc627\"),\n \"CustomerName\" : \"Chris\",\n \"CustomerPurchaseAmount\" : 700\n}\n{\n \"_id\" : ObjectId(\"5cd6ceb36d78f205348bc628\"),\n \"CustomerName\" : \"David\",\n \"CustomerPurchaseAmount\" : 56544444\n}\n{\n \"_id\" : ObjectId(\"5cd6ceb46d78f205348bc629\"),\n \"CustomerName\" : \"Larry\",\n \"CustomerPurchaseAmount\" : 1900\n}" } ]
WebRTC - Sending Messages
Now let's create a simple example. Firstly, run the signaling server we created in the “signaling server” tutorial via “node server”. There will be three text inputs on the page, one for a login, one for a username, and one for the message we want to send to the other peer. Create an index.html file and add the following code − <html lang = "en"> <head> <meta charset = "utf-8" /> </head> <body> <div> <input type = "text" id = "loginInput" /> <button id = "loginBtn">Login</button> </div> <div> <input type = "text" id = "otherUsernameInput" /> <button id = "connectToOtherUsernameBtn">Establish connection</button> </div> <div> <input type = "text" id = "msgInput" /> <button id = "sendMsgBtn">Send text message</button> </div> <script src = "client.js"></script> </body> </html> We've also added three buttons for login, establishing a connection and sending a message. Now create a client.js file and add the following code − var connection = new WebSocket('ws://localhost:9090'); var name = ""; var loginInput = document.querySelector('#loginInput'); var loginBtn = document.querySelector('#loginBtn'); var otherUsernameInput = document.querySelector('#otherUsernameInput'); var connectToOtherUsernameBtn = document.querySelector('#connectToOtherUsernameBtn'); var msgInput = document.querySelector('#msgInput'); var sendMsgBtn = document.querySelector('#sendMsgBtn'); var connectedUser, myConnection, dataChannel; //when a user clicks the login button loginBtn.addEventListener("click", function(event) { name = loginInput.value; if(name.length > 0) { send({ type: "login", name: name }); } }); //handle messages from the server connection.onmessage = function (message) { console.log("Got message", message.data); var data = JSON.parse(message.data); switch(data.type) { case "login": onLogin(data.success); break; case "offer": onOffer(data.offer, data.name); break; case "answer": onAnswer(data.answer); break; case "candidate": onCandidate(data.candidate); break; default: break; } }; //when a user logs in function onLogin(success) { if (success === false) { alert("oops...try a different username"); } else { //creating our RTCPeerConnection object var configuration = { "iceServers": [{ "url": "stun:stun.1.google.com:19302" }] }; myConnection = new webkitRTCPeerConnection(configuration, { optional: [{RtpDataChannels: true}] }); console.log("RTCPeerConnection object was created"); console.log(myConnection); //setup ice handling //when the browser finds an ice candidate we send it to another peer myConnection.onicecandidate = function (event) { if (event.candidate) { send({ type: "candidate", candidate: event.candidate }); } }; openDataChannel(); } }; connection.onopen = function () { console.log("Connected"); }; connection.onerror = function (err) { console.log("Got error", err); }; // Alias for sending messages in JSON format function send(message) { if (connectedUser) { message.name = connectedUser; } connection.send(JSON.stringify(message)); }; You can see that we establish a socket connection to our signaling server. When a user clicks on the login button the application sends his username to the server. If login is successful the application creates the RTCPeerConnection object and setup onicecandidate handler which sends all found icecandidates to the other peer. It also runs the openDataChannel() function which creates a dataChannel. Notice that when creating the RTCPeerConnection object the second argument in the constructor optional: [{RtpDataChannels: true}] is mandatory if you are using Chrome or Opera. The next step is to create an offer to the other peer. Add the following code to your client.js file− //setup a peer connection with another user connectToOtherUsernameBtn.addEventListener("click", function () { var otherUsername = otherUsernameInput.value; connectedUser = otherUsername; if (otherUsername.length > 0) { //make an offer myConnection.createOffer(function (offer) { console.log(); send({ type: "offer", offer: offer }); myConnection.setLocalDescription(offer); }, function (error) { alert("An error has occurred."); }); } }); //when somebody wants to call us function onOffer(offer, name) { connectedUser = name; myConnection.setRemoteDescription(new RTCSessionDescription(offer)); myConnection.createAnswer(function (answer) { myConnection.setLocalDescription(answer); send({ type: "answer", answer: answer }); }, function (error) { alert("oops...error"); }); } //when another user answers to our offer function onAnswer(answer) { myConnection.setRemoteDescription(new RTCSessionDescription(answer)); } //when we got ice candidate from another user function onCandidate(candidate) { myConnection.addIceCandidate(new RTCIceCandidate(candidate)); } You can see that when a user clicks the “Establish connection” button the application makes an SDP offer to the other peer. We also set onAnswer and onCandidate handlers. Finally, let's implement the openDataChannel() function which creates our dataChannel. Add the following code to your client.js file − //creating data channel function openDataChannel() { var dataChannelOptions = { reliable:true }; dataChannel = myConnection.createDataChannel("myDataChannel", dataChannelOptions); dataChannel.onerror = function (error) { console.log("Error:", error); }; dataChannel.onmessage = function (event) { console.log("Got message:", event.data); }; } //when a user clicks the send message button sendMsgBtn.addEventListener("click", function (event) { console.log("send message"); var val = msgInput.value; dataChannel.send(val); }); Here we create the dataChannel for our connection and add the event handler for the “send message” button. Now open this page in two tabs, login with two users, establish a connection, and try to send messages. You should see them in the console output. Notice that the above example is tested in Opera. Now you may see that RTCDataChannel is extremely powerful part of the WebRTC API. There are a lot of other use cases for this object, like peer-to-peer gaming or torrent-based file sharing. Print Add Notes Bookmark this page
[ { "code": null, "e": 2021, "s": 1887, "text": "Now let's create a simple example. Firstly, run the signaling server we created in the “signaling server” tutorial via “node server”." }, { "code": null, "e": 2217, "s": 2021, "text": "There will be three text inputs on the page, one for a login, one for a username, and one for the message we want to send to the other peer. Create an index.html file and add the following code −" }, { "code": null, "e": 2814, "s": 2217, "text": "<html lang = \"en\"> \n <head> \n <meta charset = \"utf-8\" /> \n </head>\n\t\n <body> \n <div> \n <input type = \"text\" id = \"loginInput\" /> \n <button id = \"loginBtn\">Login</button> \n </div> \n\t\t\n <div> \n <input type = \"text\" id = \"otherUsernameInput\" /> \n <button id = \"connectToOtherUsernameBtn\">Establish connection</button> \n </div> \n\t\t\n <div> \n <input type = \"text\" id = \"msgInput\" /> \n <button id = \"sendMsgBtn\">Send text message</button> \n </div> \n\t\t\n <script src = \"client.js\"></script>\n </body>\n\t\n</html>" }, { "code": null, "e": 2962, "s": 2814, "text": "We've also added three buttons for login, establishing a connection and sending a message. Now create a client.js file and add the following code −" }, { "code": null, "e": 5480, "s": 2962, "text": "var connection = new WebSocket('ws://localhost:9090'); \nvar name = \"\";\n\nvar loginInput = document.querySelector('#loginInput'); \nvar loginBtn = document.querySelector('#loginBtn'); \n\nvar otherUsernameInput = document.querySelector('#otherUsernameInput'); \nvar connectToOtherUsernameBtn = document.querySelector('#connectToOtherUsernameBtn'); \nvar msgInput = document.querySelector('#msgInput'); \nvar sendMsgBtn = document.querySelector('#sendMsgBtn'); \nvar connectedUser, myConnection, dataChannel;\n \n//when a user clicks the login button \nloginBtn.addEventListener(\"click\", function(event) { \n name = loginInput.value; \n\t\n if(name.length > 0) { \n send({ \n type: \"login\", \n name: name \n }); \n } \n}); \n \n//handle messages from the server \nconnection.onmessage = function (message) { \n console.log(\"Got message\", message.data); \n var data = JSON.parse(message.data); \n\t\n switch(data.type) { \n case \"login\": \n onLogin(data.success); \n break; \n case \"offer\": \n onOffer(data.offer, data.name); \n break; \n case \"answer\":\n onAnswer(data.answer); \n break; \n case \"candidate\": \n onCandidate(data.candidate); \n break; \n default: \n break; \n } \n}; \n \n//when a user logs in \nfunction onLogin(success) { \n\n if (success === false) { \n alert(\"oops...try a different username\"); \n } else { \n //creating our RTCPeerConnection object \n var configuration = { \n \"iceServers\": [{ \"url\": \"stun:stun.1.google.com:19302\" }] \n }; \n\t\t\n myConnection = new webkitRTCPeerConnection(configuration, { \n optional: [{RtpDataChannels: true}] \n }); \n\t\t\n console.log(\"RTCPeerConnection object was created\"); \n console.log(myConnection); \n \n //setup ice handling \n //when the browser finds an ice candidate we send it to another peer \n myConnection.onicecandidate = function (event) { \n\t\t\n if (event.candidate) { \n send({ \n type: \"candidate\", \n candidate: event.candidate \n });\n } \n }; \n\t\t\n openDataChannel();\n\t\t\n } \n};\n \nconnection.onopen = function () { \n console.log(\"Connected\"); \n}; \n \nconnection.onerror = function (err) { \n console.log(\"Got error\", err); \n};\n \n// Alias for sending messages in JSON format \nfunction send(message) { \n if (connectedUser) { \n message.name = connectedUser; \n }\n\t\n connection.send(JSON.stringify(message)); \n};" }, { "code": null, "e": 6160, "s": 5480, "text": "You can see that we establish a socket connection to our signaling server. When a user clicks on the login button the application sends his username to the server. If login is successful the application creates the RTCPeerConnection object and setup onicecandidate handler which sends all found icecandidates to the other peer. It also runs the openDataChannel() function which creates a dataChannel. Notice that when creating the RTCPeerConnection object the second argument in the constructor optional: [{RtpDataChannels: true}] is mandatory if you are using Chrome or Opera. The next step is to create an offer to the other peer. Add the following code to your client.js file−" }, { "code": null, "e": 7449, "s": 6160, "text": "//setup a peer connection with another user \nconnectToOtherUsernameBtn.addEventListener(\"click\", function () {\n \n var otherUsername = otherUsernameInput.value;\n connectedUser = otherUsername;\n\t\n if (otherUsername.length > 0) { \n //make an offer \n myConnection.createOffer(function (offer) { \n console.log(); \n\t\t\t\n send({ \n type: \"offer\", \n offer: offer \n }); \n\t\t\t\n myConnection.setLocalDescription(offer); \n }, function (error) { \n alert(\"An error has occurred.\"); \n }); \n } \n});\n \n//when somebody wants to call us \nfunction onOffer(offer, name) { \n connectedUser = name; \n myConnection.setRemoteDescription(new RTCSessionDescription(offer));\n\t\n myConnection.createAnswer(function (answer) { \n myConnection.setLocalDescription(answer); \n\t\t\n send({ \n type: \"answer\", \n answer: answer \n }); \n\t\t\n }, function (error) { \n alert(\"oops...error\"); \n }); \n}\n\n//when another user answers to our offer \nfunction onAnswer(answer) { \n myConnection.setRemoteDescription(new RTCSessionDescription(answer)); \n}\n \n//when we got ice candidate from another user \nfunction onCandidate(candidate) { \n myConnection.addIceCandidate(new RTCIceCandidate(candidate)); \n}" }, { "code": null, "e": 7755, "s": 7449, "text": "You can see that when a user clicks the “Establish connection” button the application makes an SDP offer to the other peer. We also set onAnswer and onCandidate handlers. Finally, let's implement the openDataChannel() function which creates our dataChannel. Add the following code to your client.js file −" }, { "code": null, "e": 8354, "s": 7755, "text": "//creating data channel \nfunction openDataChannel() { \n\n var dataChannelOptions = { \n reliable:true \n }; \n\t\n dataChannel = myConnection.createDataChannel(\"myDataChannel\", dataChannelOptions);\n\t\n dataChannel.onerror = function (error) { \n console.log(\"Error:\", error); \n };\n\t\n dataChannel.onmessage = function (event) { \n console.log(\"Got message:\", event.data); \n }; \n}\n \n//when a user clicks the send message button \nsendMsgBtn.addEventListener(\"click\", function (event) { \n console.log(\"send message\");\n var val = msgInput.value; \n dataChannel.send(val); \n});" }, { "code": null, "e": 8658, "s": 8354, "text": "Here we create the dataChannel for our connection and add the event handler for the “send message” button. Now open this page in two tabs, login with two users, establish a connection, and try to send messages. You should see them in the console output. Notice that the above example is tested in Opera." }, { "code": null, "e": 8848, "s": 8658, "text": "Now you may see that RTCDataChannel is extremely powerful part of the WebRTC API. There are a lot of other use cases for this object, like peer-to-peer gaming or torrent-based file sharing." }, { "code": null, "e": 8855, "s": 8848, "text": " Print" }, { "code": null, "e": 8866, "s": 8855, "text": " Add Notes" } ]
How to sum a variable by factor levels in R?
We can do this by using aggregate function or with the help tapply > x <- data.frame(Category=factor(c("Graduation", "Graduation", "Post-Graduation", "Graduation","PhD", "Post-Graduation", "PhD")), Frequency=c(12,19,15,20,25,13,14)) > x Category Frequency 1 Graduation 12 2 Graduation 19 3 Post-Graduation 15 4 Graduation 20 5 PhD 25 6 Post-Graduation 13 7 PhD 14 Using aggregate > aggregate(x$Frequency, by=list(Group=x$Category), FUN=sum) Group x 1 Graduation 51 2 PhD 39 3 Post-Graduation 28 Using tapply > tapply(x$Frequency, x$Category, FUN=sum) Graduation PhD Post-Graduation 51 39 28
[ { "code": null, "e": 1129, "s": 1062, "text": "We can do this by using aggregate function or with the help tapply" }, { "code": null, "e": 1426, "s": 1129, "text": "> x <- data.frame(Category=factor(c(\"Graduation\", \"Graduation\", \"Post-Graduation\",\n\"Graduation\",\"PhD\", \"Post-Graduation\", \"PhD\")),\nFrequency=c(12,19,15,20,25,13,14))\n> x\nCategory Frequency\n1 Graduation 12\n2 Graduation 19\n3 Post-Graduation 15\n4 Graduation 20\n5 PhD 25\n6 Post-Graduation 13\n7 PhD 14" }, { "code": null, "e": 1442, "s": 1426, "text": "Using aggregate" }, { "code": null, "e": 1670, "s": 1442, "text": "> aggregate(x$Frequency, by=list(Group=x$Category), FUN=sum)\n Group x\n1 Graduation 51\n2 PhD 39\n3 Post-Graduation 28\nUsing tapply\n> tapply(x$Frequency, x$Category, FUN=sum)\nGraduation PhD Post-Graduation\n51 39 28" } ]
uniform() method in Python Random module - GeeksforGeeks
15 Oct, 2020 uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there’s always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there’s an inbuilt method, “uniform()” which performs this task with ease and using just the one word. This method is defined in “random” module Syntax : uniform(int x, int y) Parameters :x Specifies the lower limit of the random number required to generate.y Specifies the upper limit of the random number required to generate. Returns : Returns the generated floating point random number between lower limit and upper limit Code #1 : Code to generate float random number. # Python3 code to demonstrate# the working of uniform() # for using uniform()import random # initializing bounds a = 4b = 9 # printing the random numberprint("The random number generated between 4 and 9 is : ", end ="")print(random.uniform(a, b)) Output: The random number generated between 4 and 9 is : 7.494931618830411 Application :There are many possible applications that can be thought of this function, some of the notable being generating random numbers in casino games, for lottery or custom games.Below is the game that decided the winner on the basis of closeness to a certain value. Code #2 : Application of uniform() – A Game # Python3 code to demonstrate# the application of uniform() # for using uniform()import random, math # initializing player numbersplayer1 = 4.50player2 = 3.78player3 = 6.54 # generating winner random numberwinner = random.uniform(2, 9) # finding closest diffa = math.fabs(winner - player1)diffb = math.fabs(winner - player2)diffc = math.fabs(winner - player3) # printing winnerif(diffa < diffb and diffa < diffc): print("The winner of game is : ", end ="") print("Player1") if(diffb < diffc and diffb < diffa): print("The winner of game is : ", end ="") print("Player2") if(diffc < diffb and diffc < diffa): print("The winner of game is : ", end ="") print("Player3") Output: The winner of game is : Player2 Python-Built-in-functions Python-Functions Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 25072, "s": 25044, "text": "\n15 Oct, 2020" }, { "code": null, "e": 25139, "s": 25072, "text": "uniform() is a method specified in the random library in Python 3." }, { "code": null, "e": 25499, "s": 25139, "text": "Nowadays, in general, day-day tasks, there’s always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there’s an inbuilt method, “uniform()” which performs this task with ease and using just the one word. This method is defined in “random” module" }, { "code": null, "e": 25530, "s": 25499, "text": "Syntax : uniform(int x, int y)" }, { "code": null, "e": 25683, "s": 25530, "text": "Parameters :x Specifies the lower limit of the random number required to generate.y Specifies the upper limit of the random number required to generate." }, { "code": null, "e": 25780, "s": 25683, "text": "Returns : Returns the generated floating point random number between lower limit and upper limit" }, { "code": null, "e": 25829, "s": 25780, "text": " Code #1 : Code to generate float random number." }, { "code": "# Python3 code to demonstrate# the working of uniform() # for using uniform()import random # initializing bounds a = 4b = 9 # printing the random numberprint(\"The random number generated between 4 and 9 is : \", end =\"\")print(random.uniform(a, b))", "e": 26079, "s": 25829, "text": null }, { "code": null, "e": 26087, "s": 26079, "text": "Output:" }, { "code": null, "e": 26155, "s": 26087, "text": "The random number generated between 4 and 9 is : 7.494931618830411\n" }, { "code": null, "e": 26428, "s": 26155, "text": "Application :There are many possible applications that can be thought of this function, some of the notable being generating random numbers in casino games, for lottery or custom games.Below is the game that decided the winner on the basis of closeness to a certain value." }, { "code": null, "e": 26473, "s": 26428, "text": " Code #2 : Application of uniform() – A Game" }, { "code": "# Python3 code to demonstrate# the application of uniform() # for using uniform()import random, math # initializing player numbersplayer1 = 4.50player2 = 3.78player3 = 6.54 # generating winner random numberwinner = random.uniform(2, 9) # finding closest diffa = math.fabs(winner - player1)diffb = math.fabs(winner - player2)diffc = math.fabs(winner - player3) # printing winnerif(diffa < diffb and diffa < diffc): print(\"The winner of game is : \", end =\"\") print(\"Player1\") if(diffb < diffc and diffb < diffa): print(\"The winner of game is : \", end =\"\") print(\"Player2\") if(diffc < diffb and diffc < diffa): print(\"The winner of game is : \", end =\"\") print(\"Player3\")", "e": 27170, "s": 26473, "text": null }, { "code": null, "e": 27178, "s": 27170, "text": "Output:" }, { "code": null, "e": 27211, "s": 27178, "text": "The winner of game is : Player2\n" }, { "code": null, "e": 27237, "s": 27211, "text": "Python-Built-in-functions" }, { "code": null, "e": 27254, "s": 27237, "text": "Python-Functions" }, { "code": null, "e": 27269, "s": 27254, "text": "Python-Library" }, { "code": null, "e": 27276, "s": 27269, "text": "Python" }, { "code": null, "e": 27374, "s": 27276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27402, "s": 27374, "text": "Read JSON file using Python" }, { "code": null, "e": 27452, "s": 27402, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27474, "s": 27452, "text": "Python map() function" }, { "code": null, "e": 27518, "s": 27474, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 27536, "s": 27518, "text": "Python Dictionary" }, { "code": null, "e": 27559, "s": 27536, "text": "Taking input in Python" }, { "code": null, "e": 27594, "s": 27559, "text": "Read a file line by line in Python" }, { "code": null, "e": 27626, "s": 27594, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27648, "s": 27626, "text": "Enumerate() in Python" } ]
How to Install Perl on Windows? - GeeksforGeeks
05 Oct, 2021 Prerequisite: Introduction to Perl Before, we start with the process of Downloading and Installing Perl on Windows operating system, we must have first-hand knowledge of What the Perl Language is and what it actually does?. Perl is a general-purpose, high level interpreted and dynamic programming language. Perl was originally developed for text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Perl programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Perl codes or can even install one on their system to make it more feasible to write these codes. Using an IDE makes it easier to write Perl codes because IDEs provides a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Perl Codes and performing various intriguing and useful operations, one must have Perl installed on their System. This can be done by following the step by step instructions provided below: Before we begin with the installation of Perl, it is good to check if it might be already installed on your system, because many software applications nowadays require Perl to perform their operations, hence a version of Perl might be included in the software’s installation package and hence there is no need to redownload and install the Perl when it already exists.To check if your device is preinstalled with Perl or not, just go to the Command line(For Windows, search for cmd in the Run dialog( + R).Now run the following command: perl -v If Perl is already installed, it will generate a message with all the details of the Perl’s version available, otherwise if Perl is not installed then an error will arise stating Bad command or file name Downloading Perl:Before starting with the installation process, you need to download it. For that, all versions of Perl for Windows are available on perl.orgDownload the Perl and follow the further instructions for installation of Perl. Beginning with the Installation: Getting Started: Getting done with the User’s License Agreement: Choosing what to Install: Installation Process: Finished Installation: After completing the installation process, any IDE or text editor can be used to write Perl Codes and Run them on the IDE or the Command prompt with the use of command: perl file_name.pl Here’s a sample Program to begin with the use of Perl Programming:Let’s consider a simple Hello World Program. #!/usr/bin/perl # Modules used use strict; use warnings; # Print function print("Hello World\n"); how-to-install perl-basics How To Installation Guide Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Install Jupyter Notebook on MacOS? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 26197, "s": 26169, "text": "\n05 Oct, 2021" }, { "code": null, "e": 26839, "s": 26197, "text": "Prerequisite: Introduction to Perl Before, we start with the process of Downloading and Installing Perl on Windows operating system, we must have first-hand knowledge of What the Perl Language is and what it actually does?. Perl is a general-purpose, high level interpreted and dynamic programming language. Perl was originally developed for text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++." }, { "code": null, "e": 27439, "s": 26839, "text": "Perl programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Perl codes or can even install one on their system to make it more feasible to write these codes. Using an IDE makes it easier to write Perl codes because IDEs provides a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Perl Codes and performing various intriguing and useful operations, one must have Perl installed on their System. This can be done by following the step by step instructions provided below:" }, { "code": null, "e": 27976, "s": 27439, "text": "Before we begin with the installation of Perl, it is good to check if it might be already installed on your system, because many software applications nowadays require Perl to perform their operations, hence a version of Perl might be included in the software’s installation package and hence there is no need to redownload and install the Perl when it already exists.To check if your device is preinstalled with Perl or not, just go to the Command line(For Windows, search for cmd in the Run dialog( + R).Now run the following command:" }, { "code": null, "e": 27984, "s": 27976, "text": "perl -v" }, { "code": null, "e": 28188, "s": 27984, "text": "If Perl is already installed, it will generate a message with all the details of the Perl’s version available, otherwise if Perl is not installed then an error will arise stating Bad command or file name" }, { "code": null, "e": 28425, "s": 28188, "text": "Downloading Perl:Before starting with the installation process, you need to download it. For that, all versions of Perl for Windows are available on perl.orgDownload the Perl and follow the further instructions for installation of Perl." }, { "code": null, "e": 28458, "s": 28425, "text": "Beginning with the Installation:" }, { "code": null, "e": 28475, "s": 28458, "text": "Getting Started:" }, { "code": null, "e": 28523, "s": 28475, "text": "Getting done with the User’s License Agreement:" }, { "code": null, "e": 28549, "s": 28523, "text": "Choosing what to Install:" }, { "code": null, "e": 28571, "s": 28549, "text": "Installation Process:" }, { "code": null, "e": 28594, "s": 28571, "text": "Finished Installation:" }, { "code": null, "e": 28763, "s": 28594, "text": "After completing the installation process, any IDE or text editor can be used to write Perl Codes and Run them on the IDE or the Command prompt with the use of command:" }, { "code": null, "e": 28781, "s": 28763, "text": "perl file_name.pl" }, { "code": null, "e": 28892, "s": 28781, "text": "Here’s a sample Program to begin with the use of Perl Programming:Let’s consider a simple Hello World Program." }, { "code": "#!/usr/bin/perl # Modules used use strict; use warnings; # Print function print(\"Hello World\\n\"); ", "e": 29000, "s": 28892, "text": null }, { "code": null, "e": 29015, "s": 29000, "text": "how-to-install" }, { "code": null, "e": 29027, "s": 29015, "text": "perl-basics" }, { "code": null, "e": 29034, "s": 29027, "text": "How To" }, { "code": null, "e": 29053, "s": 29034, "text": "Installation Guide" }, { "code": null, "e": 29058, "s": 29053, "text": "Perl" }, { "code": null, "e": 29063, "s": 29058, "text": "Perl" }, { "code": null, "e": 29161, "s": 29063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29195, "s": 29161, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29253, "s": 29195, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29302, "s": 29253, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 29349, "s": 29302, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 29391, "s": 29349, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 29424, "s": 29391, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29458, "s": 29424, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29493, "s": 29458, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 29551, "s": 29493, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
Dart - Sets - GeeksforGeeks
15 Sep, 2021 Sets in Dart is a special case in List where all the inputs are unique i.e it doesn’t contain any repeated input. It can also be interpreted as an unordered array with unique inputs. The set comes in play when we want to store unique values in a single variable without considering the order of the inputs. The sets are declared by the use of a set keyword. There are two ways to do so: var variable_name = <variable_type>{}; or, Set <variable_type> variable_name = {}; Example 1: Declaring set in two different ways. Dart // Dart program to show the Sets conceptvoid main(){ // Declaring set in First Way var gfg1 = <String>{'GeeksForGeeks'}; // Printing First Set print("Output of first set: $gfg1"); // Declaring set in Second Way Set<String> gfg2 = {'GeeksForGeeks'}; // Printing Second Set print("Output of second set: $gfg2");} Output: Output of first set: {GeeksForGeeks} Output of second set: {GeeksForGeeks} Example 2: Declaring repeated value in a set and a list and then comparing it. Dart // Dart Program to declare repeated value// in a set and a list and then// comparing it void main(){ // Declaring list with repeated value var gfg = ['Geeks','For','Geeks']; // Printing List print("Output of the list is: $gfg"); // Declaring set with repeated value var gfg1 = <String>{'Geeks','For','Geeks'}; // Printing Set print("Output of the set is: $gfg1");} Output: Output of the list is: [Geeks, For, Geeks] Output of the set is: {Geeks, For} Note: You can see that repeated value was simply ignored in the case of the set. Adding Element In Set: To add an element in the set we make use of “.add()” function or “.addAll()” function. But you must note that if you try to add a duplicate value using these functions than too they will get ignored in a set. // To add single value variable_name.add(value); // To add multiple value variable_name.addAll(value1, value2, value3, ...valueN)the Some other functions involving Sets are as follows: Example: Dart void main(){ // Declaring set with value var gfg = <String>{'Hello Geek'}; // Printing Set print("Value in the set is: $gfg"); // Adding an element in the set gfg.add("GeeksForGeeks"); // Printing Set print("Values in the set is: $gfg"); // Adding multiple values to the set var geeks_name = {"Geek1","Geek2","Geek3"}; gfg.addAll(geeks_name); // Printing Set print("Values in the set is: $gfg"); // Getting element at Index 0 var geek = gfg.elementAt(0); // Printing the element print("Element at index 0 is: $geek"); // Counting the length of the set int l = gfg.length; // Printing length print("Length of the set is: $l"); // Finding the element in the set bool check = gfg.contains("GeeksForGeeks"); // Printing boolean value print("The value of check is: $check"); // Removing an element from the set gfg.remove("Hello Geek"); // Printing Set print("Values in the set is: $gfg"); // Using forEach in set print(" "); print("Using forEach in set:"); gfg.forEach((element) { if(element == "Geek1") { print("Found"); } else { print("Not Found"); } }); // Deleting elements from set gfg.clear(); // Printing set print("Values in the set is: $gfg");} Output: Value in the set is: {Hello Geek} Values in the set is: {Hello Geek, GeeksForGeeks} Values in the set is: {Hello Geek, GeeksForGeeks, Geek1, Geek2, Geek3} Element at index 0 is: Hello Geek Length of the set is: 5 The value of check is: true Values in the set is: {GeeksForGeeks, Geek1, Geek2, Geek3} Using forEach in set: Not Found Found Not Found Not Found Values in the set is: {} Converting Set to List in Dart: Dart also provides us with the method to convert the set into the list. To do, so we make use of toList() method in Dart. List<type> list_variable_name = set_variable_name.toList(); Note: It is useful in the way as the list we will get will contain unique values and no repeated values. Example: Dart // Converting Set to List in Dartvoid main(){ // Declaring set with value var gfg = <String>{'Hello Geek',"GeeksForGeeks","Geek1","Geek2","Geek3"}; // Printing values in set print("Values in set are:"); print(gfg); print(""); // Converting Set to List List<String> gfg_list = gfg.toList(); // Printing values of list print("Values in the list are:"); print(gfg_list);} Output: Values in set are: {Hello Geek, GeeksForGeeks, Geek1, Geek2, Geek3} Values in the list are: [Hello Geek, GeeksForGeeks, Geek1, Geek2, Geek3] Converting Set to Map in Dart: Dart also provides us with the method to convert the set into the map. Example: Dart // Converting Set to Map in Dartvoid main(){ // Declaring set 1 with value var gfg = <String>{"GeeksForGeeks","Geek1","Geek2","Geek3"}; var geeksforgeeks = gfg.map((value) { return 'mapped $value'; }); print("Values in the map:"); print(geeksforgeeks); } Output: Values in the map: (mapped GeeksForGeeks, mapped Geek1, mapped Geek2, mapped Geek3) Set Operations in Dart: There are three operations on set in Dart: Example: Dart // Set Operations in Dart void main(){ // Declaring set 1 with value var gfg1 = <String>{"GeeksForGeeks","Geek1","Geek2","Geek3"}; // Printing values in set print("Values in set 1 are:"); print(gfg1); print(""); // Declaring set 2 with value var gfg2 = <String>{"GeeksForGeeks","Geek3","Geek4","Geek5"}; // Printing values in set print("Values in set 2 are:"); print(gfg2); print(""); // Finding Union print("Union of two sets is ${gfg1.union(gfg2)} \n"); // Finding Intersection print("Intersection of two sets is ${gfg1.intersection(gfg2)} \n"); // Finding Difference print("Difference of two sets is ${gfg2.difference(gfg1)} \n"); } Output: Values in set 1 are: {GeeksForGeeks, Geek1, Geek2, Geek3} Values in set 2 are: {GeeksForGeeks, Geek3, Geek4, Geek5} Union of two sets is {GeeksForGeeks, Geek1, Geek2, Geek3, Geek4, Geek5} Intersection of two sets is {GeeksForGeeks, Geek3} Difference of two sets is {Geek4, Geek5} In the above code, we can also compare more than two sets as: Example: Dart // Comparing more than 2 sets in Dart void main(){ // Declaring set 1 with value var gfg1 = <String>{"GeeksForGeeks","Geek1","Geek2","Geek3"}; // Declaring set 2 with value var gfg2 = <String>{"GeeksForGeeks","Geek3","Geek4","Geek5"}; // Declaring set 3 with value var gfg3 = <String>{"GeeksForGeeks","Geek5","Geek6","Geek7"}; // Finding Union print("Union of two sets is ${gfg1.union(gfg2).union(gfg3)}\n"); // Finding Intersection print("Intersection of two sets is ${gfg1.intersection(gfg2).intersection(gfg3)}\n"); // Finding Difference print("Difference of two sets is ${gfg2.difference(gfg1).difference(gfg3)}\n");} Output: Union of two sets is {GeeksForGeeks, Geek1, Geek2, Geek3, Geek4, Geek5, Geek6, Geek7} Intersection of two sets is {GeeksForGeeks} Difference of two sets is {Geek4} simmytarika5 Dart-Set Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Android Studio Setup for Flutter Development Flutter - Positioned Widget Format Dates in Flutter Flutter - Managing the MediaQuery Object What is widgets in Flutter?
[ { "code": null, "e": 25261, "s": 25233, "text": "\n15 Sep, 2021" }, { "code": null, "e": 25619, "s": 25261, "text": "Sets in Dart is a special case in List where all the inputs are unique i.e it doesn’t contain any repeated input. It can also be interpreted as an unordered array with unique inputs. The set comes in play when we want to store unique values in a single variable without considering the order of the inputs. The sets are declared by the use of a set keyword." }, { "code": null, "e": 25649, "s": 25619, "text": "There are two ways to do so: " }, { "code": null, "e": 25736, "s": 25649, "text": "var variable_name = <variable_type>{};\n \nor,\n \nSet <variable_type> variable_name = {};" }, { "code": null, "e": 25784, "s": 25736, "text": "Example 1: Declaring set in two different ways." }, { "code": null, "e": 25789, "s": 25784, "text": "Dart" }, { "code": "// Dart program to show the Sets conceptvoid main(){ // Declaring set in First Way var gfg1 = <String>{'GeeksForGeeks'}; // Printing First Set print(\"Output of first set: $gfg1\"); // Declaring set in Second Way Set<String> gfg2 = {'GeeksForGeeks'}; // Printing Second Set print(\"Output of second set: $gfg2\");}", "e": 26118, "s": 25789, "text": null }, { "code": null, "e": 26127, "s": 26118, "text": "Output: " }, { "code": null, "e": 26202, "s": 26127, "text": "Output of first set: {GeeksForGeeks}\nOutput of second set: {GeeksForGeeks}" }, { "code": null, "e": 26282, "s": 26202, "text": "Example 2: Declaring repeated value in a set and a list and then comparing it. " }, { "code": null, "e": 26287, "s": 26282, "text": "Dart" }, { "code": "// Dart Program to declare repeated value// in a set and a list and then// comparing it void main(){ // Declaring list with repeated value var gfg = ['Geeks','For','Geeks']; // Printing List print(\"Output of the list is: $gfg\"); // Declaring set with repeated value var gfg1 = <String>{'Geeks','For','Geeks'}; // Printing Set print(\"Output of the set is: $gfg1\");}", "e": 26670, "s": 26287, "text": null }, { "code": null, "e": 26679, "s": 26670, "text": "Output: " }, { "code": null, "e": 26757, "s": 26679, "text": "Output of the list is: [Geeks, For, Geeks]\nOutput of the set is: {Geeks, For}" }, { "code": null, "e": 26839, "s": 26757, "text": "Note: You can see that repeated value was simply ignored in the case of the set. " }, { "code": null, "e": 27071, "s": 26839, "text": "Adding Element In Set: To add an element in the set we make use of “.add()” function or “.addAll()” function. But you must note that if you try to add a duplicate value using these functions than too they will get ignored in a set." }, { "code": null, "e": 27207, "s": 27071, "text": " // To add single value\nvariable_name.add(value);\n\n// To add multiple value\nvariable_name.addAll(value1, value2, value3, ...valueN)the " }, { "code": null, "e": 27260, "s": 27207, "text": "Some other functions involving Sets are as follows: " }, { "code": null, "e": 27270, "s": 27260, "text": "Example: " }, { "code": null, "e": 27275, "s": 27270, "text": "Dart" }, { "code": "void main(){ // Declaring set with value var gfg = <String>{'Hello Geek'}; // Printing Set print(\"Value in the set is: $gfg\"); // Adding an element in the set gfg.add(\"GeeksForGeeks\"); // Printing Set print(\"Values in the set is: $gfg\"); // Adding multiple values to the set var geeks_name = {\"Geek1\",\"Geek2\",\"Geek3\"}; gfg.addAll(geeks_name); // Printing Set print(\"Values in the set is: $gfg\"); // Getting element at Index 0 var geek = gfg.elementAt(0); // Printing the element print(\"Element at index 0 is: $geek\"); // Counting the length of the set int l = gfg.length; // Printing length print(\"Length of the set is: $l\"); // Finding the element in the set bool check = gfg.contains(\"GeeksForGeeks\"); // Printing boolean value print(\"The value of check is: $check\"); // Removing an element from the set gfg.remove(\"Hello Geek\"); // Printing Set print(\"Values in the set is: $gfg\"); // Using forEach in set print(\" \"); print(\"Using forEach in set:\"); gfg.forEach((element) { if(element == \"Geek1\") { print(\"Found\"); } else { print(\"Not Found\"); } }); // Deleting elements from set gfg.clear(); // Printing set print(\"Values in the set is: $gfg\");}", "e": 28539, "s": 27275, "text": null }, { "code": null, "e": 28548, "s": 28539, "text": "Output: " }, { "code": null, "e": 28933, "s": 28548, "text": "Value in the set is: {Hello Geek}\nValues in the set is: {Hello Geek, GeeksForGeeks}\nValues in the set is: {Hello Geek, GeeksForGeeks, Geek1, Geek2, Geek3}\nElement at index 0 is: Hello Geek\nLength of the set is: 5\nThe value of check is: true\nValues in the set is: {GeeksForGeeks, Geek1, Geek2, Geek3}\n \nUsing forEach in set:\nNot Found\nFound\nNot Found\nNot Found\nValues in the set is: {}" }, { "code": null, "e": 29087, "s": 28933, "text": "Converting Set to List in Dart: Dart also provides us with the method to convert the set into the list. To do, so we make use of toList() method in Dart." }, { "code": null, "e": 29147, "s": 29087, "text": "List<type> list_variable_name = set_variable_name.toList();" }, { "code": null, "e": 29262, "s": 29147, "text": "Note: It is useful in the way as the list we will get will contain unique values and no repeated values. Example: " }, { "code": null, "e": 29267, "s": 29262, "text": "Dart" }, { "code": "// Converting Set to List in Dartvoid main(){ // Declaring set with value var gfg = <String>{'Hello Geek',\"GeeksForGeeks\",\"Geek1\",\"Geek2\",\"Geek3\"}; // Printing values in set print(\"Values in set are:\"); print(gfg); print(\"\"); // Converting Set to List List<String> gfg_list = gfg.toList(); // Printing values of list print(\"Values in the list are:\"); print(gfg_list);}", "e": 29660, "s": 29267, "text": null }, { "code": null, "e": 29669, "s": 29660, "text": "Output: " }, { "code": null, "e": 29811, "s": 29669, "text": "Values in set are:\n{Hello Geek, GeeksForGeeks, Geek1, Geek2, Geek3}\n\nValues in the list are:\n[Hello Geek, GeeksForGeeks, Geek1, Geek2, Geek3]" }, { "code": null, "e": 29915, "s": 29811, "text": "Converting Set to Map in Dart: Dart also provides us with the method to convert the set into the map. " }, { "code": null, "e": 29925, "s": 29915, "text": "Example: " }, { "code": null, "e": 29930, "s": 29925, "text": "Dart" }, { "code": "// Converting Set to Map in Dartvoid main(){ // Declaring set 1 with value var gfg = <String>{\"GeeksForGeeks\",\"Geek1\",\"Geek2\",\"Geek3\"}; var geeksforgeeks = gfg.map((value) { return 'mapped $value'; }); print(\"Values in the map:\"); print(geeksforgeeks); }", "e": 30201, "s": 29930, "text": null }, { "code": null, "e": 30211, "s": 30201, "text": "Output: " }, { "code": null, "e": 30295, "s": 30211, "text": "Values in the map:\n(mapped GeeksForGeeks, mapped Geek1, mapped Geek2, mapped Geek3)" }, { "code": null, "e": 30363, "s": 30295, "text": "Set Operations in Dart: There are three operations on set in Dart: " }, { "code": null, "e": 30374, "s": 30363, "text": "Example: " }, { "code": null, "e": 30379, "s": 30374, "text": "Dart" }, { "code": "// Set Operations in Dart void main(){ // Declaring set 1 with value var gfg1 = <String>{\"GeeksForGeeks\",\"Geek1\",\"Geek2\",\"Geek3\"}; // Printing values in set print(\"Values in set 1 are:\"); print(gfg1); print(\"\"); // Declaring set 2 with value var gfg2 = <String>{\"GeeksForGeeks\",\"Geek3\",\"Geek4\",\"Geek5\"}; // Printing values in set print(\"Values in set 2 are:\"); print(gfg2); print(\"\"); // Finding Union print(\"Union of two sets is ${gfg1.union(gfg2)} \\n\"); // Finding Intersection print(\"Intersection of two sets is ${gfg1.intersection(gfg2)} \\n\"); // Finding Difference print(\"Difference of two sets is ${gfg2.difference(gfg1)} \\n\"); }", "e": 31064, "s": 30379, "text": null }, { "code": null, "e": 31074, "s": 31064, "text": "Output: " }, { "code": null, "e": 31361, "s": 31074, "text": "Values in set 1 are:\n{GeeksForGeeks, Geek1, Geek2, Geek3}\n\nValues in set 2 are:\n{GeeksForGeeks, Geek3, Geek4, Geek5}\n\nUnion of two sets is {GeeksForGeeks, Geek1, Geek2, Geek3, Geek4, Geek5} \n\nIntersection of two sets is {GeeksForGeeks, Geek3} \n\nDifference of two sets is {Geek4, Geek5} " }, { "code": null, "e": 31424, "s": 31361, "text": "In the above code, we can also compare more than two sets as: " }, { "code": null, "e": 31434, "s": 31424, "text": "Example: " }, { "code": null, "e": 31439, "s": 31434, "text": "Dart" }, { "code": "// Comparing more than 2 sets in Dart void main(){ // Declaring set 1 with value var gfg1 = <String>{\"GeeksForGeeks\",\"Geek1\",\"Geek2\",\"Geek3\"}; // Declaring set 2 with value var gfg2 = <String>{\"GeeksForGeeks\",\"Geek3\",\"Geek4\",\"Geek5\"}; // Declaring set 3 with value var gfg3 = <String>{\"GeeksForGeeks\",\"Geek5\",\"Geek6\",\"Geek7\"}; // Finding Union print(\"Union of two sets is ${gfg1.union(gfg2).union(gfg3)}\\n\"); // Finding Intersection print(\"Intersection of two sets is ${gfg1.intersection(gfg2).intersection(gfg3)}\\n\"); // Finding Difference print(\"Difference of two sets is ${gfg2.difference(gfg1).difference(gfg3)}\\n\");}", "e": 32088, "s": 31439, "text": null }, { "code": null, "e": 32097, "s": 32088, "text": "Output: " }, { "code": null, "e": 32266, "s": 32097, "text": "Union of two sets is {GeeksForGeeks, Geek1, Geek2, Geek3, Geek4, Geek5, Geek6, Geek7} \n\nIntersection of two sets is {GeeksForGeeks} \n\nDifference of two sets is {Geek4} " }, { "code": null, "e": 32279, "s": 32266, "text": "simmytarika5" }, { "code": null, "e": 32288, "s": 32279, "text": "Dart-Set" }, { "code": null, "e": 32293, "s": 32288, "text": "Dart" }, { "code": null, "e": 32391, "s": 32293, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32430, "s": 32391, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32456, "s": 32430, "text": "ListView Class in Flutter" }, { "code": null, "e": 32482, "s": 32456, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 32505, "s": 32482, "text": "Flutter - Stack Widget" }, { "code": null, "e": 32523, "s": 32505, "text": "Flutter - Dialogs" }, { "code": null, "e": 32568, "s": 32523, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 32596, "s": 32568, "text": "Flutter - Positioned Widget" }, { "code": null, "e": 32620, "s": 32596, "text": "Format Dates in Flutter" }, { "code": null, "e": 32661, "s": 32620, "text": "Flutter - Managing the MediaQuery Object" } ]
Role of Subnet Mask - GeeksforGeeks
26 May, 2020 Suppose we have a Class A network that means we have 16 million hosts in a network. The task we have to do is: Maintenance of such a huge networkSecurity for the network – For example, we have 4 departments in a company and all of the 4 departments need not access the whole network. Maintenance of such a huge network Security for the network – For example, we have 4 departments in a company and all of the 4 departments need not access the whole network. For this we need subnetting i.e., dividing a huge network into smaller network. Now every department will have their own network . In case of addressing without subnetting, the process of reaching an address is done by 3 steps – Identification of the networkIdentification of the hostIdentification of the process Identification of the network Identification of the host Identification of the process In case of addressing with subnetting, the process of reaching an address is done by 4 steps – Identification of the networkIdentification of the subnetIdentification of the hostIdentification of the process Identification of the network Identification of the subnet Identification of the host Identification of the process Suppose we have a Class C network and we want to divide it into 4 subnets. To divide we need to choose 2 bits from the host part. As the first and last IP addresses are reserved for network ID and directed broadcast address in every subnet, we have to reserve 8 IP addresses in this case. A packet is received which has destination address -200.1.2.20 . Then how the router will identify that which subnet it belongs to . It’ll be done using Subnet Mask. A subnet mask is a 32-bit number which is used to identify the subnet of an IP address. The subnet mask is combination of 1’s and 0’s. 1’s represents network and subnet ID while 0’s represents the host ID. For this case, subnet mask is, 11111111.11111111.11111111.11000000 or 255.255.255.192 So in order to get the network which the destination address belongs to we have to bitwise & with subnet mask. 11111111.11111111.11111111.11000000 && 11001000.00000001.00000010.00010100 ----------------------------------------------------- 11001000.00000001.00000010.00000000 The address belongs to, 11001000.00000001.00000010.00000000 or 200.1.2.0 The internal router will forward the packet to the network through an interface . The interface will be identified by the routing table residing in the router. Routing table :If the network id doesn’t matches with any then the packet will be sent to default entry. Default entry has network id as 0.0.0.0. In some cases the network id may match with two entries in the routing table, so here the interface having the longest subnet mask(more 1’s) is selected. Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Introduction and IPv4 Datagram Header Secure Socket Layer (SSL) Cryptography and its Types ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Cache Memory in Computer Organization
[ { "code": null, "e": 25755, "s": 25727, "text": "\n26 May, 2020" }, { "code": null, "e": 25866, "s": 25755, "text": "Suppose we have a Class A network that means we have 16 million hosts in a network. The task we have to do is:" }, { "code": null, "e": 26039, "s": 25866, "text": "Maintenance of such a huge networkSecurity for the network – For example, we have 4 departments in a company and all of the 4 departments need not access the whole network." }, { "code": null, "e": 26074, "s": 26039, "text": "Maintenance of such a huge network" }, { "code": null, "e": 26213, "s": 26074, "text": "Security for the network – For example, we have 4 departments in a company and all of the 4 departments need not access the whole network." }, { "code": null, "e": 26344, "s": 26213, "text": "For this we need subnetting i.e., dividing a huge network into smaller network. Now every department will have their own network ." }, { "code": null, "e": 26442, "s": 26344, "text": "In case of addressing without subnetting, the process of reaching an address is done by 3 steps –" }, { "code": null, "e": 26527, "s": 26442, "text": "Identification of the networkIdentification of the hostIdentification of the process" }, { "code": null, "e": 26557, "s": 26527, "text": "Identification of the network" }, { "code": null, "e": 26584, "s": 26557, "text": "Identification of the host" }, { "code": null, "e": 26614, "s": 26584, "text": "Identification of the process" }, { "code": null, "e": 26709, "s": 26614, "text": "In case of addressing with subnetting, the process of reaching an address is done by 4 steps –" }, { "code": null, "e": 26822, "s": 26709, "text": "Identification of the networkIdentification of the subnetIdentification of the hostIdentification of the process" }, { "code": null, "e": 26852, "s": 26822, "text": "Identification of the network" }, { "code": null, "e": 26881, "s": 26852, "text": "Identification of the subnet" }, { "code": null, "e": 26908, "s": 26881, "text": "Identification of the host" }, { "code": null, "e": 26938, "s": 26908, "text": "Identification of the process" }, { "code": null, "e": 27068, "s": 26938, "text": "Suppose we have a Class C network and we want to divide it into 4 subnets. To divide we need to choose 2 bits from the host part." }, { "code": null, "e": 27227, "s": 27068, "text": "As the first and last IP addresses are reserved for network ID and directed broadcast address in every subnet, we have to reserve 8 IP addresses in this case." }, { "code": null, "e": 27393, "s": 27227, "text": "A packet is received which has destination address -200.1.2.20 . Then how the router will identify that which subnet it belongs to . It’ll be done using Subnet Mask." }, { "code": null, "e": 27630, "s": 27393, "text": "A subnet mask is a 32-bit number which is used to identify the subnet of an IP address. The subnet mask is combination of 1’s and 0’s. 1’s represents network and subnet ID while 0’s represents the host ID. For this case, subnet mask is," }, { "code": null, "e": 27687, "s": 27630, "text": "11111111.11111111.11111111.11000000 \nor\n255.255.255.192 " }, { "code": null, "e": 27798, "s": 27687, "text": "So in order to get the network which the destination address belongs to we have to bitwise & with subnet mask." }, { "code": null, "e": 27973, "s": 27798, "text": " 11111111.11111111.11111111.11000000\n&& 11001000.00000001.00000010.00010100\n-----------------------------------------------------\n 11001000.00000001.00000010.00000000 " }, { "code": null, "e": 27997, "s": 27973, "text": "The address belongs to," }, { "code": null, "e": 28048, "s": 27997, "text": "11001000.00000001.00000010.00000000 \nor\n200.1.2.0 " }, { "code": null, "e": 28208, "s": 28048, "text": "The internal router will forward the packet to the network through an interface . The interface will be identified by the routing table residing in the router." }, { "code": null, "e": 28354, "s": 28208, "text": "Routing table :If the network id doesn’t matches with any then the packet will be sent to default entry. Default entry has network id as 0.0.0.0." }, { "code": null, "e": 28508, "s": 28354, "text": "In some cases the network id may match with two entries in the routing table, so here the interface having the longest subnet mask(more 1’s) is selected." }, { "code": null, "e": 28526, "s": 28508, "text": "Computer Networks" }, { "code": null, "e": 28534, "s": 28526, "text": "GATE CS" }, { "code": null, "e": 28552, "s": 28534, "text": "Computer Networks" }, { "code": null, "e": 28650, "s": 28552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28685, "s": 28650, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 28718, "s": 28685, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 28756, "s": 28718, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 28782, "s": 28756, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 28809, "s": 28782, "text": "Cryptography and its Types" }, { "code": null, "e": 28833, "s": 28809, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28860, "s": 28833, "text": "Types of Operating Systems" }, { "code": null, "e": 28881, "s": 28860, "text": "Normal Forms in DBMS" }, { "code": null, "e": 28930, "s": 28881, "text": "Page Replacement Algorithms in Operating Systems" } ]
IPC through shared memory - GeeksforGeeks
22 Jul, 2019 Inter Process Communication through shared memory is a concept where two or more process can access the common memory. And communication is done via this shared memory where changes made by one process can be viewed by another process. The problem with pipes, fifo and message queue – is that for two process to exchange information. The information has to go through the kernel. Server reads from the input file. The server writes this data in a message using either a pipe, fifo or message queue. The client reads the data from the IPC channel,again requiring the data to be copied from kernel’s IPC buffer to the client’s buffer. Finally the data is copied from the client’s buffer.A total of four copies of data are required (2 read and 2 write). So, shared memory provides a way by letting two or more processes share a memory segment. With Shared Memory the data is only copied twice – from input file into shared memory and from shared memory to the output file.SYSTEM CALLS USED ARE:ftok(): is use to generate a unique key.shmget(): int shmget(key_t,size_tsize,intshmflg); upon successful completion, shmget() returns an identifier for the shared memory segment.shmat(): Before you can use a shared memory segment, you have to attach yourselfto it using shmat(). void *shmat(int shmid ,void *shmaddr ,int shmflg);shmid is shared memory id. shmaddr specifies specific address to use but we should setit to zero and OS will automatically choose the address.shmdt(): When you’re done with the shared memory segment, your program shoulddetach itself from it using shmdt(). int shmdt(void *shmaddr);shmctl(): when you detach from shared memory,it is not destroyed. So, to destroyshmctl() is used. shmctl(int shmid,IPC_RMID,NULL);SHARED MEMORY FOR WRITER PROCESS#include <iostream>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>using namespace std; int main(){ // ftok to generate unique key key_t key = ftok("shmfile",65); // shmget returns an identifier in shmid int shmid = shmget(key,1024,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(void*)0,0); cout<<"Write Data : "; gets(str); printf("Data written in memory: %s\n",str); //detach from shared memory shmdt(str); return 0;}SHARED MEMORY FOR READER PROCESS#include <iostream>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>using namespace std; int main(){ // ftok to generate unique key key_t key = ftok("shmfile",65); // shmget returns an identifier in shmid int shmid = shmget(key,1024,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(void*)0,0); printf("Data read from memory: %s\n",str); //detach from shared memory shmdt(str); // destroy the shared memory shmctl(shmid,IPC_RMID,NULL); return 0;}Output:My Personal Notes arrow_drop_upSave A total of four copies of data are required (2 read and 2 write). So, shared memory provides a way by letting two or more processes share a memory segment. With Shared Memory the data is only copied twice – from input file into shared memory and from shared memory to the output file. SYSTEM CALLS USED ARE: ftok(): is use to generate a unique key. shmget(): int shmget(key_t,size_tsize,intshmflg); upon successful completion, shmget() returns an identifier for the shared memory segment. shmat(): Before you can use a shared memory segment, you have to attach yourselfto it using shmat(). void *shmat(int shmid ,void *shmaddr ,int shmflg);shmid is shared memory id. shmaddr specifies specific address to use but we should setit to zero and OS will automatically choose the address. shmdt(): When you’re done with the shared memory segment, your program shoulddetach itself from it using shmdt(). int shmdt(void *shmaddr); shmctl(): when you detach from shared memory,it is not destroyed. So, to destroyshmctl() is used. shmctl(int shmid,IPC_RMID,NULL); SHARED MEMORY FOR WRITER PROCESS #include <iostream>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>using namespace std; int main(){ // ftok to generate unique key key_t key = ftok("shmfile",65); // shmget returns an identifier in shmid int shmid = shmget(key,1024,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(void*)0,0); cout<<"Write Data : "; gets(str); printf("Data written in memory: %s\n",str); //detach from shared memory shmdt(str); return 0;} SHARED MEMORY FOR READER PROCESS #include <iostream>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>using namespace std; int main(){ // ftok to generate unique key key_t key = ftok("shmfile",65); // shmget returns an identifier in shmid int shmid = shmget(key,1024,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(void*)0,0); printf("Data read from memory: %s\n",str); //detach from shared memory shmdt(str); // destroy the shared memory shmctl(shmid,IPC_RMID,NULL); return 0;} Output: ankursgh70 system-programming C Language Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C std::string class in C++ Command line arguments in C/C++ Enumeration (or enum) in C Types of Operating Systems Banker's Algorithm in Operating System Page Replacement Algorithms in Operating Systems Paging in Operating System Program for FCFS CPU Scheduling | Set 1
[ { "code": null, "e": 25667, "s": 25639, "text": "\n22 Jul, 2019" }, { "code": null, "e": 25903, "s": 25667, "text": "Inter Process Communication through shared memory is a concept where two or more process can access the common memory. And communication is done via this shared memory where changes made by one process can be viewed by another process." }, { "code": null, "e": 26047, "s": 25903, "text": "The problem with pipes, fifo and message queue – is that for two process to exchange information. The information has to go through the kernel." }, { "code": null, "e": 26081, "s": 26047, "text": "Server reads from the input file." }, { "code": null, "e": 26166, "s": 26081, "text": "The server writes this data in a message using either a pipe, fifo or message queue." }, { "code": null, "e": 26300, "s": 26166, "text": "The client reads the data from the IPC channel,again requiring the data to be copied from kernel’s IPC buffer to the client’s buffer." }, { "code": null, "e": 28578, "s": 26300, "text": "Finally the data is copied from the client’s buffer.A total of four copies of data are required (2 read and 2 write). So, shared memory provides a way by letting two or more processes share a memory segment. With Shared Memory the data is only copied twice – from input file into shared memory and from shared memory to the output file.SYSTEM CALLS USED ARE:ftok(): is use to generate a unique key.shmget(): int shmget(key_t,size_tsize,intshmflg); upon successful completion, shmget() returns an identifier for the shared memory segment.shmat(): Before you can use a shared memory segment, you have to attach yourselfto it using shmat(). void *shmat(int shmid ,void *shmaddr ,int shmflg);shmid is shared memory id. shmaddr specifies specific address to use but we should setit to zero and OS will automatically choose the address.shmdt(): When you’re done with the shared memory segment, your program shoulddetach itself from it using shmdt(). int shmdt(void *shmaddr);shmctl(): when you detach from shared memory,it is not destroyed. So, to destroyshmctl() is used. shmctl(int shmid,IPC_RMID,NULL);SHARED MEMORY FOR WRITER PROCESS#include <iostream>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>using namespace std; int main(){ // ftok to generate unique key key_t key = ftok(\"shmfile\",65); // shmget returns an identifier in shmid int shmid = shmget(key,1024,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(void*)0,0); cout<<\"Write Data : \"; gets(str); printf(\"Data written in memory: %s\\n\",str); //detach from shared memory shmdt(str); return 0;}SHARED MEMORY FOR READER PROCESS#include <iostream>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>using namespace std; int main(){ // ftok to generate unique key key_t key = ftok(\"shmfile\",65); // shmget returns an identifier in shmid int shmid = shmget(key,1024,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(void*)0,0); printf(\"Data read from memory: %s\\n\",str); //detach from shared memory shmdt(str); // destroy the shared memory shmctl(shmid,IPC_RMID,NULL); return 0;}Output:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28863, "s": 28578, "text": "A total of four copies of data are required (2 read and 2 write). So, shared memory provides a way by letting two or more processes share a memory segment. With Shared Memory the data is only copied twice – from input file into shared memory and from shared memory to the output file." }, { "code": null, "e": 28886, "s": 28863, "text": "SYSTEM CALLS USED ARE:" }, { "code": null, "e": 28927, "s": 28886, "text": "ftok(): is use to generate a unique key." }, { "code": null, "e": 29067, "s": 28927, "text": "shmget(): int shmget(key_t,size_tsize,intshmflg); upon successful completion, shmget() returns an identifier for the shared memory segment." }, { "code": null, "e": 29361, "s": 29067, "text": "shmat(): Before you can use a shared memory segment, you have to attach yourselfto it using shmat(). void *shmat(int shmid ,void *shmaddr ,int shmflg);shmid is shared memory id. shmaddr specifies specific address to use but we should setit to zero and OS will automatically choose the address." }, { "code": null, "e": 29501, "s": 29361, "text": "shmdt(): When you’re done with the shared memory segment, your program shoulddetach itself from it using shmdt(). int shmdt(void *shmaddr);" }, { "code": null, "e": 29632, "s": 29501, "text": "shmctl(): when you detach from shared memory,it is not destroyed. So, to destroyshmctl() is used. shmctl(int shmid,IPC_RMID,NULL);" }, { "code": null, "e": 29665, "s": 29632, "text": "SHARED MEMORY FOR WRITER PROCESS" }, { "code": "#include <iostream>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>using namespace std; int main(){ // ftok to generate unique key key_t key = ftok(\"shmfile\",65); // shmget returns an identifier in shmid int shmid = shmget(key,1024,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(void*)0,0); cout<<\"Write Data : \"; gets(str); printf(\"Data written in memory: %s\\n\",str); //detach from shared memory shmdt(str); return 0;}", "e": 30188, "s": 29665, "text": null }, { "code": null, "e": 30221, "s": 30188, "text": "SHARED MEMORY FOR READER PROCESS" }, { "code": "#include <iostream>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>using namespace std; int main(){ // ftok to generate unique key key_t key = ftok(\"shmfile\",65); // shmget returns an identifier in shmid int shmid = shmget(key,1024,0666|IPC_CREAT); // shmat to attach to shared memory char *str = (char*) shmat(shmid,(void*)0,0); printf(\"Data read from memory: %s\\n\",str); //detach from shared memory shmdt(str); // destroy the shared memory shmctl(shmid,IPC_RMID,NULL); return 0;}", "e": 30772, "s": 30221, "text": null }, { "code": null, "e": 30780, "s": 30772, "text": "Output:" }, { "code": null, "e": 30791, "s": 30780, "text": "ankursgh70" }, { "code": null, "e": 30810, "s": 30791, "text": "system-programming" }, { "code": null, "e": 30821, "s": 30810, "text": "C Language" }, { "code": null, "e": 30839, "s": 30821, "text": "Operating Systems" }, { "code": null, "e": 30857, "s": 30839, "text": "Operating Systems" }, { "code": null, "e": 30955, "s": 30857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30972, "s": 30955, "text": "Substring in C++" }, { "code": null, "e": 30994, "s": 30972, "text": "Function Pointer in C" }, { "code": null, "e": 31019, "s": 30994, "text": "std::string class in C++" }, { "code": null, "e": 31051, "s": 31019, "text": "Command line arguments in C/C++" }, { "code": null, "e": 31078, "s": 31051, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 31105, "s": 31078, "text": "Types of Operating Systems" }, { "code": null, "e": 31144, "s": 31105, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 31193, "s": 31144, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 31220, "s": 31193, "text": "Paging in Operating System" } ]
How to Merge/Combine Arrays using JavaScript ? - GeeksforGeeks
01 Jul, 2020 There are many ways of merging arrays in JavaScript. We will discuss two problem statements that are commonly encountered in merging arrays: Merge without removing duplicate elements.Merge after removing the duplicate elements. Merge without removing duplicate elements. Merge after removing the duplicate elements. Merge without removing duplicate elements: We will first begin with three arrays and merge them. Later, we will generalize it for an indefinite number of arrays. The three arrays are stated below:let nums1 = [1, 2, 3, 4]let nums2 = [3, 4, 5, 6]let nums3 = [5, 6, 7, 8] We have to merge them so the our new array becomes: combinedNums = [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8] Using concat() Method: The concat() method accept arrays as arguments and returns the merged array.<script> // Elements of nums2 and nums3 concatenated // with elements of nums1 and returns the // combined array - combinedSum array let combinedNums = nums1.concat(nums2, nums3); // More readable form let combinedNums = [].concat(nums1, nums2, nums3); console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]Using spread operator: Spread operator spreads the value of the array into its constituent elements.<script> let combinedNums = [...nums1, ...nums2, ...nums3]; console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]Using push() Method: The push() method is used with spread operator to pushes the elements of arrays into the existing array. It is especially helpful when we need to append a value to an existing array and need not return a new array.Note: If spread operator is not used, then arrays as a whole are appended.<script> nums1.push(...nums2, ...nums3); console.log(nums1); // If spread operator is not used nums1.push(nums2, nums3); console.log(nums1);</script>Output:first log: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8] second log: [1, 2, 3, 4, [3, 4, 5, 6], [5, 6, 7, 8]] Using concat() Method: The concat() method accept arrays as arguments and returns the merged array.<script> // Elements of nums2 and nums3 concatenated // with elements of nums1 and returns the // combined array - combinedSum array let combinedNums = nums1.concat(nums2, nums3); // More readable form let combinedNums = [].concat(nums1, nums2, nums3); console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8] <script> // Elements of nums2 and nums3 concatenated // with elements of nums1 and returns the // combined array - combinedSum array let combinedNums = nums1.concat(nums2, nums3); // More readable form let combinedNums = [].concat(nums1, nums2, nums3); console.log(combinedNums);</script> Output: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8] Using spread operator: Spread operator spreads the value of the array into its constituent elements.<script> let combinedNums = [...nums1, ...nums2, ...nums3]; console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8] <script> let combinedNums = [...nums1, ...nums2, ...nums3]; console.log(combinedNums);</script> Output: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8] Using push() Method: The push() method is used with spread operator to pushes the elements of arrays into the existing array. It is especially helpful when we need to append a value to an existing array and need not return a new array.Note: If spread operator is not used, then arrays as a whole are appended.<script> nums1.push(...nums2, ...nums3); console.log(nums1); // If spread operator is not used nums1.push(nums2, nums3); console.log(nums1);</script>Output:first log: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8] second log: [1, 2, 3, 4, [3, 4, 5, 6], [5, 6, 7, 8]] Note: If spread operator is not used, then arrays as a whole are appended. <script> nums1.push(...nums2, ...nums3); console.log(nums1); // If spread operator is not used nums1.push(nums2, nums3); console.log(nums1);</script> Output: first log: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8] second log: [1, 2, 3, 4, [3, 4, 5, 6], [5, 6, 7, 8]] We will now generalize this for merging of an indefinite number of arrays:Our function mergeArrays accepts any number of arrays as arguments (rest operator). We will iterate through each array with forEach loop and add it into our final array: mergedArray. Below are the implementations using concat, spread operator, and push method: Using array.concat() method:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = mergedArray.concat(array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Using spread operator:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Using Array.push() Method:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray.push(...array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Merging and removing duplicate elements: Consider the following three approaches for doing this:Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]My Personal Notes arrow_drop_upSave Using array.concat() method:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = mergedArray.concat(array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6] <script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = mergedArray.concat(array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script> Output: [1, 2, 3, 4, 3, 4, 5, 6] Using spread operator:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6] <script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script> Output: [1, 2, 3, 4, 3, 4, 5, 6] Using Array.push() Method:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray.push(...array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Merging and removing duplicate elements: Consider the following three approaches for doing this:Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]My Personal Notes arrow_drop_upSave <script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray.push(...array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script> Output: [1, 2, 3, 4, 3, 4, 5, 6] Merging and removing duplicate elements: Consider the following three approaches for doing this: Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8] Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8] <script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script> Output: [1, 2, 3, 4, 5, 6, 7, 8] Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8] <script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script> Output: [1, 2, 3, 4, 5, 6, 7, 8] Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8] <script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script> Output: [1, 2, 3, 4, 5, 6, 7, 8] JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25797, "s": 25769, "text": "\n01 Jul, 2020" }, { "code": null, "e": 25938, "s": 25797, "text": "There are many ways of merging arrays in JavaScript. We will discuss two problem statements that are commonly encountered in merging arrays:" }, { "code": null, "e": 26025, "s": 25938, "text": "Merge without removing duplicate elements.Merge after removing the duplicate elements." }, { "code": null, "e": 26068, "s": 26025, "text": "Merge without removing duplicate elements." }, { "code": null, "e": 26113, "s": 26068, "text": "Merge after removing the duplicate elements." }, { "code": null, "e": 26275, "s": 26113, "text": "Merge without removing duplicate elements: We will first begin with three arrays and merge them. Later, we will generalize it for an indefinite number of arrays." }, { "code": null, "e": 26382, "s": 26275, "text": "The three arrays are stated below:let nums1 = [1, 2, 3, 4]let nums2 = [3, 4, 5, 6]let nums3 = [5, 6, 7, 8]" }, { "code": null, "e": 26434, "s": 26382, "text": "We have to merge them so the our new array becomes:" }, { "code": null, "e": 26486, "s": 26434, "text": "combinedNums = [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]" }, { "code": null, "e": 27774, "s": 26486, "text": "Using concat() Method: The concat() method accept arrays as arguments and returns the merged array.<script> // Elements of nums2 and nums3 concatenated // with elements of nums1 and returns the // combined array - combinedSum array let combinedNums = nums1.concat(nums2, nums3); // More readable form let combinedNums = [].concat(nums1, nums2, nums3); console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]Using spread operator: Spread operator spreads the value of the array into its constituent elements.<script> let combinedNums = [...nums1, ...nums2, ...nums3]; console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]Using push() Method: The push() method is used with spread operator to pushes the elements of arrays into the existing array. It is especially helpful when we need to append a value to an existing array and need not return a new array.Note: If spread operator is not used, then arrays as a whole are appended.<script> nums1.push(...nums2, ...nums3); console.log(nums1); // If spread operator is not used nums1.push(nums2, nums3); console.log(nums1);</script>Output:first log: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]\nsecond log: [1, 2, 3, 4, [3, 4, 5, 6], [5, 6, 7, 8]]\n" }, { "code": null, "e": 28233, "s": 27774, "text": "Using concat() Method: The concat() method accept arrays as arguments and returns the merged array.<script> // Elements of nums2 and nums3 concatenated // with elements of nums1 and returns the // combined array - combinedSum array let combinedNums = nums1.concat(nums2, nums3); // More readable form let combinedNums = [].concat(nums1, nums2, nums3); console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]" }, { "code": "<script> // Elements of nums2 and nums3 concatenated // with elements of nums1 and returns the // combined array - combinedSum array let combinedNums = nums1.concat(nums2, nums3); // More readable form let combinedNums = [].concat(nums1, nums2, nums3); console.log(combinedNums);</script>", "e": 28550, "s": 28233, "text": null }, { "code": null, "e": 28558, "s": 28550, "text": "Output:" }, { "code": null, "e": 28595, "s": 28558, "text": "[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]" }, { "code": null, "e": 28842, "s": 28595, "text": "Using spread operator: Spread operator spreads the value of the array into its constituent elements.<script> let combinedNums = [...nums1, ...nums2, ...nums3]; console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]" }, { "code": "<script> let combinedNums = [...nums1, ...nums2, ...nums3]; console.log(combinedNums);</script>", "e": 28946, "s": 28842, "text": null }, { "code": null, "e": 28954, "s": 28946, "text": "Output:" }, { "code": null, "e": 28991, "s": 28954, "text": "[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]" }, { "code": null, "e": 29575, "s": 28991, "text": "Using push() Method: The push() method is used with spread operator to pushes the elements of arrays into the existing array. It is especially helpful when we need to append a value to an existing array and need not return a new array.Note: If spread operator is not used, then arrays as a whole are appended.<script> nums1.push(...nums2, ...nums3); console.log(nums1); // If spread operator is not used nums1.push(nums2, nums3); console.log(nums1);</script>Output:first log: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]\nsecond log: [1, 2, 3, 4, [3, 4, 5, 6], [5, 6, 7, 8]]\n" }, { "code": null, "e": 29650, "s": 29575, "text": "Note: If spread operator is not used, then arrays as a whole are appended." }, { "code": "<script> nums1.push(...nums2, ...nums3); console.log(nums1); // If spread operator is not used nums1.push(nums2, nums3); console.log(nums1);</script>", "e": 29817, "s": 29650, "text": null }, { "code": null, "e": 29825, "s": 29817, "text": "Output:" }, { "code": null, "e": 29927, "s": 29825, "text": "first log: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]\nsecond log: [1, 2, 3, 4, [3, 4, 5, 6], [5, 6, 7, 8]]\n" }, { "code": null, "e": 30184, "s": 29927, "text": "We will now generalize this for merging of an indefinite number of arrays:Our function mergeArrays accepts any number of arrays as arguments (rest operator). We will iterate through each array with forEach loop and add it into our final array: mergedArray." }, { "code": null, "e": 30262, "s": 30184, "text": "Below are the implementations using concat, spread operator, and push method:" }, { "code": null, "e": 33895, "s": 30262, "text": "Using array.concat() method:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = mergedArray.concat(array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Using spread operator:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Using Array.push() Method:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray.push(...array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Merging and removing duplicate elements: Consider the following three approaches for doing this:Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 34278, "s": 33895, "text": "Using array.concat() method:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = mergedArray.concat(array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]" }, { "code": "<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = mergedArray.concat(array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>", "e": 34602, "s": 34278, "text": null }, { "code": null, "e": 34610, "s": 34602, "text": "Output:" }, { "code": null, "e": 34635, "s": 34610, "text": "[1, 2, 3, 4, 3, 4, 5, 6]" }, { "code": null, "e": 35013, "s": 34635, "text": "Using spread operator:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]" }, { "code": "<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>", "e": 35338, "s": 35013, "text": null }, { "code": null, "e": 35346, "s": 35338, "text": "Output:" }, { "code": null, "e": 35371, "s": 35346, "text": "[1, 2, 3, 4, 3, 4, 5, 6]" }, { "code": null, "e": 38245, "s": 35371, "text": "Using Array.push() Method:<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray.push(...array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Merging and removing duplicate elements: Consider the following three approaches for doing this:Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]My Personal Notes\narrow_drop_upSave" }, { "code": "<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; function mergeArrays(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray.push(...array) }); return mergedArray; } console.log(mergeArrays(nums1, nums2));</script>", "e": 38556, "s": 38245, "text": null }, { "code": null, "e": 38564, "s": 38556, "text": "Output:" }, { "code": null, "e": 38589, "s": 38564, "text": "[1, 2, 3, 4, 3, 4, 5, 6]" }, { "code": null, "e": 38686, "s": 38589, "text": "Merging and removing duplicate elements: Consider the following three approaches for doing this:" }, { "code": null, "e": 41062, "s": 38686, "text": "Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": null, "e": 41718, "s": 41062, "text": "Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": "<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); return [...new Set([...mergedArray])]; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>", "e": 42109, "s": 41718, "text": null }, { "code": null, "e": 42117, "s": 42109, "text": "Output:" }, { "code": null, "e": 42142, "s": 42117, "text": "[1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": null, "e": 42911, "s": 42142, "text": "Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": "<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .filter((item, index) => mergedArray.indexOf(item) === index); return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>", "e": 43415, "s": 42911, "text": null }, { "code": null, "e": 43423, "s": 43415, "text": "Output:" }, { "code": null, "e": 43448, "s": 43423, "text": "[1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": null, "e": 44401, "s": 43448, "text": "Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": "<script> let nums1 = [1, 2, 3, 4]; let nums2 = [3, 4, 5, 6]; let nums3 = [5, 6, 7, 8]; function mergeNoDuplicates(...arrays) { let mergedArray = []; arrays.forEach(array => { mergedArray = [...mergedArray, ...array] }); const mergedUnique = mergedArray .reduce((noDuplicates, item) => { if (noDuplicates.includes(item)) { return noDuplicates; } else { return [...noDuplicates, item]; } }, []) return mergedUnique; } console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>", "e": 45050, "s": 44401, "text": null }, { "code": null, "e": 45058, "s": 45050, "text": "Output:" }, { "code": null, "e": 45083, "s": 45058, "text": "[1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": null, "e": 45099, "s": 45083, "text": "JavaScript-Misc" }, { "code": null, "e": 45110, "s": 45099, "text": "JavaScript" }, { "code": null, "e": 45127, "s": 45110, "text": "Web Technologies" }, { "code": null, "e": 45225, "s": 45127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45265, "s": 45225, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 45310, "s": 45265, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45371, "s": 45310, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 45443, "s": 45371, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 45489, "s": 45443, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 45529, "s": 45489, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 45562, "s": 45529, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 45607, "s": 45562, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45650, "s": 45607, "text": "How to fetch data from an API in ReactJS ?" } ]
Shortest distance between two nodes in BST - GeeksforGeeks
17 Mar, 2022 Given a Binary Search Tree and two keys in it. Find the distance between two nodes with given two keys. It may be assumed that both keys exist in BST. Examples: Input: Root of above tree a = 3, b = 9 Output: 4 Distance between 3 and 9 in above BST is 4. Input: Root of above tree a = 9, b = 25 Output: 3 Distance between 9 and 25 in above BST is 3. We have discussed distance between two nodes in binary tree. The time complexity of this solution is O(n)In the case of BST, we can find the distance faster. We start from the root and for every node, we do following. If both keys are greater than the current node, we move to the right child of the current node.If both keys are smaller than current node, we move to left child of current node.If one keys is smaller and other key is greater, current node is Lowest Common Ancestor (LCA) of two nodes. We find distances of current node from two keys and return sum of the distances. If both keys are greater than the current node, we move to the right child of the current node. If both keys are smaller than current node, we move to left child of current node. If one keys is smaller and other key is greater, current node is Lowest Common Ancestor (LCA) of two nodes. We find distances of current node from two keys and return sum of the distances. C++ Java Python3 C# Javascript // CPP program to find distance between// two nodes in BST#include <bits/stdc++.h>using namespace std; struct Node { struct Node* left, *right; int key;}; struct Node* newNode(int key){ struct Node* ptr = new Node; ptr->key = key; ptr->left = ptr->right = NULL; return ptr;} // Standard BST insert functionstruct Node* insert(struct Node* root, int key){ if (!root) root = newNode(key); else if (root->key > key) root->left = insert(root->left, key); else if (root->key < key) root->right = insert(root->right, key); return root;} // This function returns distance of x from// root. This function assumes that x exists// in BST and BST is not NULL.int distanceFromRoot(struct Node* root, int x){ if (root->key == x) return 0; else if (root->key > x) return 1 + distanceFromRoot(root->left, x); return 1 + distanceFromRoot(root->right, x);} // Returns minimum distance between a and b.// This function assumes that a and b exist// in BST.int distanceBetween2(struct Node* root, int a, int b){ if (!root) return 0; // Both keys lie in left if (root->key > a && root->key > b) return distanceBetween2(root->left, a, b); // Both keys lie in right if (root->key < a && root->key < b) // same path return distanceBetween2(root->right, a, b); // Lie in opposite directions (Root is // LCA of two nodes) if (root->key >= a && root->key <= b) return distanceFromRoot(root, a) + distanceFromRoot(root, b);} // This function make sure that a is smaller// than b before making a call to findDistWrapper()int findDistWrapper(Node *root, int a, int b){ if (a > b) swap(a, b); return distanceBetween2(root, a, b); } // Driver codeint main(){ struct Node* root = NULL; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); int a = 5, b = 55; cout << findDistWrapper(root, 5, 35); return 0;} // Java program to find distance between// two nodes in BSTclass GfG { static class Node { Node left, right; int key;} static Node newNode(int key){ Node ptr = new Node(); ptr.key = key; ptr.left = null; ptr.right = null; return ptr;} // Standard BST insert functionstatic Node insert(Node root, int key){ if (root == null) root = newNode(key); else if (root.key > key) root.left = insert(root.left, key); else if (root.key < key) root.right = insert(root.right, key); return root;} // This function returns distance of x from// root. This function assumes that x exists// in BST and BST is not NULL.static int distanceFromRoot(Node root, int x){ if (root.key == x) return 0; else if (root.key > x) return 1 + distanceFromRoot(root.left, x); return 1 + distanceFromRoot(root.right, x);} // Returns minimum distance between a and b.// This function assumes that a and b exist// in BST.static int distanceBetween2(Node root, int a, int b){ if (root == null) return 0; // Both keys lie in left if (root.key > a && root.key > b) return distanceBetween2(root.left, a, b); // Both keys lie in right if (root.key < a && root.key < b) // same path return distanceBetween2(root.right, a, b); // Lie in opposite directions (Root is // LCA of two nodes) if (root.key >= a && root.key <= b) return distanceFromRoot(root, a) + distanceFromRoot(root, b); return 0;} // This function make sure that a is smaller// than b before making a call to findDistWrapper()static int findDistWrapper(Node root, int a, int b){ int temp = 0;if (a > b) { temp = a; a = b; b = temp; }return distanceBetween2(root, a, b);} // Driver codepublic static void main(String[] args){ Node root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); System.out.println(findDistWrapper(root, 5, 35));}} # Python3 program to find distance between# two nodes in BSTclass newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Standard BST insert functiondef insert(root, key): if root == None: root = newNode(key) else if root.key > key: root.left = insert(root.left, key) else if root.key < key: root.right = insert(root.right, key) return root # This function returns distance of x from# root. This function assumes that x exists# in BST and BST is not NULL.def distanceFromRoot(root, x): if root.key == x: return 0 else if root.key > x: return 1 + distanceFromRoot(root.left, x) return 1 + distanceFromRoot(root.right, x) # Returns minimum distance between a and b.# This function assumes that a and b exist# in BST.def distanceBetween2(root, a, b): if root == None: return 0 # Both keys lie in left if root.key > a and root.key > b: return distanceBetween2(root.left, a, b) # Both keys lie in right if root.key < a and root.key < b: # same path return distanceBetween2(root.right, a, b) # Lie in opposite directions # (Root is LCA of two nodes) if root.key >= a and root.key <= b: return (distanceFromRoot(root, a) + distanceFromRoot(root, b)) # This function make sure that a is smaller# than b before making a call to findDistWrapper()def findDistWrapper(root, a, b): if a > b: a, b = b, a return distanceBetween2(root, a, b) # Driver codeif __name__ == '__main__': root = None root = insert(root, 20) insert(root, 10) insert(root, 5) insert(root, 15) insert(root, 30) insert(root, 25) insert(root, 35) a, b = 5, 55 print(findDistWrapper(root, 5, 35)) # This code is contributed by PranchalK // C# program to find distance between// two nodes in BSTusing System; class GfG{ public class Node{ public Node left, right; public int key;} static Node newNode(int key){ Node ptr = new Node(); ptr.key = key; ptr.left = null; ptr.right = null; return ptr;} // Standard BST insert functionstatic Node insert(Node root, int key){ if (root == null) root = newNode(key); else if (root.key > key) root.left = insert(root.left, key); else if (root.key < key) root.right = insert(root.right, key); return root;} // This function returns distance of x from// root. This function assumes that x exists// in BST and BST is not NULL.static int distanceFromRoot(Node root, int x){ if (root.key == x) return 0; else if (root.key > x) return 1 + distanceFromRoot(root.left, x); return 1 + distanceFromRoot(root.right, x);} // Returns minimum distance between a and b.// This function assumes that a and b exist// in BST.static int distanceBetween2(Node root, int a, int b){ if (root == null) return 0; // Both keys lie in left if (root.key > a && root.key > b) return distanceBetween2(root.left, a, b); // Both keys lie in right if (root.key < a && root.key < b) // same path return distanceBetween2(root.right, a, b); // Lie in opposite directions (Root is // LCA of two nodes) if (root.key >= a && root.key <= b) return distanceFromRoot(root, a) + distanceFromRoot(root, b); return 0;} // This function make sure that a is smaller// than b before making a call to findDistWrapper()static int findDistWrapper(Node root, int a, int b){ int temp = 0;if (a > b) { temp = a; a = b; b = temp; }return distanceBetween2(root, a, b);} // Driver codepublic static void Main(String[] args){ Node root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); Console.WriteLine(findDistWrapper(root, 5, 35));}} // This code contributed by Rajput-Ji <script> // JavaScript program to find distance between// two nodes in BST class Node { constructor() { this.key = 0; this.left = null; this.right = null; } } function newNode(key) {var ptr = new Node(); ptr.key = key; ptr.left = null; ptr.right = null; return ptr; } // Standard BST insert function function insert(root , key) { if (root == null) root = newNode(key); else if (root.key > key) root.left = insert(root.left, key); else if (root.key < key) root.right = insert(root.right, key); return root; } // This function returns distance of x from // root. This function assumes that x exists // in BST and BST is not NULL. function distanceFromRoot(root , x) { if (root.key == x) return 0; else if (root.key > x) return 1 + distanceFromRoot(root.left, x); return 1 + distanceFromRoot(root.right, x); } // Returns minimum distance between a and b. // This function assumes that a and b exist // in BST. function distanceBetween2(root , a , b) { if (root == null) return 0; // Both keys lie in left if (root.key > a && root.key > b) return distanceBetween2(root.left, a, b); // Both keys lie in right if (root.key < a && root.key < b) // same path return distanceBetween2(root.right, a, b); // Lie in opposite directions (Root is // LCA of two nodes) if (root.key >= a && root.key <= b) return distanceFromRoot(root, a) + distanceFromRoot(root, b); return 0; } // This function make sure that a is smaller // than b before making a call to findDistWrapper() function findDistWrapper(root , a , b) { var temp = 0; if (a > b) { temp = a; a = b; b = temp; } return distanceBetween2(root, a, b); } // Driver code var root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); document.write(findDistWrapper(root, 5, 35)); // This code is contributed by todaysgaurav </script> Output: 4 Time Complexity: O(h) where h is height of Binary Search Tree. This article is contributed by Shweta Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prerna saini PranchalKatiyar Rajput-Ji Akanksha_Rai todaysgaurav sagartomar9927 surinderdawra388 Amazon LCA Ola Cabs Qualcomm Samsung Binary Search Tree Amazon Samsung Ola Cabs Qualcomm Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advantages of BST over Hash Table Difference between Binary Tree and Binary Search Tree Binary Tree to Binary Search Tree Conversion Merge Two Balanced Binary Search Trees set vs unordered_set in C++ STL Sorted Linked List to Balanced BST Insert a node in Binary Search Tree Iteratively C Program for Red Black Tree Insertion How to handle duplicates in Binary Search Tree? K'th largest element in a stream
[ { "code": null, "e": 26505, "s": 26477, "text": "\n17 Mar, 2022" }, { "code": null, "e": 26656, "s": 26505, "text": "Given a Binary Search Tree and two keys in it. Find the distance between two nodes with given two keys. It may be assumed that both keys exist in BST." }, { "code": null, "e": 26668, "s": 26656, "text": "Examples: " }, { "code": null, "e": 26878, "s": 26668, "text": "Input: Root of above tree\n a = 3, b = 9\nOutput: 4\nDistance between 3 and 9 in \nabove BST is 4.\n\nInput: Root of above tree\n a = 9, b = 25\nOutput: 3\nDistance between 9 and 25 in \nabove BST is 3." }, { "code": null, "e": 27097, "s": 26878, "text": "We have discussed distance between two nodes in binary tree. The time complexity of this solution is O(n)In the case of BST, we can find the distance faster. We start from the root and for every node, we do following. " }, { "code": null, "e": 27463, "s": 27097, "text": "If both keys are greater than the current node, we move to the right child of the current node.If both keys are smaller than current node, we move to left child of current node.If one keys is smaller and other key is greater, current node is Lowest Common Ancestor (LCA) of two nodes. We find distances of current node from two keys and return sum of the distances." }, { "code": null, "e": 27559, "s": 27463, "text": "If both keys are greater than the current node, we move to the right child of the current node." }, { "code": null, "e": 27642, "s": 27559, "text": "If both keys are smaller than current node, we move to left child of current node." }, { "code": null, "e": 27831, "s": 27642, "text": "If one keys is smaller and other key is greater, current node is Lowest Common Ancestor (LCA) of two nodes. We find distances of current node from two keys and return sum of the distances." }, { "code": null, "e": 27835, "s": 27831, "text": "C++" }, { "code": null, "e": 27840, "s": 27835, "text": "Java" }, { "code": null, "e": 27848, "s": 27840, "text": "Python3" }, { "code": null, "e": 27851, "s": 27848, "text": "C#" }, { "code": null, "e": 27862, "s": 27851, "text": "Javascript" }, { "code": "// CPP program to find distance between// two nodes in BST#include <bits/stdc++.h>using namespace std; struct Node { struct Node* left, *right; int key;}; struct Node* newNode(int key){ struct Node* ptr = new Node; ptr->key = key; ptr->left = ptr->right = NULL; return ptr;} // Standard BST insert functionstruct Node* insert(struct Node* root, int key){ if (!root) root = newNode(key); else if (root->key > key) root->left = insert(root->left, key); else if (root->key < key) root->right = insert(root->right, key); return root;} // This function returns distance of x from// root. This function assumes that x exists// in BST and BST is not NULL.int distanceFromRoot(struct Node* root, int x){ if (root->key == x) return 0; else if (root->key > x) return 1 + distanceFromRoot(root->left, x); return 1 + distanceFromRoot(root->right, x);} // Returns minimum distance between a and b.// This function assumes that a and b exist// in BST.int distanceBetween2(struct Node* root, int a, int b){ if (!root) return 0; // Both keys lie in left if (root->key > a && root->key > b) return distanceBetween2(root->left, a, b); // Both keys lie in right if (root->key < a && root->key < b) // same path return distanceBetween2(root->right, a, b); // Lie in opposite directions (Root is // LCA of two nodes) if (root->key >= a && root->key <= b) return distanceFromRoot(root, a) + distanceFromRoot(root, b);} // This function make sure that a is smaller// than b before making a call to findDistWrapper()int findDistWrapper(Node *root, int a, int b){ if (a > b) swap(a, b); return distanceBetween2(root, a, b); } // Driver codeint main(){ struct Node* root = NULL; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); int a = 5, b = 55; cout << findDistWrapper(root, 5, 35); return 0;}", "e": 29900, "s": 27862, "text": null }, { "code": "// Java program to find distance between// two nodes in BSTclass GfG { static class Node { Node left, right; int key;} static Node newNode(int key){ Node ptr = new Node(); ptr.key = key; ptr.left = null; ptr.right = null; return ptr;} // Standard BST insert functionstatic Node insert(Node root, int key){ if (root == null) root = newNode(key); else if (root.key > key) root.left = insert(root.left, key); else if (root.key < key) root.right = insert(root.right, key); return root;} // This function returns distance of x from// root. This function assumes that x exists// in BST and BST is not NULL.static int distanceFromRoot(Node root, int x){ if (root.key == x) return 0; else if (root.key > x) return 1 + distanceFromRoot(root.left, x); return 1 + distanceFromRoot(root.right, x);} // Returns minimum distance between a and b.// This function assumes that a and b exist// in BST.static int distanceBetween2(Node root, int a, int b){ if (root == null) return 0; // Both keys lie in left if (root.key > a && root.key > b) return distanceBetween2(root.left, a, b); // Both keys lie in right if (root.key < a && root.key < b) // same path return distanceBetween2(root.right, a, b); // Lie in opposite directions (Root is // LCA of two nodes) if (root.key >= a && root.key <= b) return distanceFromRoot(root, a) + distanceFromRoot(root, b); return 0;} // This function make sure that a is smaller// than b before making a call to findDistWrapper()static int findDistWrapper(Node root, int a, int b){ int temp = 0;if (a > b) { temp = a; a = b; b = temp; }return distanceBetween2(root, a, b);} // Driver codepublic static void main(String[] args){ Node root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); System.out.println(findDistWrapper(root, 5, 35));}}", "e": 31937, "s": 29900, "text": null }, { "code": "# Python3 program to find distance between# two nodes in BSTclass newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Standard BST insert functiondef insert(root, key): if root == None: root = newNode(key) else if root.key > key: root.left = insert(root.left, key) else if root.key < key: root.right = insert(root.right, key) return root # This function returns distance of x from# root. This function assumes that x exists# in BST and BST is not NULL.def distanceFromRoot(root, x): if root.key == x: return 0 else if root.key > x: return 1 + distanceFromRoot(root.left, x) return 1 + distanceFromRoot(root.right, x) # Returns minimum distance between a and b.# This function assumes that a and b exist# in BST.def distanceBetween2(root, a, b): if root == None: return 0 # Both keys lie in left if root.key > a and root.key > b: return distanceBetween2(root.left, a, b) # Both keys lie in right if root.key < a and root.key < b: # same path return distanceBetween2(root.right, a, b) # Lie in opposite directions # (Root is LCA of two nodes) if root.key >= a and root.key <= b: return (distanceFromRoot(root, a) + distanceFromRoot(root, b)) # This function make sure that a is smaller# than b before making a call to findDistWrapper()def findDistWrapper(root, a, b): if a > b: a, b = b, a return distanceBetween2(root, a, b) # Driver codeif __name__ == '__main__': root = None root = insert(root, 20) insert(root, 10) insert(root, 5) insert(root, 15) insert(root, 30) insert(root, 25) insert(root, 35) a, b = 5, 55 print(findDistWrapper(root, 5, 35)) # This code is contributed by PranchalK", "e": 33795, "s": 31937, "text": null }, { "code": "// C# program to find distance between// two nodes in BSTusing System; class GfG{ public class Node{ public Node left, right; public int key;} static Node newNode(int key){ Node ptr = new Node(); ptr.key = key; ptr.left = null; ptr.right = null; return ptr;} // Standard BST insert functionstatic Node insert(Node root, int key){ if (root == null) root = newNode(key); else if (root.key > key) root.left = insert(root.left, key); else if (root.key < key) root.right = insert(root.right, key); return root;} // This function returns distance of x from// root. This function assumes that x exists// in BST and BST is not NULL.static int distanceFromRoot(Node root, int x){ if (root.key == x) return 0; else if (root.key > x) return 1 + distanceFromRoot(root.left, x); return 1 + distanceFromRoot(root.right, x);} // Returns minimum distance between a and b.// This function assumes that a and b exist// in BST.static int distanceBetween2(Node root, int a, int b){ if (root == null) return 0; // Both keys lie in left if (root.key > a && root.key > b) return distanceBetween2(root.left, a, b); // Both keys lie in right if (root.key < a && root.key < b) // same path return distanceBetween2(root.right, a, b); // Lie in opposite directions (Root is // LCA of two nodes) if (root.key >= a && root.key <= b) return distanceFromRoot(root, a) + distanceFromRoot(root, b); return 0;} // This function make sure that a is smaller// than b before making a call to findDistWrapper()static int findDistWrapper(Node root, int a, int b){ int temp = 0;if (a > b) { temp = a; a = b; b = temp; }return distanceBetween2(root, a, b);} // Driver codepublic static void Main(String[] args){ Node root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); Console.WriteLine(findDistWrapper(root, 5, 35));}} // This code contributed by Rajput-Ji", "e": 35908, "s": 33795, "text": null }, { "code": "<script> // JavaScript program to find distance between// two nodes in BST class Node { constructor() { this.key = 0; this.left = null; this.right = null; } } function newNode(key) {var ptr = new Node(); ptr.key = key; ptr.left = null; ptr.right = null; return ptr; } // Standard BST insert function function insert(root , key) { if (root == null) root = newNode(key); else if (root.key > key) root.left = insert(root.left, key); else if (root.key < key) root.right = insert(root.right, key); return root; } // This function returns distance of x from // root. This function assumes that x exists // in BST and BST is not NULL. function distanceFromRoot(root , x) { if (root.key == x) return 0; else if (root.key > x) return 1 + distanceFromRoot(root.left, x); return 1 + distanceFromRoot(root.right, x); } // Returns minimum distance between a and b. // This function assumes that a and b exist // in BST. function distanceBetween2(root , a , b) { if (root == null) return 0; // Both keys lie in left if (root.key > a && root.key > b) return distanceBetween2(root.left, a, b); // Both keys lie in right if (root.key < a && root.key < b) // same path return distanceBetween2(root.right, a, b); // Lie in opposite directions (Root is // LCA of two nodes) if (root.key >= a && root.key <= b) return distanceFromRoot(root, a) + distanceFromRoot(root, b); return 0; } // This function make sure that a is smaller // than b before making a call to findDistWrapper() function findDistWrapper(root , a , b) { var temp = 0; if (a > b) { temp = a; a = b; b = temp; } return distanceBetween2(root, a, b); } // Driver code var root = null; root = insert(root, 20); insert(root, 10); insert(root, 5); insert(root, 15); insert(root, 30); insert(root, 25); insert(root, 35); document.write(findDistWrapper(root, 5, 35)); // This code is contributed by todaysgaurav </script>", "e": 38297, "s": 35908, "text": null }, { "code": null, "e": 38307, "s": 38297, "text": "Output: " }, { "code": null, "e": 38309, "s": 38307, "text": "4" }, { "code": null, "e": 38372, "s": 38309, "text": "Time Complexity: O(h) where h is height of Binary Search Tree." }, { "code": null, "e": 38793, "s": 38372, "text": "This article is contributed by Shweta Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 38806, "s": 38793, "text": "prerna saini" }, { "code": null, "e": 38822, "s": 38806, "text": "PranchalKatiyar" }, { "code": null, "e": 38832, "s": 38822, "text": "Rajput-Ji" }, { "code": null, "e": 38845, "s": 38832, "text": "Akanksha_Rai" }, { "code": null, "e": 38858, "s": 38845, "text": "todaysgaurav" }, { "code": null, "e": 38873, "s": 38858, "text": "sagartomar9927" }, { "code": null, "e": 38890, "s": 38873, "text": "surinderdawra388" }, { "code": null, "e": 38897, "s": 38890, "text": "Amazon" }, { "code": null, "e": 38901, "s": 38897, "text": "LCA" }, { "code": null, "e": 38910, "s": 38901, "text": "Ola Cabs" }, { "code": null, "e": 38919, "s": 38910, "text": "Qualcomm" }, { "code": null, "e": 38927, "s": 38919, "text": "Samsung" }, { "code": null, "e": 38946, "s": 38927, "text": "Binary Search Tree" }, { "code": null, "e": 38953, "s": 38946, "text": "Amazon" }, { "code": null, "e": 38961, "s": 38953, "text": "Samsung" }, { "code": null, "e": 38970, "s": 38961, "text": "Ola Cabs" }, { "code": null, "e": 38979, "s": 38970, "text": "Qualcomm" }, { "code": null, "e": 38998, "s": 38979, "text": "Binary Search Tree" }, { "code": null, "e": 39096, "s": 38998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39130, "s": 39096, "text": "Advantages of BST over Hash Table" }, { "code": null, "e": 39184, "s": 39130, "text": "Difference between Binary Tree and Binary Search Tree" }, { "code": null, "e": 39229, "s": 39184, "text": "Binary Tree to Binary Search Tree Conversion" }, { "code": null, "e": 39268, "s": 39229, "text": "Merge Two Balanced Binary Search Trees" }, { "code": null, "e": 39300, "s": 39268, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 39335, "s": 39300, "text": "Sorted Linked List to Balanced BST" }, { "code": null, "e": 39383, "s": 39335, "text": "Insert a node in Binary Search Tree Iteratively" }, { "code": null, "e": 39422, "s": 39383, "text": "C Program for Red Black Tree Insertion" }, { "code": null, "e": 39470, "s": 39422, "text": "How to handle duplicates in Binary Search Tree?" } ]
Named List in R Programming - GeeksforGeeks
22 Jun, 2020 A list is an object in R Language which consists of heterogeneous elements. A list can even contain matrices, data frames, or functions as its elements. The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them. Named list can also be created using names() function to specify the names of elements after defining the list. In this article, we’ll learn to create named list in R using two different methods and different operations that can be performed on named lists. Syntax: names(x) <- value Parameters:x: represents an R objectvalue: represents names that has to be given to elements of x object A Named list can be created by two methods. The first one is by allocating the names to the elements while defining the list and another method is by using names() function. Example 1:In this example, we are going to create a named list without using names() function. # Defining a list with namesx <- list(mt = matrix(1:6, nrow = 2), lt = letters[1:8], n = c(1:10)) # Print whole listcat("Whole List:\n")print(x) Output: Whole List: $mt [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 $lt [1] "a" "b" "c" "d" "e" "f" "g" "h" $n [1] 1 2 3 4 5 6 7 8 9 10 Example 2:In this example, we are going to define the names of elements of the list using names() function after defining the list. # Defining listx <- list(matrix(1:6, nrow = 2), letters[1:8], c(1:10)) # Print whole listcat("Whole list:\n")print(x) Output: Whole list: [[1]] [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [[2]] [1] "a" "b" "c" "d" "e" "f" "g" "h" [[3]] [1] 1 2 3 4 5 6 7 8 9 10 Components of a named list can be easily accessed by $ operator. Example: # Defining a list with namesx <- list(mt = matrix(1:6, nrow = 2), lt = letters[1:8], n = c(1:10)) # Print list elements using the names given# Prints element of the list named "mt"cat("Element named 'mt':\n")print(x$mt)cat("\n") # Print element of the list named "n"cat("Element named 'n':\n")print(x$n) Output: Element named 'mt': [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 Element named 'n': [1] 1 2 3 4 5 6 7 8 9 10 Components of named list can be modified by assigning new values to them. Example: # Defining a named listlt <- list(a = 1, let = letters[1:8], mt = matrix(1:6, nrow = 2)) cat("List before modifying:\n")print(lt) # Modifying element named 'a'lt$a <- 5 cat("List after modifying:\n")print(lt) Output: List before modifying: $a [1] 1 $let [1] "a" "b" "c" "d" "e" "f" "g" "h" $mt [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 List after modifying: $a [1] 5 $let [1] "a" "b" "c" "d" "e" "f" "g" "h" $mt [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 To delete elements from named list, we’ll use within() function and the result will be assigned to the named list itself. Example: # Defining a named listlt <- list(a = 1, let = letters[1:8], mt = matrix(1:6, nrow = 2)) cat("List before deleting:\n")print(lt) # Modifying element named 'a'lt <- within(lt, rm(a)) cat("List after deleting:\n")print(lt) Output: List before deleting: $a [1] 1 $let [1] "a" "b" "c" "d" "e" "f" "g" "h" $mt [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 List after deleting: $let [1] "a" "b" "c" "d" "e" "f" "g" "h" $mt [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 Picked R-List R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Group by function in R using Dplyr How to Change Axis Scales in R Plots? Printing Output of an R Program How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming
[ { "code": null, "e": 26451, "s": 26423, "text": "\n22 Jun, 2020" }, { "code": null, "e": 27020, "s": 26451, "text": "A list is an object in R Language which consists of heterogeneous elements. A list can even contain matrices, data frames, or functions as its elements. The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them. Named list can also be created using names() function to specify the names of elements after defining the list. In this article, we’ll learn to create named list in R using two different methods and different operations that can be performed on named lists." }, { "code": null, "e": 27046, "s": 27020, "text": "Syntax: names(x) <- value" }, { "code": null, "e": 27151, "s": 27046, "text": "Parameters:x: represents an R objectvalue: represents names that has to be given to elements of x object" }, { "code": null, "e": 27325, "s": 27151, "text": "A Named list can be created by two methods. The first one is by allocating the names to the elements while defining the list and another method is by using names() function." }, { "code": null, "e": 27420, "s": 27325, "text": "Example 1:In this example, we are going to create a named list without using names() function." }, { "code": "# Defining a list with namesx <- list(mt = matrix(1:6, nrow = 2), lt = letters[1:8], n = c(1:10)) # Print whole listcat(\"Whole List:\\n\")print(x)", "e": 27584, "s": 27420, "text": null }, { "code": null, "e": 27592, "s": 27584, "text": "Output:" }, { "code": null, "e": 27749, "s": 27592, "text": "Whole List:\n$mt\n [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n\n$lt\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\"\n\n$n\n [1] 1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 27881, "s": 27749, "text": "Example 2:In this example, we are going to define the names of elements of the list using names() function after defining the list." }, { "code": "# Defining listx <- list(matrix(1:6, nrow = 2), letters[1:8], c(1:10)) # Print whole listcat(\"Whole list:\\n\")print(x)", "e": 28018, "s": 27881, "text": null }, { "code": null, "e": 28026, "s": 28018, "text": "Output:" }, { "code": null, "e": 28190, "s": 28026, "text": "Whole list:\n[[1]]\n [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n\n[[2]]\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\"\n\n[[3]]\n [1] 1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 28255, "s": 28190, "text": "Components of a named list can be easily accessed by $ operator." }, { "code": null, "e": 28264, "s": 28255, "text": "Example:" }, { "code": "# Defining a list with namesx <- list(mt = matrix(1:6, nrow = 2), lt = letters[1:8], n = c(1:10)) # Print list elements using the names given# Prints element of the list named \"mt\"cat(\"Element named 'mt':\\n\")print(x$mt)cat(\"\\n\") # Print element of the list named \"n\"cat(\"Element named 'n':\\n\")print(x$n)", "e": 28588, "s": 28264, "text": null }, { "code": null, "e": 28596, "s": 28588, "text": "Output:" }, { "code": null, "e": 28732, "s": 28596, "text": "Element named 'mt':\n [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n\nElement named 'n':\n [1] 1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 28806, "s": 28732, "text": "Components of named list can be modified by assigning new values to them." }, { "code": null, "e": 28815, "s": 28806, "text": "Example:" }, { "code": "# Defining a named listlt <- list(a = 1, let = letters[1:8], mt = matrix(1:6, nrow = 2)) cat(\"List before modifying:\\n\")print(lt) # Modifying element named 'a'lt$a <- 5 cat(\"List after modifying:\\n\")print(lt)", "e": 29047, "s": 28815, "text": null }, { "code": null, "e": 29055, "s": 29047, "text": "Output:" }, { "code": null, "e": 29334, "s": 29055, "text": "List before modifying:\n$a\n[1] 1\n\n$let\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\"\n\n$mt\n [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n\nList after modifying:\n$a\n[1] 5\n\n$let\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\"\n\n$mt\n [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n" }, { "code": null, "e": 29456, "s": 29334, "text": "To delete elements from named list, we’ll use within() function and the result will be assigned to the named list itself." }, { "code": null, "e": 29465, "s": 29456, "text": "Example:" }, { "code": "# Defining a named listlt <- list(a = 1, let = letters[1:8], mt = matrix(1:6, nrow = 2)) cat(\"List before deleting:\\n\")print(lt) # Modifying element named 'a'lt <- within(lt, rm(a)) cat(\"List after deleting:\\n\")print(lt)", "e": 29709, "s": 29465, "text": null }, { "code": null, "e": 29717, "s": 29709, "text": "Output:" }, { "code": null, "e": 29984, "s": 29717, "text": "List before deleting:\n$a\n[1] 1\n\n$let\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\"\n\n$mt\n [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n\nList after deleting:\n$let\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\"\n\n$mt\n [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n" }, { "code": null, "e": 29991, "s": 29984, "text": "Picked" }, { "code": null, "e": 29998, "s": 29991, "text": "R-List" }, { "code": null, "e": 30009, "s": 29998, "text": "R Language" }, { "code": null, "e": 30107, "s": 30009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30165, "s": 30107, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 30217, "s": 30165, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 30249, "s": 30217, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 30301, "s": 30249, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30345, "s": 30301, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 30380, "s": 30345, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30418, "s": 30380, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30450, "s": 30418, "text": "Printing Output of an R Program" }, { "code": null, "e": 30508, "s": 30450, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
An Ultimate Guide to Git and Github - GeeksforGeeks
02 Mar, 2021 Highlights of the article: Introduction to GitGit Repository StructureAccessing github central repository via Https or sshWorking with git – Important Git commands Introduction to Git Git Repository Structure Accessing github central repository via Https or ssh Working with git – Important Git commands Introduction to Git For installation purposes on ubuntu, you can refer this article : https://www.geeksforgeeks.org/how-to-install-configure-and-use-git-on-ubuntu/ Git is a distributed version control system. So, What is a Version Control System?A version Control system is a system that maintains different versions of your project when we work in a team or as an individual. (system managing changes to files) As the project progresses, new features get added to it. So,a version control system maintains all your different versions of your project for you and you can rollback to any version you want without causing any trouble to you for maintaining different versions by giving names to it like MyProject, MyProjectWithFeature1, etc. Distributed Version control system means every collaborator(any developer working on a team project)has a local repository of the project in his/her local machine unlike central where team members should have an internet connection to every time update their work to the main central repository. So, by distributed we mean: the project is distributed.A repository is an area that keeps all your project files, images, etc. In terms of Github: different versions of projects correspond to commits.For more details on introduction to Github you can refer : https://www.geeksforgeeks.org/git-lets-get-into-it/ Git Repository Structure It consists of 4 parts: Working directory : This is your local directory where you make the project (write code) and make changes to it.Staging Area (or index) : this is an area where you first need to put your project before committing. This is used for code review by other team members.Local Repository : this is your local repository where you commit changes to theproject before pushing them to central repository on Github. This is what is provided by distributed version control system. This corresponds to the .git folder in our directory.Central Repository : This is the main project on the central server, a copy of whichis with every team member as local repository. Working directory : This is your local directory where you make the project (write code) and make changes to it. Staging Area (or index) : this is an area where you first need to put your project before committing. This is used for code review by other team members. Local Repository : this is your local repository where you commit changes to theproject before pushing them to central repository on Github. This is what is provided by distributed version control system. This corresponds to the .git folder in our directory. Central Repository : This is the main project on the central server, a copy of whichis with every team member as local repository. All the repository structure is internal to Git and is transparent to the developer. Some commands which relate to repository structure: git add // transfers your project from working directory // to staging area. git commit // transfers your project from staging area to // Local Repository. git push // transfers project from local to central repository. // (requires internet) Accessing github central repository via Https or ssh Here, transfer project means transfer changes as git is very lightweight and works on changes in a project. It internally does the transfer by using Lossless Compression Techniques and transferring compressed files. Https is the default way to access Github central repository. by git remote add origin http_url : remote means the remote central repository. origin corresponds to your central repository which you need to define (hereby giving https URL) in order to push changes to Github. Via SSH: connect to Linux or other servers remotely. If you access Github by ssh you don’t need to type your username and password every time you push changes to GitHub. Terminal commands : ssh-keygen -t rsa -b 4096 -C "[email protected]" This does the ssh key generation using RSA cryptographic algorithm. eval "$(ssh-agent -s)" -> enable information about local login session. ssh-add ~/.ssh/id_rsa -> add to ssh key. cat ~/.ssh/id_rsa (use .pub file if not able to connect) add this ssh key to github. Now, go to github settings -> new ssh key -> create key ssh -T [email protected] -> activate ssh key (test connection) Refresh your github Page. Working with git – Important Git commands Git user configuration (First Step)git --version (to check git version) git config --global user.name "your name here" git config --global user.email "your email here"These are the information attached to commits. git --version (to check git version) git config --global user.name "your name here" git config --global user.email "your email here" These are the information attached to commits. Initialize directory :git init initializes your directory to work with git and makes a local repository. .git folder is madeORgit clone http_url This is done if we have an existing git repository. git init initializes your directory to work with git and makes a local repository. .git folder is made OR git clone http_url This is done if we have an existing git repository. Connecting to repository :git remote add origin http_url/ssh_url connect to central repo to push/pullpull means transferring the changes on the central repository to your local repository. push is the vice versa of pull.git pull origin masterAlways first pull contents from the central repo before pushing so that you are updated with other team members’ work.Here, master means the master branch (in Git). git remote add origin http_url/ssh_url connect to central repo to push/pull pull means transferring the changes on the central repository to your local repository. push is the vice versa of pull. git pull origin master Always first pull contents from the central repo before pushing so that you are updated with other team members’ work.Here, master means the master branch (in Git). Steps to add a file to central Repository:First, your file is in your working directory, Move it to the staging area by typing:git add -A (for all files and folders) #To add all files only in the current directory git add . git status: here, untracked files mean files that you haven’t added to the staging area. Changes are not staged for commit means you have staged the file earlier then you have made changes in that files in your working directory and the changes need to be staged once more.Changes ready to be committed: these are files that have been committed and ready to be pushed to the central repository.git commit -a -m "message for commit" -a: commit all files and for files that have been staged earlier need not to be git add once more -a option does that automatically.git push origin master -> pushes your files to github master branch git push origin anyOtherBranch -> pushes any other branch to github. git log ; to see all your commitsgit checkout commitObject(first 8 bits) file.txt-> revert back to this previous commit for file file.txtcommitObject can be seen via git log.HEAD -> pointer to our latest commit. git add -A (for all files and folders) #To add all files only in the current directory git add . git status: here, untracked files mean files that you haven’t added to the staging area. Changes are not staged for commit means you have staged the file earlier then you have made changes in that files in your working directory and the changes need to be staged once more.Changes ready to be committed: these are files that have been committed and ready to be pushed to the central repository. git commit -a -m "message for commit" -a: commit all files and for files that have been staged earlier need not to be git add once more -a option does that automatically. git push origin master -> pushes your files to github master branch git push origin anyOtherBranch -> pushes any other branch to github. git log ; to see all your commits git checkout commitObject(first 8 bits) file.txt-> revert back to this previous commit for file file.txt commitObject can be seen via git log. HEAD -> pointer to our latest commit. Ignoring files while committing.In many cases, the project creates a lot of log and other irrelevant files which are to be ignored.So to ignore those files, we have to put their names in“.gitignore” file.touch .gitignore echo "filename.ext" >>.gitignore #to ignore all files with .log extension echo "*.log" > .gitignore Now the filenames written in the .gitignore file would be ignored while pushing a new commit. touch .gitignore echo "filename.ext" >>.gitignore #to ignore all files with .log extension echo "*.log" > .gitignore Now the filenames written in the .gitignore file would be ignored while pushing a new commit. To get the changes between commits, commit and working tree.git diff‘git diff’ command compares staging area with the working directory and tells us the changes made. It compares the earlier information as well as the current modified information. git diff ‘git diff’ command compares staging area with the working directory and tells us the changes made. It compares the earlier information as well as the current modified information. Branching in Git create branch -> git branch myBranch or git checkout -b myBranch -> make and switch to the branch myBranch Do the work in your branch. Then, git checkout master ; to switch back to master branch Now,merge contents with your myBranch By: git merge myBranch (writing in master branch) This merger makes a new commit. Another way: git rebase myBranch This merges the branch with master in a serial fashion. Now, git push origin master Contributing to open source by fork a project and do some work (add new features) in your branch and then do a pull request on Github. Sushant Oberoi khu5h1 GitHub GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Supervised and Unsupervised learning Introduction to Recurrent Neural Network Top 10 System Design Interview Questions and Answers 12 pip Commands For Python Developers Working with PDF files in Python A Freshers Guide To Programming ML | Underfitting and Overfitting
[ { "code": null, "e": 25975, "s": 25947, "text": "\n02 Mar, 2021" }, { "code": null, "e": 26002, "s": 25975, "text": "Highlights of the article:" }, { "code": null, "e": 26139, "s": 26002, "text": "Introduction to GitGit Repository StructureAccessing github central repository via Https or sshWorking with git – Important Git commands" }, { "code": null, "e": 26159, "s": 26139, "text": "Introduction to Git" }, { "code": null, "e": 26184, "s": 26159, "text": "Git Repository Structure" }, { "code": null, "e": 26237, "s": 26184, "text": "Accessing github central repository via Https or ssh" }, { "code": null, "e": 26279, "s": 26237, "text": "Working with git – Important Git commands" }, { "code": null, "e": 26299, "s": 26279, "text": "Introduction to Git" }, { "code": null, "e": 26443, "s": 26299, "text": "For installation purposes on ubuntu, you can refer this article : https://www.geeksforgeeks.org/how-to-install-configure-and-use-git-on-ubuntu/" }, { "code": null, "e": 27019, "s": 26443, "text": "Git is a distributed version control system. So, What is a Version Control System?A version Control system is a system that maintains different versions of your project when we work in a team or as an individual. (system managing changes to files) As the project progresses, new features get added to it. So,a version control system maintains all your different versions of your project for you and you can rollback to any version you want without causing any trouble to you for maintaining different versions by giving names to it like MyProject, MyProjectWithFeature1, etc." }, { "code": null, "e": 27315, "s": 27019, "text": "Distributed Version control system means every collaborator(any developer working on a team project)has a local repository of the project in his/her local machine unlike central where team members should have an internet connection to every time update their work to the main central repository." }, { "code": null, "e": 27442, "s": 27315, "text": "So, by distributed we mean: the project is distributed.A repository is an area that keeps all your project files, images, etc." }, { "code": null, "e": 27626, "s": 27442, "text": "In terms of Github: different versions of projects correspond to commits.For more details on introduction to Github you can refer : https://www.geeksforgeeks.org/git-lets-get-into-it/" }, { "code": null, "e": 27651, "s": 27626, "text": "Git Repository Structure" }, { "code": null, "e": 27675, "s": 27651, "text": "It consists of 4 parts:" }, { "code": null, "e": 28329, "s": 27675, "text": "Working directory : This is your local directory where you make the project (write code) and make changes to it.Staging Area (or index) : this is an area where you first need to put your project before committing. This is used for code review by other team members.Local Repository : this is your local repository where you commit changes to theproject before pushing them to central repository on Github. This is what is provided by distributed version control system. This corresponds to the .git folder in our directory.Central Repository : This is the main project on the central server, a copy of whichis with every team member as local repository." }, { "code": null, "e": 28442, "s": 28329, "text": "Working directory : This is your local directory where you make the project (write code) and make changes to it." }, { "code": null, "e": 28596, "s": 28442, "text": "Staging Area (or index) : this is an area where you first need to put your project before committing. This is used for code review by other team members." }, { "code": null, "e": 28855, "s": 28596, "text": "Local Repository : this is your local repository where you commit changes to theproject before pushing them to central repository on Github. This is what is provided by distributed version control system. This corresponds to the .git folder in our directory." }, { "code": null, "e": 28986, "s": 28855, "text": "Central Repository : This is the main project on the central server, a copy of whichis with every team member as local repository." }, { "code": null, "e": 29071, "s": 28986, "text": "All the repository structure is internal to Git and is transparent to the developer." }, { "code": null, "e": 29123, "s": 29071, "text": "Some commands which relate to repository structure:" }, { "code": null, "e": 29372, "s": 29123, "text": "git add \n// transfers your project from working directory\n// to staging area.\n\ngit commit \n// transfers your project from staging area to \n// Local Repository.\n\ngit push\n// transfers project from local to central repository.\n// (requires internet)\n" }, { "code": null, "e": 29425, "s": 29372, "text": "Accessing github central repository via Https or ssh" }, { "code": null, "e": 29703, "s": 29425, "text": "Here, transfer project means transfer changes as git is very lightweight and works on changes in a project. It internally does the transfer by using Lossless Compression Techniques and transferring compressed files. Https is the default way to access Github central repository." }, { "code": null, "e": 29972, "s": 29703, "text": "by git remote add origin http_url :\nremote means the remote central repository.\norigin corresponds to your central repository\nwhich you need to define (hereby giving https URL) \nin order to push changes to Github.\n\nVia SSH: connect to Linux or other servers remotely.\n" }, { "code": null, "e": 30089, "s": 29972, "text": "If you access Github by ssh you don’t need to type your username and password every time you push changes to GitHub." }, { "code": null, "e": 30109, "s": 30089, "text": "Terminal commands :" }, { "code": null, "e": 30577, "s": 30109, "text": "ssh-keygen -t rsa -b 4096 -C \"[email protected]\"\nThis does the ssh key generation using RSA cryptographic algorithm.\n\neval \"$(ssh-agent -s)\" -> enable information about local login session.\n\nssh-add ~/.ssh/id_rsa -> add to ssh key.\ncat ~/.ssh/id_rsa (use .pub file if not able to connect)\nadd this ssh key to github.\n\nNow, go to github settings -> new ssh key -> create key\n\nssh -T [email protected] -> activate ssh key (test connection)\n\nRefresh your github Page.\n" }, { "code": null, "e": 30619, "s": 30577, "text": "Working with git – Important Git commands" }, { "code": null, "e": 30833, "s": 30619, "text": "Git user configuration (First Step)git --version (to check git version)\ngit config --global user.name \"your name here\"\ngit config --global user.email \"your email here\"These are the information attached to commits." }, { "code": null, "e": 30966, "s": 30833, "text": "git --version (to check git version)\ngit config --global user.name \"your name here\"\ngit config --global user.email \"your email here\"" }, { "code": null, "e": 31013, "s": 30966, "text": "These are the information attached to commits." }, { "code": null, "e": 31212, "s": 31013, "text": "Initialize directory :git init \ninitializes your directory to work with git and\nmakes a local repository. .git folder is madeORgit clone http_url \nThis is done if we have an existing git repository." }, { "code": null, "e": 31316, "s": 31212, "text": "git init \ninitializes your directory to work with git and\nmakes a local repository. .git folder is made" }, { "code": null, "e": 31319, "s": 31316, "text": "OR" }, { "code": null, "e": 31391, "s": 31319, "text": "git clone http_url \nThis is done if we have an existing git repository." }, { "code": null, "e": 31799, "s": 31391, "text": "Connecting to repository :git remote add origin http_url/ssh_url \nconnect to central repo to push/pullpull means transferring the changes on the central repository to your local repository. push is the vice versa of pull.git pull origin masterAlways first pull contents from the central repo before pushing so that you are updated with other team members’ work.Here, master means the master branch (in Git)." }, { "code": null, "e": 31876, "s": 31799, "text": "git remote add origin http_url/ssh_url \nconnect to central repo to push/pull" }, { "code": null, "e": 31996, "s": 31876, "text": "pull means transferring the changes on the central repository to your local repository. push is the vice versa of pull." }, { "code": null, "e": 32019, "s": 31996, "text": "git pull origin master" }, { "code": null, "e": 32184, "s": 32019, "text": "Always first pull contents from the central repo before pushing so that you are updated with other team members’ work.Here, master means the master branch (in Git)." }, { "code": null, "e": 33378, "s": 32184, "text": "Steps to add a file to central Repository:First, your file is in your working directory, Move it to the staging area by typing:git add -A (for all files and folders)\n#To add all files only in the current directory\ngit add .\ngit status: here, untracked files mean files that you haven’t added to the staging area. Changes are not staged for commit means you have staged the file earlier then you have made changes in that files in your working directory and the changes need to be staged once more.Changes ready to be committed: these are files that have been committed and ready to be pushed to the central repository.git commit -a -m \"message for commit\"\n-a: commit all files and for files that have been \n staged earlier need not to be git add once more\n-a option does that automatically.git push origin master -> pushes your files to \n github master branch\ngit push origin anyOtherBranch -> pushes any \n other branch to github.\ngit log ; to see all your commitsgit checkout commitObject(first 8 bits) file.txt-> \nrevert back to this previous commit for file file.txtcommitObject can be seen via git log.HEAD -> pointer to our latest commit." }, { "code": null, "e": 33476, "s": 33378, "text": "git add -A (for all files and folders)\n#To add all files only in the current directory\ngit add .\n" }, { "code": null, "e": 33871, "s": 33476, "text": "git status: here, untracked files mean files that you haven’t added to the staging area. Changes are not staged for commit means you have staged the file earlier then you have made changes in that files in your working directory and the changes need to be staged once more.Changes ready to be committed: these are files that have been committed and ready to be pushed to the central repository." }, { "code": null, "e": 34048, "s": 33871, "text": "git commit -a -m \"message for commit\"\n-a: commit all files and for files that have been \n staged earlier need not to be git add once more\n-a option does that automatically." }, { "code": null, "e": 34268, "s": 34048, "text": "git push origin master -> pushes your files to \n github master branch\ngit push origin anyOtherBranch -> pushes any \n other branch to github.\ngit log ; to see all your commits" }, { "code": null, "e": 34375, "s": 34268, "text": "git checkout commitObject(first 8 bits) file.txt-> \nrevert back to this previous commit for file file.txt" }, { "code": null, "e": 34413, "s": 34375, "text": "commitObject can be seen via git log." }, { "code": null, "e": 34451, "s": 34413, "text": "HEAD -> pointer to our latest commit." }, { "code": null, "e": 34866, "s": 34451, "text": "Ignoring files while committing.In many cases, the project creates a lot of log and other irrelevant files which are to be ignored.So to ignore those files, we have to put their names in“.gitignore” file.touch .gitignore\necho \"filename.ext\" >>.gitignore\n#to ignore all files with .log extension\necho \"*.log\" > .gitignore\nNow the filenames written in the .gitignore file would be ignored while pushing a new commit." }, { "code": null, "e": 34984, "s": 34866, "text": "touch .gitignore\necho \"filename.ext\" >>.gitignore\n#to ignore all files with .log extension\necho \"*.log\" > .gitignore\n" }, { "code": null, "e": 35078, "s": 34984, "text": "Now the filenames written in the .gitignore file would be ignored while pushing a new commit." }, { "code": null, "e": 35326, "s": 35078, "text": "To get the changes between commits, commit and working tree.git diff‘git diff’ command compares staging area with the working directory and tells us the changes made. It compares the earlier information as well as the current modified information." }, { "code": null, "e": 35335, "s": 35326, "text": "git diff" }, { "code": null, "e": 35515, "s": 35335, "text": "‘git diff’ command compares staging area with the working directory and tells us the changes made. It compares the earlier information as well as the current modified information." }, { "code": null, "e": 35532, "s": 35515, "text": "Branching in Git" }, { "code": null, "e": 35674, "s": 35532, "text": "create branch ->\ngit branch myBranch\nor\ngit checkout -b myBranch -> make and switch to the \n branch myBranch" }, { "code": null, "e": 35702, "s": 35674, "text": "Do the work in your branch." }, { "code": null, "e": 35708, "s": 35702, "text": "Then," }, { "code": null, "e": 35762, "s": 35708, "text": "git checkout master ; to switch back to master branch" }, { "code": null, "e": 35804, "s": 35762, "text": "Now,merge contents with your myBranch By:" }, { "code": null, "e": 35850, "s": 35804, "text": "git merge myBranch (writing in master branch)" }, { "code": null, "e": 35882, "s": 35850, "text": "This merger makes a new commit." }, { "code": null, "e": 35895, "s": 35882, "text": "Another way:" }, { "code": null, "e": 35915, "s": 35895, "text": "git rebase myBranch" }, { "code": null, "e": 35971, "s": 35915, "text": "This merges the branch with master in a serial fashion." }, { "code": null, "e": 35976, "s": 35971, "text": "Now," }, { "code": null, "e": 35999, "s": 35976, "text": "git push origin master" }, { "code": null, "e": 36134, "s": 35999, "text": "Contributing to open source by fork a project and do some work (add new features) in your branch and then do a pull request on Github." }, { "code": null, "e": 36149, "s": 36134, "text": "Sushant Oberoi" }, { "code": null, "e": 36156, "s": 36149, "text": "khu5h1" }, { "code": null, "e": 36163, "s": 36156, "text": "GitHub" }, { "code": null, "e": 36169, "s": 36163, "text": "GBlog" }, { "code": null, "e": 36267, "s": 36169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36292, "s": 36267, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 36319, "s": 36292, "text": "How to Start Learning DSA?" }, { "code": null, "e": 36356, "s": 36319, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 36397, "s": 36356, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 36450, "s": 36397, "text": "Top 10 System Design Interview Questions and Answers" }, { "code": null, "e": 36488, "s": 36450, "text": "12 pip Commands For Python Developers" }, { "code": null, "e": 36521, "s": 36488, "text": "Working with PDF files in Python" }, { "code": null, "e": 36553, "s": 36521, "text": "A Freshers Guide To Programming" } ]
p5.js | torus() Function - GeeksforGeeks
22 Apr, 2019 The torus() function in p5.js is used to draw a torus with given torus radius and tube radius. Syntax: torus( radius, tubeRadius, detailX, detailY ) Parameters: This function accepts four parameters as mentioned above and described below: radius: This parameter stores the radius of the torus. tubeRadius: This parameter stores the radius of the tube. detailX: This parameter stores the number of segments in x-dimension. detailY: This parameter stores the number of segments in y-dimension.Below programs illustrate the torus() function in p5.js:Example 1: This example uses torus() function to draw a torus with given torus radius and tube radius.function setup() { // Create Canvas of size 600*600 createCanvas(600, 600, WEBGL);} function draw() { // Set background color background(200); // Set fill color of torus fill('green'); // Call to torus function torus(90, 35, 12, 12);}Output:Example 2: This example uses torus() function to draw a torus with given torus radius and tube radius.function setup() { // Create Canvas of size 600*600 createCanvas(600, 600, WEBGL);} function draw() { // Set background color background(200); // Set fill color of torus fill('yellow'); // Rotate rotateX(frameCount * 0.01); rotate(frameCount*0.05); // Call to torus function torus(90, 35);}Output:Reference: https://p5js.org/reference/#/p5/torusMy Personal Notes arrow_drop_upSave Below programs illustrate the torus() function in p5.js: Example 1: This example uses torus() function to draw a torus with given torus radius and tube radius. function setup() { // Create Canvas of size 600*600 createCanvas(600, 600, WEBGL);} function draw() { // Set background color background(200); // Set fill color of torus fill('green'); // Call to torus function torus(90, 35, 12, 12);} Output: Example 2: This example uses torus() function to draw a torus with given torus radius and tube radius. function setup() { // Create Canvas of size 600*600 createCanvas(600, 600, WEBGL);} function draw() { // Set background color background(200); // Set fill color of torus fill('yellow'); // Rotate rotateX(frameCount * 0.01); rotate(frameCount*0.05); // Call to torus function torus(90, 35);} Output:Reference: https://p5js.org/reference/#/p5/torus JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26627, "s": 26599, "text": "\n22 Apr, 2019" }, { "code": null, "e": 26722, "s": 26627, "text": "The torus() function in p5.js is used to draw a torus with given torus radius and tube radius." }, { "code": null, "e": 26730, "s": 26722, "text": "Syntax:" }, { "code": null, "e": 26776, "s": 26730, "text": "torus( radius, tubeRadius, detailX, detailY )" }, { "code": null, "e": 26866, "s": 26776, "text": "Parameters: This function accepts four parameters as mentioned above and described below:" }, { "code": null, "e": 26921, "s": 26866, "text": "radius: This parameter stores the radius of the torus." }, { "code": null, "e": 26979, "s": 26921, "text": "tubeRadius: This parameter stores the radius of the tube." }, { "code": null, "e": 27049, "s": 26979, "text": "detailX: This parameter stores the number of segments in x-dimension." }, { "code": null, "e": 28111, "s": 27049, "text": "detailY: This parameter stores the number of segments in y-dimension.Below programs illustrate the torus() function in p5.js:Example 1: This example uses torus() function to draw a torus with given torus radius and tube radius.function setup() { // Create Canvas of size 600*600 createCanvas(600, 600, WEBGL);} function draw() { // Set background color background(200); // Set fill color of torus fill('green'); // Call to torus function torus(90, 35, 12, 12);}Output:Example 2: This example uses torus() function to draw a torus with given torus radius and tube radius.function setup() { // Create Canvas of size 600*600 createCanvas(600, 600, WEBGL);} function draw() { // Set background color background(200); // Set fill color of torus fill('yellow'); // Rotate rotateX(frameCount * 0.01); rotate(frameCount*0.05); // Call to torus function torus(90, 35);}Output:Reference: https://p5js.org/reference/#/p5/torusMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28168, "s": 28111, "text": "Below programs illustrate the torus() function in p5.js:" }, { "code": null, "e": 28271, "s": 28168, "text": "Example 1: This example uses torus() function to draw a torus with given torus radius and tube radius." }, { "code": "function setup() { // Create Canvas of size 600*600 createCanvas(600, 600, WEBGL);} function draw() { // Set background color background(200); // Set fill color of torus fill('green'); // Call to torus function torus(90, 35, 12, 12);}", "e": 28554, "s": 28271, "text": null }, { "code": null, "e": 28562, "s": 28554, "text": "Output:" }, { "code": null, "e": 28665, "s": 28562, "text": "Example 2: This example uses torus() function to draw a torus with given torus radius and tube radius." }, { "code": "function setup() { // Create Canvas of size 600*600 createCanvas(600, 600, WEBGL);} function draw() { // Set background color background(200); // Set fill color of torus fill('yellow'); // Rotate rotateX(frameCount * 0.01); rotate(frameCount*0.05); // Call to torus function torus(90, 35);}", "e": 29019, "s": 28665, "text": null }, { "code": null, "e": 29075, "s": 29019, "text": "Output:Reference: https://p5js.org/reference/#/p5/torus" }, { "code": null, "e": 29092, "s": 29075, "text": "JavaScript-p5.js" }, { "code": null, "e": 29103, "s": 29092, "text": "JavaScript" }, { "code": null, "e": 29120, "s": 29103, "text": "Web Technologies" }, { "code": null, "e": 29218, "s": 29120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29258, "s": 29218, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29319, "s": 29258, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29360, "s": 29319, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29382, "s": 29360, "text": "JavaScript | Promises" }, { "code": null, "e": 29436, "s": 29382, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29476, "s": 29436, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29509, "s": 29476, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29552, "s": 29509, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29614, "s": 29552, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Python | Convert dictionary to list of tuples - GeeksforGeeks
08 Jul, 2021 Given a dictionary, write a Python program to convert the given dictionary into list of tuples.Examples: Input: { 'Geeks': 10, 'for': 12, 'Geek': 31 } Output : [ ('Geeks', 10), ('for', 12), ('Geek', 31) ] Input: { 'dict': 11, 'to': 22, 'list_of_tup': 33} Output : [ ('dict', 11), ('to', 22), ('list_of_tup', 33) ] Below are various methods to convert dictionary to list of tuples.Method #1 : Using list comprehension Python3 # Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Converting into list of tuplelist = [(k, v) for k, v in dict.items()] # Printing list of tupleprint(list) [('Geek', 31), ('for', 12), ('Geeks', 10)] Method #2 : Using items() Python3 # Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Converting into list of tuplelist = list(dict.items()) # Printing list of tupleprint(list) [('for', 12), ('Geeks', 10), ('Geek', 31)] Method #3 : Using zip Python3 # Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Using ziplist = zip(dict.keys(), dict.values()) # Converting from zip object to list objectlist = list(list) # Printing listprint(list) [('Geek', 31), ('Geeks', 10), ('for', 12)] Method #4 : Using iteration Python3 # Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Initialization of empty listlist = [] # Iterationfor i in dict: k = (i, dict[i]) list.append(k) # Printing listprint(list) [('Geeks', 10), ('for', 12), ('Geek', 31)] Method #5 : Using collection Python3 # Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Importingimport collections # Convertinglist_of_tuple = collections.namedtuple('List', 'name value') lists = list(list_of_tuple(*item) for item in dict.items()) # Printing listprint(lists) [List(name=’for’, value=12), List(name=’Geek’, value=31), List(name=’Geeks’, value=10)] akshaysingh98088 Python dictionary-programs python-dict Python Python Programs python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26179, "s": 26151, "text": "\n08 Jul, 2021" }, { "code": null, "e": 26286, "s": 26179, "text": "Given a dictionary, write a Python program to convert the given dictionary into list of tuples.Examples: " }, { "code": null, "e": 26496, "s": 26286, "text": "Input: { 'Geeks': 10, 'for': 12, 'Geek': 31 }\nOutput : [ ('Geeks', 10), ('for', 12), ('Geek', 31) ]\n\nInput: { 'dict': 11, 'to': 22, 'list_of_tup': 33}\nOutput : [ ('dict', 11), ('to', 22), ('list_of_tup', 33) ]" }, { "code": null, "e": 26601, "s": 26496, "text": "Below are various methods to convert dictionary to list of tuples.Method #1 : Using list comprehension " }, { "code": null, "e": 26609, "s": 26601, "text": "Python3" }, { "code": "# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Converting into list of tuplelist = [(k, v) for k, v in dict.items()] # Printing list of tupleprint(list)", "e": 26849, "s": 26609, "text": null }, { "code": null, "e": 26892, "s": 26849, "text": "[('Geek', 31), ('for', 12), ('Geeks', 10)]" }, { "code": null, "e": 26924, "s": 26894, "text": " Method #2 : Using items() " }, { "code": null, "e": 26932, "s": 26924, "text": "Python3" }, { "code": "# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Converting into list of tuplelist = list(dict.items()) # Printing list of tupleprint(list)", "e": 27157, "s": 26932, "text": null }, { "code": null, "e": 27200, "s": 27157, "text": "[('for', 12), ('Geeks', 10), ('Geek', 31)]" }, { "code": null, "e": 27228, "s": 27202, "text": " Method #3 : Using zip " }, { "code": null, "e": 27236, "s": 27228, "text": "Python3" }, { "code": "# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Using ziplist = zip(dict.keys(), dict.values()) # Converting from zip object to list objectlist = list(list) # Printing listprint(list)", "e": 27506, "s": 27236, "text": null }, { "code": null, "e": 27549, "s": 27506, "text": "[('Geek', 31), ('Geeks', 10), ('for', 12)]" }, { "code": null, "e": 27583, "s": 27551, "text": " Method #4 : Using iteration " }, { "code": null, "e": 27591, "s": 27583, "text": "Python3" }, { "code": "# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Initialization of empty listlist = [] # Iterationfor i in dict: k = (i, dict[i]) list.append(k) # Printing listprint(list)", "e": 27852, "s": 27591, "text": null }, { "code": null, "e": 27895, "s": 27852, "text": "[('Geeks', 10), ('for', 12), ('Geek', 31)]" }, { "code": null, "e": 27930, "s": 27897, "text": " Method #5 : Using collection " }, { "code": null, "e": 27938, "s": 27930, "text": "Python3" }, { "code": "# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Importingimport collections # Convertinglist_of_tuple = collections.namedtuple('List', 'name value') lists = list(list_of_tuple(*item) for item in dict.items()) # Printing listprint(lists)", "e": 28261, "s": 27938, "text": null }, { "code": null, "e": 28350, "s": 28261, "text": "[List(name=’for’, value=12), List(name=’Geek’, value=31), List(name=’Geeks’, value=10)] " }, { "code": null, "e": 28369, "s": 28352, "text": "akshaysingh98088" }, { "code": null, "e": 28396, "s": 28369, "text": "Python dictionary-programs" }, { "code": null, "e": 28408, "s": 28396, "text": "python-dict" }, { "code": null, "e": 28415, "s": 28408, "text": "Python" }, { "code": null, "e": 28431, "s": 28415, "text": "Python Programs" }, { "code": null, "e": 28443, "s": 28431, "text": "python-dict" }, { "code": null, "e": 28541, "s": 28443, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28559, "s": 28541, "text": "Python Dictionary" }, { "code": null, "e": 28594, "s": 28559, "text": "Read a file line by line in Python" }, { "code": null, "e": 28626, "s": 28594, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28648, "s": 28626, "text": "Enumerate() in Python" }, { "code": null, "e": 28690, "s": 28648, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28733, "s": 28690, "text": "Python program to convert a list to string" }, { "code": null, "e": 28755, "s": 28733, "text": "Defaultdict in Python" }, { "code": null, "e": 28794, "s": 28755, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28840, "s": 28794, "text": "Python | Split string into list of characters" } ]
Sort a linked list of 0s, 1s and 2s - GeeksforGeeks
17 Jan, 2022 Given a linked list of 0s, 1s and 2s, sort it.Examples: Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULLInput: 1 -> 1 -> 2 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL Source: Microsoft Interview | Set 1 Following steps can be used to sort the given linked list. Traverse the list and count the number of 0s, 1s, and 2s. Let the counts be n1, n2, and n3 respectively. Traverse the list again, fill the first n1 nodes with 0, then n2 nodes with 1, and finally n3 nodes with 2. Below image is a dry run of the above approach: Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ Program to sort a linked list 0s, 1s or 2s#include <bits/stdc++.h>using namespace std; /* Link list node */class Node{ public: int data; Node* next;}; // Function to sort a linked list of 0s, 1s and 2svoid sortList(Node *head){ int count[3] = {0, 0, 0}; // Initialize count of '0', '1' and '2' as 0 Node *ptr = head; /* count total number of '0', '1' and '2' * count[0] will store total number of '0's * count[1] will store total number of '1's * count[2] will store total number of '2's */ while (ptr != NULL) { count[ptr->data] += 1; ptr = ptr->next; } int i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 * now start traversing list from head node, * 1) fill the list with 0, till n1 > 0 * 2) fill the list with 1, till n2 > 0 * 3) fill the list with 2, till n3 > 0 */ while (ptr != NULL) { if (count[i] == 0) ++i; else { ptr->data = i; --count[i]; ptr = ptr->next; } }} /* Function to push a node */void push (Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(Node *node){ while (node != NULL) { cout << node->data << " "; node = node->next; } cout << endl;} /* Driver code*/int main(void){ Node *head = NULL; push(&head, 0); push(&head, 1); push(&head, 0); push(&head, 2); push(&head, 1); push(&head, 1); push(&head, 2); push(&head, 1); push(&head, 2); cout << "Linked List Before Sorting\n"; printList(head); sortList(head); cout << "Linked List After Sorting\n"; printList(head); return 0;} // This code is contributed by rathbhupendra // C Program to sort a linked list 0s, 1s or 2s#include<stdio.h>#include<stdlib.h> /* Link list node */struct Node{ int data; struct Node* next;}; // Function to sort a linked list of 0s, 1s and 2svoid sortList(struct Node *head){ int count[3] = {0, 0, 0}; // Initialize count of '0', '1' and '2' as 0 struct Node *ptr = head; /* count total number of '0', '1' and '2' * count[0] will store total number of '0's * count[1] will store total number of '1's * count[2] will store total number of '2's */ while (ptr != NULL) { count[ptr->data] += 1; ptr = ptr->next; } int i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 * now start traversing list from head node, * 1) fill the list with 0, till n1 > 0 * 2) fill the list with 1, till n2 > 0 * 3) fill the list with 2, till n3 > 0 */ while (ptr != NULL) { if (count[i] == 0) ++i; else { ptr->data = i; --count[i]; ptr = ptr->next; } }} /* Function to push a node */void push (struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node *node){ while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("n");} /* Driver program to test above function*/int main(void){ struct Node *head = NULL; push(&head, 0); push(&head, 1); push(&head, 0); push(&head, 2); push(&head, 1); push(&head, 1); push(&head, 2); push(&head, 1); push(&head, 2); printf("Linked List Before Sorting\n"); printList(head); sortList(head); printf("Linked List After Sorting\n"); printList(head); return 0;} // Java program to sort a linked list of 0, 1 and 2class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) {data = d; next = null; } } void sortList() { // initialise count of 0 1 and 2 as 0 int count[] = {0, 0, 0}; Node ptr = head; /* count total number of '0', '1' and '2' * count[0] will store total number of '0's * count[1] will store total number of '1's * count[2] will store total number of '2's */ while (ptr != null) { count[ptr.data]++; ptr = ptr.next; } int i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 * now start traversing list from head node, * 1) fill the list with 0, till n1 > 0 * 2) fill the list with 1, till n2 > 0 * 3) fill the list with 2, till n3 > 0 */ while (ptr != null) { if (count[i] == 0) i++; else { ptr.data= i; --count[i]; ptr = ptr.next; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data+" "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->6->7-> 8->8->9->null */ llist.push(0); llist.push(1); llist.push(0); llist.push(2); llist.push(1); llist.push(1); llist.push(2); llist.push(1); llist.push(2); System.out.println("Linked List before sorting"); llist.printList(); llist.sortList(); System.out.println("Linked List after sorting"); llist.printList(); }}/* This code is contributed by Rajat Mishra */ # Python program to sort a linked list of 0, 1 and 2class LinkedList(object): def __init__(self): # head of list self.head = None # Linked list Node class Node(object): def __init__(self, d): self.data = d self.next = None def sortList(self): # initialise count of 0 1 and 2 as 0 count = [0, 0, 0] ptr = self.head # count total number of '0', '1' and '2' # * count[0] will store total number of '0's # * count[1] will store total number of '1's # * count[2] will store total number of '2's while ptr != None: count[ptr.data]+=1 ptr = ptr.next i = 0 ptr = self.head # Let say count[0] = n1, count[1] = n2 and count[2] = n3 # * now start traversing list from head node, # * 1) fill the list with 0, till n1 > 0 # * 2) fill the list with 1, till n2 > 0 # * 3) fill the list with 2, till n3 > 0 while ptr != None: if count[i] == 0: i+=1 else: ptr.data = i count[i]-=1 ptr = ptr.next # Utility functions # Inserts a new Node at front of the list. def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = self.Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Function to print linked list def printList(self): temp = self.head while temp != None: print (str(temp.data),end=" ") temp = temp.next print() # Driver program to test above functionsllist = LinkedList()llist.push(0)llist.push(1)llist.push(0)llist.push(2)llist.push(1)llist.push(1)llist.push(2)llist.push(1)llist.push(2) print ("Linked List before sorting")llist.printList() llist.sortList() print ("Linked List after sorting")llist.printList() # This code is contributed by BHAVYA JAIN // C# program to sort a linked// list of 0, 1 and 2using System; public class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } void sortList() { // initialise count of 0 1 and 2 as 0 int []count = {0, 0, 0}; Node ptr = head; /* count total number of '0', '1' and '2' * count[0] will store total number of '0's * count[1] will store total number of '1's * count[2] will store total number of '2's */ while (ptr != null) { count[ptr.data]++; ptr = ptr.next; } int i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 * now start traversing list from head node, * 1) fill the list with 0, till n1 > 0 * 2) fill the list with 1, till n2 > 0 * 3) fill the list with 2, till n3 > 0 */ while (ptr != null) { if (count[i] == 0) i++; else { ptr.data= i; --count[i]; ptr = ptr.next; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data+" "); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String []args) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4-> 5->6->7->8->8->9->null */ llist.push(0); llist.push(1); llist.push(0); llist.push(2); llist.push(1); llist.push(1); llist.push(2); llist.push(1); llist.push(2); Console.WriteLine("Linked List before sorting"); llist.printList(); llist.sortList(); Console.WriteLine("Linked List after sorting"); llist.printList(); }} /* This code is contributed by 29AjayKumar */ <script> // Javascript program to sort a// linked list of 0, 1 and 2var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } function sortList() { // initialise count of 0 1 and 2 as 0 var count = [ 0, 0, 0 ]; var ptr = head; /* count total number of '0', '1' and '2' count[0] will store total number of '0's count[1] will store total number of '1's count[2] will store total number of '2's */ while (ptr != null) { count[ptr.data]++; ptr = ptr.next; } var i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 now start traversing list from head node, 1) fill the list with 0, till n1 > 0 2) fill the list with 1, till n2 > 0 3) fill the list with 2, till n3 > 0 */ while (ptr != null) { if (count[i] == 0) i++; else { ptr.data = i; --count[i]; ptr = ptr.next; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write("<br/>"); } /* Driver program to test above functions */ /* Constructed Linked List is 1->2->3->4->5->6->7-> 8->8->9->null */ push(0); push(1); push(0); push(2); push(1); push(1); push(2); push(1); push(2); document.write("Linked List before sorting<br/>"); printList(); sortList(); document.write("Linked List after sorting<br/>"); printList(); // This code is contributed by todaysgaurav </script> Output: Linked List Before Sorting 2 1 2 1 1 2 0 1 0 Linked List After Sorting 0 0 1 1 1 1 2 2 2 Time Complexity: O(n) where n is the number of nodes in the linked list. Auxiliary Space: O(1) https://youtu.be/4 -3TU2FRs70?list=PLqM7alHXFySH41ZxzrPNj2pAYPOI8ITe7Sort a linked list of 0s, 1s and 2s by changing linksThis article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar rathbhupendra nidhi_biet todaysgaurav amartyaghoshgfg Amazon Linked-List-Sorting MakeMyTrip Microsoft Linked List Sorting Amazon Microsoft MakeMyTrip Linked List Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Linked List vs Array Doubly Linked List | Set 1 (Introduction and Insertion) Delete a Linked List node at a given position Implement a stack using singly linked list
[ { "code": null, "e": 26149, "s": 26121, "text": "\n17 Jan, 2022" }, { "code": null, "e": 26207, "s": 26149, "text": "Given a linked list of 0s, 1s and 2s, sort it.Examples: " }, { "code": null, "e": 26378, "s": 26207, "text": "Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULLInput: 1 -> 1 -> 2 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL " }, { "code": null, "e": 26416, "s": 26378, "text": "Source: Microsoft Interview | Set 1 " }, { "code": null, "e": 26477, "s": 26416, "text": "Following steps can be used to sort the given linked list. " }, { "code": null, "e": 26582, "s": 26477, "text": "Traverse the list and count the number of 0s, 1s, and 2s. Let the counts be n1, n2, and n3 respectively." }, { "code": null, "e": 26690, "s": 26582, "text": "Traverse the list again, fill the first n1 nodes with 0, then n2 nodes with 1, and finally n3 nodes with 2." }, { "code": null, "e": 26739, "s": 26690, "text": "Below image is a dry run of the above approach: " }, { "code": null, "e": 26791, "s": 26739, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26795, "s": 26791, "text": "C++" }, { "code": null, "e": 26797, "s": 26795, "text": "C" }, { "code": null, "e": 26802, "s": 26797, "text": "Java" }, { "code": null, "e": 26810, "s": 26802, "text": "Python3" }, { "code": null, "e": 26813, "s": 26810, "text": "C#" }, { "code": null, "e": 26824, "s": 26813, "text": "Javascript" }, { "code": "// C++ Program to sort a linked list 0s, 1s or 2s#include <bits/stdc++.h>using namespace std; /* Link list node */class Node{ public: int data; Node* next;}; // Function to sort a linked list of 0s, 1s and 2svoid sortList(Node *head){ int count[3] = {0, 0, 0}; // Initialize count of '0', '1' and '2' as 0 Node *ptr = head; /* count total number of '0', '1' and '2' * count[0] will store total number of '0's * count[1] will store total number of '1's * count[2] will store total number of '2's */ while (ptr != NULL) { count[ptr->data] += 1; ptr = ptr->next; } int i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 * now start traversing list from head node, * 1) fill the list with 0, till n1 > 0 * 2) fill the list with 1, till n2 > 0 * 3) fill the list with 2, till n3 > 0 */ while (ptr != NULL) { if (count[i] == 0) ++i; else { ptr->data = i; --count[i]; ptr = ptr->next; } }} /* Function to push a node */void push (Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(Node *node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; } cout << endl;} /* Driver code*/int main(void){ Node *head = NULL; push(&head, 0); push(&head, 1); push(&head, 0); push(&head, 2); push(&head, 1); push(&head, 1); push(&head, 2); push(&head, 1); push(&head, 2); cout << \"Linked List Before Sorting\\n\"; printList(head); sortList(head); cout << \"Linked List After Sorting\\n\"; printList(head); return 0;} // This code is contributed by rathbhupendra", "e": 28833, "s": 26824, "text": null }, { "code": "// C Program to sort a linked list 0s, 1s or 2s#include<stdio.h>#include<stdlib.h> /* Link list node */struct Node{ int data; struct Node* next;}; // Function to sort a linked list of 0s, 1s and 2svoid sortList(struct Node *head){ int count[3] = {0, 0, 0}; // Initialize count of '0', '1' and '2' as 0 struct Node *ptr = head; /* count total number of '0', '1' and '2' * count[0] will store total number of '0's * count[1] will store total number of '1's * count[2] will store total number of '2's */ while (ptr != NULL) { count[ptr->data] += 1; ptr = ptr->next; } int i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 * now start traversing list from head node, * 1) fill the list with 0, till n1 > 0 * 2) fill the list with 1, till n2 > 0 * 3) fill the list with 2, till n3 > 0 */ while (ptr != NULL) { if (count[i] == 0) ++i; else { ptr->data = i; --count[i]; ptr = ptr->next; } }} /* Function to push a node */void push (struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node *node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; } printf(\"n\");} /* Driver program to test above function*/int main(void){ struct Node *head = NULL; push(&head, 0); push(&head, 1); push(&head, 0); push(&head, 2); push(&head, 1); push(&head, 1); push(&head, 2); push(&head, 1); push(&head, 2); printf(\"Linked List Before Sorting\\n\"); printList(head); sortList(head); printf(\"Linked List After Sorting\\n\"); printList(head); return 0;}", "e": 30905, "s": 28833, "text": null }, { "code": "// Java program to sort a linked list of 0, 1 and 2class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) {data = d; next = null; } } void sortList() { // initialise count of 0 1 and 2 as 0 int count[] = {0, 0, 0}; Node ptr = head; /* count total number of '0', '1' and '2' * count[0] will store total number of '0's * count[1] will store total number of '1's * count[2] will store total number of '2's */ while (ptr != null) { count[ptr.data]++; ptr = ptr.next; } int i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 * now start traversing list from head node, * 1) fill the list with 0, till n1 > 0 * 2) fill the list with 1, till n2 > 0 * 3) fill the list with 2, till n3 > 0 */ while (ptr != null) { if (count[i] == 0) i++; else { ptr.data= i; --count[i]; ptr = ptr.next; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data+\" \"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->6->7-> 8->8->9->null */ llist.push(0); llist.push(1); llist.push(0); llist.push(2); llist.push(1); llist.push(1); llist.push(2); llist.push(1); llist.push(2); System.out.println(\"Linked List before sorting\"); llist.printList(); llist.sortList(); System.out.println(\"Linked List after sorting\"); llist.printList(); }}/* This code is contributed by Rajat Mishra */", "e": 33467, "s": 30905, "text": null }, { "code": "# Python program to sort a linked list of 0, 1 and 2class LinkedList(object): def __init__(self): # head of list self.head = None # Linked list Node class Node(object): def __init__(self, d): self.data = d self.next = None def sortList(self): # initialise count of 0 1 and 2 as 0 count = [0, 0, 0] ptr = self.head # count total number of '0', '1' and '2' # * count[0] will store total number of '0's # * count[1] will store total number of '1's # * count[2] will store total number of '2's while ptr != None: count[ptr.data]+=1 ptr = ptr.next i = 0 ptr = self.head # Let say count[0] = n1, count[1] = n2 and count[2] = n3 # * now start traversing list from head node, # * 1) fill the list with 0, till n1 > 0 # * 2) fill the list with 1, till n2 > 0 # * 3) fill the list with 2, till n3 > 0 while ptr != None: if count[i] == 0: i+=1 else: ptr.data = i count[i]-=1 ptr = ptr.next # Utility functions # Inserts a new Node at front of the list. def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = self.Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Function to print linked list def printList(self): temp = self.head while temp != None: print (str(temp.data),end=\" \") temp = temp.next print() # Driver program to test above functionsllist = LinkedList()llist.push(0)llist.push(1)llist.push(0)llist.push(2)llist.push(1)llist.push(1)llist.push(2)llist.push(1)llist.push(2) print (\"Linked List before sorting\")llist.printList() llist.sortList() print (\"Linked List after sorting\")llist.printList() # This code is contributed by BHAVYA JAIN", "e": 35521, "s": 33467, "text": null }, { "code": "// C# program to sort a linked// list of 0, 1 and 2using System; public class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } void sortList() { // initialise count of 0 1 and 2 as 0 int []count = {0, 0, 0}; Node ptr = head; /* count total number of '0', '1' and '2' * count[0] will store total number of '0's * count[1] will store total number of '1's * count[2] will store total number of '2's */ while (ptr != null) { count[ptr.data]++; ptr = ptr.next; } int i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 * now start traversing list from head node, * 1) fill the list with 0, till n1 > 0 * 2) fill the list with 1, till n2 > 0 * 3) fill the list with 2, till n3 > 0 */ while (ptr != null) { if (count[i] == 0) i++; else { ptr.data= i; --count[i]; ptr = ptr.next; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data+\" \"); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String []args) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4-> 5->6->7->8->8->9->null */ llist.push(0); llist.push(1); llist.push(0); llist.push(2); llist.push(1); llist.push(1); llist.push(2); llist.push(1); llist.push(2); Console.WriteLine(\"Linked List before sorting\"); llist.printList(); llist.sortList(); Console.WriteLine(\"Linked List after sorting\"); llist.printList(); }} /* This code is contributed by 29AjayKumar */", "e": 38132, "s": 35521, "text": null }, { "code": "<script> // Javascript program to sort a// linked list of 0, 1 and 2var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } function sortList() { // initialise count of 0 1 and 2 as 0 var count = [ 0, 0, 0 ]; var ptr = head; /* count total number of '0', '1' and '2' count[0] will store total number of '0's count[1] will store total number of '1's count[2] will store total number of '2's */ while (ptr != null) { count[ptr.data]++; ptr = ptr.next; } var i = 0; ptr = head; /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 now start traversing list from head node, 1) fill the list with 0, till n1 > 0 2) fill the list with 1, till n2 > 0 3) fill the list with 2, till n3 > 0 */ while (ptr != null) { if (count[i] == 0) i++; else { ptr.data = i; --count[i]; ptr = ptr.next; } } } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(\"<br/>\"); } /* Driver program to test above functions */ /* Constructed Linked List is 1->2->3->4->5->6->7-> 8->8->9->null */ push(0); push(1); push(0); push(2); push(1); push(1); push(2); push(1); push(2); document.write(\"Linked List before sorting<br/>\"); printList(); sortList(); document.write(\"Linked List after sorting<br/>\"); printList(); // This code is contributed by todaysgaurav </script>", "e": 40500, "s": 38132, "text": null }, { "code": null, "e": 40509, "s": 40500, "text": "Output: " }, { "code": null, "e": 40614, "s": 40509, "text": "Linked List Before Sorting\n2 1 2 1 1 2 0 1 0\nLinked List After Sorting\n0 0 1 1 1 1 2 2 2" }, { "code": null, "e": 40711, "s": 40614, "text": "Time Complexity: O(n) where n is the number of nodes in the linked list. Auxiliary Space: O(1) " }, { "code": null, "e": 40730, "s": 40711, "text": "https://youtu.be/4" }, { "code": null, "e": 41008, "s": 40730, "text": "-3TU2FRs70?list=PLqM7alHXFySH41ZxzrPNj2pAYPOI8ITe7Sort a linked list of 0s, 1s and 2s by changing linksThis article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41020, "s": 41008, "text": "29AjayKumar" }, { "code": null, "e": 41034, "s": 41020, "text": "rathbhupendra" }, { "code": null, "e": 41045, "s": 41034, "text": "nidhi_biet" }, { "code": null, "e": 41058, "s": 41045, "text": "todaysgaurav" }, { "code": null, "e": 41074, "s": 41058, "text": "amartyaghoshgfg" }, { "code": null, "e": 41081, "s": 41074, "text": "Amazon" }, { "code": null, "e": 41101, "s": 41081, "text": "Linked-List-Sorting" }, { "code": null, "e": 41112, "s": 41101, "text": "MakeMyTrip" }, { "code": null, "e": 41122, "s": 41112, "text": "Microsoft" }, { "code": null, "e": 41134, "s": 41122, "text": "Linked List" }, { "code": null, "e": 41142, "s": 41134, "text": "Sorting" }, { "code": null, "e": 41149, "s": 41142, "text": "Amazon" }, { "code": null, "e": 41159, "s": 41149, "text": "Microsoft" }, { "code": null, "e": 41170, "s": 41159, "text": "MakeMyTrip" }, { "code": null, "e": 41182, "s": 41170, "text": "Linked List" }, { "code": null, "e": 41190, "s": 41182, "text": "Sorting" }, { "code": null, "e": 41288, "s": 41190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41307, "s": 41288, "text": "LinkedList in Java" }, { "code": null, "e": 41328, "s": 41307, "text": "Linked List vs Array" }, { "code": null, "e": 41384, "s": 41328, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 41430, "s": 41384, "text": "Delete a Linked List node at a given position" } ]
What is the use of serve favicon from Node.js server ? - GeeksforGeeks
13 Jul, 2021 When the browser loads a website for the first time, it will automatically request /favicon.ico (GET) to load favicon. A favicon is a small size file as known as website icon, tab icon, URL icon or bookmark icon. The serve-favicon module is used to serve favicon from the NodeJS server. Why to use this module? User agents request frequently and indiscriminately for favicon. Use this middleware before your logger middleware to exclude these request from logs. favicon.ico is small size file, this module caches the favicon in memory to give better performance by skipping dick access. This module provides an ETag for the icon. This module provides compatible Content-Type for the icon. Project Setup and Module Installation: Step 1: Create a NodeJS application and name it Project using the following command.mkdir Project && cd Project npm init -y Step 1: Create a NodeJS application and name it Project using the following command. mkdir Project && cd Project npm init -y Step 2: Install the dependency modules using the following command.npm install express serve-favicon Step 2: Install the dependency modules using the following command. npm install express serve-favicon Step 3: Generate a favicon from here or download the GFG favicon and place it in your root directory. Then create index.html and server.js in your Project directory. Step 3: Generate a favicon from here or download the GFG favicon and place it in your root directory. Then create index.html and server.js in your Project directory. Project Directory: It will look like this. Project directory Example: index.html <!DOCTYPE html><html> <head> <title>GeeksForGeeks</title></head> <body> <h1 style="color: green;"> GeeksForGeeks </h1></body> </html> server.js // Import modulesconst favicon = require('serve-favicon');const express = require('express')const app = express() // Returns a middleware to serve faviconapp.use(favicon(__dirname + '/favicon.ico')); // API endpoint to serve index app.get('/', (_, res)=> res.sendFile(__dirname + '/index.html')) // Start the serverapp.listen(8080); Step to run the application: Run the server.js using the following command node server.js Output: Open the browser and go to http://localhost:8080/, we will see the following output on screen. Note: Remember, serve-favicon is only serving default, implicit favicon, which is GET /favicon.ico. Use serve-static for vendor-specific icons that require HTML markup. Node.js-Methods NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js Export Module How to connect Node.js with React.js ? Difference between dependencies, devDependencies and peerDependencies Mongoose find() Function Mongoose Populate() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n13 Jul, 2021" }, { "code": null, "e": 26554, "s": 26267, "text": "When the browser loads a website for the first time, it will automatically request /favicon.ico (GET) to load favicon. A favicon is a small size file as known as website icon, tab icon, URL icon or bookmark icon. The serve-favicon module is used to serve favicon from the NodeJS server." }, { "code": null, "e": 26578, "s": 26554, "text": "Why to use this module?" }, { "code": null, "e": 26729, "s": 26578, "text": "User agents request frequently and indiscriminately for favicon. Use this middleware before your logger middleware to exclude these request from logs." }, { "code": null, "e": 26854, "s": 26729, "text": "favicon.ico is small size file, this module caches the favicon in memory to give better performance by skipping dick access." }, { "code": null, "e": 26897, "s": 26854, "text": "This module provides an ETag for the icon." }, { "code": null, "e": 26956, "s": 26897, "text": "This module provides compatible Content-Type for the icon." }, { "code": null, "e": 26995, "s": 26956, "text": "Project Setup and Module Installation:" }, { "code": null, "e": 27120, "s": 26995, "text": "Step 1: Create a NodeJS application and name it Project using the following command.mkdir Project && cd Project\nnpm init -y " }, { "code": null, "e": 27205, "s": 27120, "text": "Step 1: Create a NodeJS application and name it Project using the following command." }, { "code": null, "e": 27245, "s": 27205, "text": "mkdir Project && cd Project\nnpm init -y" }, { "code": null, "e": 27348, "s": 27247, "text": "Step 2: Install the dependency modules using the following command.npm install express serve-favicon" }, { "code": null, "e": 27416, "s": 27348, "text": "Step 2: Install the dependency modules using the following command." }, { "code": null, "e": 27450, "s": 27416, "text": "npm install express serve-favicon" }, { "code": null, "e": 27617, "s": 27450, "text": "Step 3: Generate a favicon from here or download the GFG favicon and place it in your root directory. Then create index.html and server.js in your Project directory. " }, { "code": null, "e": 27784, "s": 27617, "text": "Step 3: Generate a favicon from here or download the GFG favicon and place it in your root directory. Then create index.html and server.js in your Project directory. " }, { "code": null, "e": 27827, "s": 27784, "text": "Project Directory: It will look like this." }, { "code": null, "e": 27845, "s": 27827, "text": "Project directory" }, { "code": null, "e": 27854, "s": 27845, "text": "Example:" }, { "code": null, "e": 27865, "s": 27854, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <head> <title>GeeksForGeeks</title></head> <body> <h1 style=\"color: green;\"> GeeksForGeeks </h1></body> </html>", "e": 28018, "s": 27865, "text": null }, { "code": null, "e": 28028, "s": 28018, "text": "server.js" }, { "code": "// Import modulesconst favicon = require('serve-favicon');const express = require('express')const app = express() // Returns a middleware to serve faviconapp.use(favicon(__dirname + '/favicon.ico')); // API endpoint to serve index app.get('/', (_, res)=> res.sendFile(__dirname + '/index.html')) // Start the serverapp.listen(8080);", "e": 28364, "s": 28028, "text": null }, { "code": null, "e": 28439, "s": 28364, "text": "Step to run the application: Run the server.js using the following command" }, { "code": null, "e": 28454, "s": 28439, "text": "node server.js" }, { "code": null, "e": 28557, "s": 28454, "text": "Output: Open the browser and go to http://localhost:8080/, we will see the following output on screen." }, { "code": null, "e": 28727, "s": 28557, "text": "Note: Remember, serve-favicon is only serving default, implicit favicon, which is GET /favicon.ico. Use serve-static for vendor-specific icons that require HTML markup. " }, { "code": null, "e": 28743, "s": 28727, "text": "Node.js-Methods" }, { "code": null, "e": 28760, "s": 28743, "text": "NodeJS-Questions" }, { "code": null, "e": 28767, "s": 28760, "text": "Picked" }, { "code": null, "e": 28775, "s": 28767, "text": "Node.js" }, { "code": null, "e": 28792, "s": 28775, "text": "Web Technologies" }, { "code": null, "e": 28890, "s": 28792, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28912, "s": 28890, "text": "Node.js Export Module" }, { "code": null, "e": 28951, "s": 28912, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 29021, "s": 28951, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 29046, "s": 29021, "text": "Mongoose find() Function" }, { "code": null, "e": 29073, "s": 29046, "text": "Mongoose Populate() Method" }, { "code": null, "e": 29113, "s": 29073, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29158, "s": 29113, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29201, "s": 29158, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29263, "s": 29201, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Angular PrimeNG Accordion Component - GeeksforGeeks
11 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Accordion Component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code. Accordion component: It is used to display a section of custom content in tabs. Properties for Accordion: multiple: It specifies whether multiple tabs can be activated at the same time. It is of boolean data type & the default value is false. style: It is the inline style of the component. It is of string data type & the default value is null. styleClass: it is the style class of the component. It is of string data type & the default value is false. activeIndex: It is the index of the active tab. It accepts any data type & the default value is null. expandIcon: It is the icon of a collapsed tab. It is of string data type & the default value is pi pi-fw pi-chevron-right. collapseIcon: It is the icon of an expanded tab. It is of string data type & the default value is pi pi-fw pi-chevron-down. Properties for AccordionTab: header: It specifies the title of the tab. It is of string data type & the default value is null. selected: It defines if the tab is active. It is of the boolean data type & the default value is false. disabled: It defines whether the tab can be selected. It is of the boolean data type & the default value is false. transitionOptions: Transition options of the animation. It is of string data type & the default value is 400ms cubic-bezier(0.86, 0, 0.07, 1). cache: It specifies whether a lazy loaded panel should avoid getting loaded again on reselection. It is of the boolean data type & the default value is true. Event: onClose: It is a callback that is fired by clicking on the header. onOpen: It is a callback that is fired when the tab gets expanded. Styling: p-accordion: it is the container element. p-accordion-header: it is the header of a tab. p-accordion-content: it is the content of a tab. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that illustrates how to use the Accordion component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Accordion component</h5><p-accordion> <p-accordionTab header="Angular PrimeNG" [selected]="true"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab> <p-accordionTab header="Angular PrimeNG"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab> <p-accordionTab header="Angular PrimeNG"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab></p-accordion> app.component.ts import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"],})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { AccordionModule } from "primeng/accordion"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, AccordionModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will know how to use multiple property in the Accordion Component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Accordion component</h5><p-accordion multiple="true"> <p-accordionTab header="Angular PrimeNG" [selected]="true"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab> <p-accordionTab header="Angular PrimeNG"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab> <p-accordionTab header="Angular PrimeNG"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab></p-accordion> app.component.ts import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"],})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { AccordionModule } from "primeng/accordion"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, AccordionModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/accordion Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n11 Sep, 2021" }, { "code": null, "e": 26746, "s": 26354, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Accordion Component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 26826, "s": 26746, "text": "Accordion component: It is used to display a section of custom content in tabs." }, { "code": null, "e": 26852, "s": 26826, "text": "Properties for Accordion:" }, { "code": null, "e": 26989, "s": 26852, "text": "multiple: It specifies whether multiple tabs can be activated at the same time. It is of boolean data type & the default value is false." }, { "code": null, "e": 27092, "s": 26989, "text": "style: It is the inline style of the component. It is of string data type & the default value is null." }, { "code": null, "e": 27200, "s": 27092, "text": "styleClass: it is the style class of the component. It is of string data type & the default value is false." }, { "code": null, "e": 27302, "s": 27200, "text": "activeIndex: It is the index of the active tab. It accepts any data type & the default value is null." }, { "code": null, "e": 27425, "s": 27302, "text": "expandIcon: It is the icon of a collapsed tab. It is of string data type & the default value is pi pi-fw pi-chevron-right." }, { "code": null, "e": 27549, "s": 27425, "text": "collapseIcon: It is the icon of an expanded tab. It is of string data type & the default value is pi pi-fw pi-chevron-down." }, { "code": null, "e": 27578, "s": 27549, "text": "Properties for AccordionTab:" }, { "code": null, "e": 27676, "s": 27578, "text": "header: It specifies the title of the tab. It is of string data type & the default value is null." }, { "code": null, "e": 27780, "s": 27676, "text": "selected: It defines if the tab is active. It is of the boolean data type & the default value is false." }, { "code": null, "e": 27895, "s": 27780, "text": "disabled: It defines whether the tab can be selected. It is of the boolean data type & the default value is false." }, { "code": null, "e": 28038, "s": 27895, "text": "transitionOptions: Transition options of the animation. It is of string data type & the default value is 400ms cubic-bezier(0.86, 0, 0.07, 1)." }, { "code": null, "e": 28196, "s": 28038, "text": "cache: It specifies whether a lazy loaded panel should avoid getting loaded again on reselection. It is of the boolean data type & the default value is true." }, { "code": null, "e": 28205, "s": 28198, "text": "Event:" }, { "code": null, "e": 28272, "s": 28205, "text": "onClose: It is a callback that is fired by clicking on the header." }, { "code": null, "e": 28339, "s": 28272, "text": "onOpen: It is a callback that is fired when the tab gets expanded." }, { "code": null, "e": 28348, "s": 28339, "text": "Styling:" }, { "code": null, "e": 28390, "s": 28348, "text": "p-accordion: it is the container element." }, { "code": null, "e": 28437, "s": 28390, "text": "p-accordion-header: it is the header of a tab." }, { "code": null, "e": 28486, "s": 28437, "text": "p-accordion-content: it is the content of a tab." }, { "code": null, "e": 28538, "s": 28486, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 28605, "s": 28538, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 28620, "s": 28605, "text": "ng new appname" }, { "code": null, "e": 28717, "s": 28620, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28728, "s": 28717, "text": "cd appname" }, { "code": null, "e": 28777, "s": 28728, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28834, "s": 28777, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28886, "s": 28834, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 28976, "s": 28886, "text": "Example 1: This is the basic example that illustrates how to use the Accordion component." }, { "code": null, "e": 28995, "s": 28976, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Accordion component</h5><p-accordion> <p-accordionTab header=\"Angular PrimeNG\" [selected]=\"true\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab> <p-accordionTab header=\"Angular PrimeNG\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab> <p-accordionTab header=\"Angular PrimeNG\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab></p-accordion>", "e": 30011, "s": 28995, "text": null }, { "code": null, "e": 30030, "s": 30013, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styleUrls: [\"./app.component.scss\"],})export class AppComponent {}", "e": 30214, "s": 30030, "text": null }, { "code": null, "e": 30228, "s": 30214, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { AccordionModule } from \"primeng/accordion\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, AccordionModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 30706, "s": 30228, "text": null }, { "code": null, "e": 30714, "s": 30706, "text": "Output:" }, { "code": null, "e": 30812, "s": 30714, "text": "Example 2: In this example, we will know how to use multiple property in the Accordion Component." }, { "code": null, "e": 30831, "s": 30812, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Accordion component</h5><p-accordion multiple=\"true\"> <p-accordionTab header=\"Angular PrimeNG\" [selected]=\"true\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab> <p-accordionTab header=\"Angular PrimeNG\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab> <p-accordionTab header=\"Angular PrimeNG\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-accordionTab></p-accordion>", "e": 31759, "s": 30831, "text": null }, { "code": null, "e": 31776, "s": 31759, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styleUrls: [\"./app.component.scss\"],})export class AppComponent {}", "e": 31960, "s": 31776, "text": null }, { "code": null, "e": 31974, "s": 31960, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { AccordionModule } from \"primeng/accordion\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, AccordionModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 32452, "s": 31974, "text": null }, { "code": null, "e": 32460, "s": 32452, "text": "Output:" }, { "code": null, "e": 32523, "s": 32460, "text": "Reference: https://primefaces.org/primeng/showcase/#/accordion" }, { "code": null, "e": 32539, "s": 32523, "text": "Angular-PrimeNG" }, { "code": null, "e": 32549, "s": 32539, "text": "AngularJS" }, { "code": null, "e": 32566, "s": 32549, "text": "Web Technologies" }, { "code": null, "e": 32664, "s": 32566, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32699, "s": 32664, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 32734, "s": 32699, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 32758, "s": 32734, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 32793, "s": 32758, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 32846, "s": 32793, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 32886, "s": 32846, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32919, "s": 32886, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32964, "s": 32919, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33007, "s": 32964, "text": "How to fetch data from an API in ReactJS ?" } ]
Python 3 - String ljust() Method
The method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s). Following is the syntax for ljust() method − str.ljust(width[, fillchar]) width − This is string length in total after padding. width − This is string length in total after padding. fillchar − This is filler character, default is a space. fillchar − This is filler character, default is a space. This method returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s). The following example shows the usage of ljust() method. #!/usr/bin/python3 str = "this is string example....wow!!!" print str.ljust(50, '*') When we run above program, it produces the following result − this is string example....wow!!!****************** 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2551, "s": 2340, "text": "The method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s)." }, { "code": null, "e": 2596, "s": 2551, "text": "Following is the syntax for ljust() method −" }, { "code": null, "e": 2626, "s": 2596, "text": "str.ljust(width[, fillchar])\n" }, { "code": null, "e": 2680, "s": 2626, "text": "width − This is string length in total after padding." }, { "code": null, "e": 2734, "s": 2680, "text": "width − This is string length in total after padding." }, { "code": null, "e": 2791, "s": 2734, "text": "fillchar − This is filler character, default is a space." }, { "code": null, "e": 2848, "s": 2791, "text": "fillchar − This is filler character, default is a space." }, { "code": null, "e": 3052, "s": 2848, "text": "This method returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s)." }, { "code": null, "e": 3109, "s": 3052, "text": "The following example shows the usage of ljust() method." }, { "code": null, "e": 3195, "s": 3109, "text": "#!/usr/bin/python3\n\nstr = \"this is string example....wow!!!\"\nprint str.ljust(50, '*')" }, { "code": null, "e": 3257, "s": 3195, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 3309, "s": 3257, "text": "this is string example....wow!!!******************\n" }, { "code": null, "e": 3346, "s": 3309, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3362, "s": 3346, "text": " Malhar Lathkar" }, { "code": null, "e": 3395, "s": 3362, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3414, "s": 3395, "text": " Arnab Chakraborty" }, { "code": null, "e": 3449, "s": 3414, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3471, "s": 3449, "text": " In28Minutes Official" }, { "code": null, "e": 3505, "s": 3471, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3533, "s": 3505, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3568, "s": 3533, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3582, "s": 3568, "text": " Lets Kode It" }, { "code": null, "e": 3615, "s": 3582, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3632, "s": 3615, "text": " Abhilash Nelson" }, { "code": null, "e": 3639, "s": 3632, "text": " Print" }, { "code": null, "e": 3650, "s": 3639, "text": " Add Notes" } ]
XML DOM - Create Node
In this chapter, we will discuss how to create new nodes using a couple of methods of the document object. These methods provide a scope to create new element node, text node, comment node, CDATA section node and attribute node. If the newly created node already exists in the element object, it is replaced by the new one. Following sections demonstrate this with examples. The method createElement() creates a new element node. If the newly created element node exists in the element object, it is replaced by the new one. Syntax to use the createElement() method is as follows − var_name = xmldoc.createElement("tagname"); Where, var_name − is the user-defined variable name which holds the name of new element. var_name − is the user-defined variable name which holds the name of new element. ("tagname") − is the name of new element node to be created. ("tagname") − is the name of new element node to be created. The following example (createnewelement_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new element node PhoneNo in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); new_element = xmlDoc.createElement("PhoneNo"); x = xmlDoc.getElementsByTagName("FirstName")[0]; x.appendChild(new_element); document.write(x.getElementsByTagName("PhoneNo")[0].nodeName); </script> </body> </html> new_element = xmlDoc.createElement("PhoneNo"); creates the new element node <PhoneNo> new_element = xmlDoc.createElement("PhoneNo"); creates the new element node <PhoneNo> x.appendChild(new_element); x holds the name of the specified child node <FirstName> to which the new element node is appended. x.appendChild(new_element); x holds the name of the specified child node <FirstName> to which the new element node is appended. Save this file as createnewelement_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output we get the attribute value as PhoneNo. The method createTextNode() creates a new text node. Syntax to use createTextNode() is as follows − var_name = xmldoc.createTextNode("tagname"); Where, var_name − it is the user-defined variable name which holds the name of new text node. var_name − it is the user-defined variable name which holds the name of new text node. ("tagname") − within the parenthesis is the name of new text node to be created. ("tagname") − within the parenthesis is the name of new text node to be created. The following example (createtextnode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new text node Im new text node in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_e = xmlDoc.createElement("PhoneNo"); create_t = xmlDoc.createTextNode("Im new text node"); create_e.appendChild(create_t); x = xmlDoc.getElementsByTagName("Employee")[0]; x.appendChild(create_e); document.write(" PhoneNO: "); document.write(x.getElementsByTagName("PhoneNo")[0].childNodes[0].nodeValue); </script> </body> </html> Details of the above code are as below − create_e = xmlDoc.createElement("PhoneNo"); creates a new element <PhoneNo>. create_e = xmlDoc.createElement("PhoneNo"); creates a new element <PhoneNo>. create_t = xmlDoc.createTextNode("Im new text node"); creates a new text node "Im new text node". create_t = xmlDoc.createTextNode("Im new text node"); creates a new text node "Im new text node". x.appendChild(create_e); the text node, "Im new text node" is appended to the element, <PhoneNo>. x.appendChild(create_e); the text node, "Im new text node" is appended to the element, <PhoneNo>. document.write(x.getElementsByTagName("PhoneNo")[0].childNodes[0].nodeValue); writes the new text node value to the element <PhoneNo>. document.write(x.getElementsByTagName("PhoneNo")[0].childNodes[0].nodeValue); writes the new text node value to the element <PhoneNo>. Save this file as createtextnode_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the attribute value as i.e. PhoneNO: Im new text node. The method createComment() creates a new comment node. Comment node is included in the program for the easy understanding of the code functionality. Syntax to use createComment() is as follows − var_name = xmldoc.createComment("tagname"); Where, var_name − is the user-defined variable name which holds the name of new comment node. var_name − is the user-defined variable name which holds the name of new comment node. ("tagname") − is the name of the new comment node to be created. ("tagname") − is the name of the new comment node to be created. The following example (createcommentnode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new comment node, "Company is the parent node" in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_comment = xmlDoc.createComment("Company is the parent node"); x = xmlDoc.getElementsByTagName("Company")[0]; x.appendChild(create_comment); document.write(x.lastChild.nodeValue); </script> </body> </html> In the above example − create_comment = xmlDoc.createComment("Company is the parent node") creates a specified comment line. create_comment = xmlDoc.createComment("Company is the parent node") creates a specified comment line. x.appendChild(create_comment) In this line, 'x' holds the name of the element <Company> to which the comment line is appended. x.appendChild(create_comment) In this line, 'x' holds the name of the element <Company> to which the comment line is appended. Save this file as createcommentnode_example.htm on the server path (this file and the node.xml should be on the same path in your server). In the output, we get the attribute value as Company is the parent node . The method createCDATASection() creates a new CDATA section node. If the newly created CDATA section node exists in the element object, it is replaced by the new one. Syntax to use createCDATASection() is as follows − var_name = xmldoc.createCDATASection("tagname"); Where, var_name − is the user-defined variable name which holds the name of new the CDATA section node. var_name − is the user-defined variable name which holds the name of new the CDATA section node. ("tagname") − is the name of new CDATA section node to be created. ("tagname") − is the name of new CDATA section node to be created. The following example (createcdatanode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new CDATA section node, "Create CDATA Example" in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_CDATA = xmlDoc.createCDATASection("Create CDATA Example"); x = xmlDoc.getElementsByTagName("Employee")[0]; x.appendChild(create_CDATA); document.write(x.lastChild.nodeValue); </script> </body> </html> In the above example − create_CDATA = xmlDoc.createCDATASection("Create CDATA Example") creates a new CDATA section node, "Create CDATA Example" create_CDATA = xmlDoc.createCDATASection("Create CDATA Example") creates a new CDATA section node, "Create CDATA Example" x.appendChild(create_CDATA) here, x holds the specified element <Employee> indexed at 0 to which the CDATA node value is appended. x.appendChild(create_CDATA) here, x holds the specified element <Employee> indexed at 0 to which the CDATA node value is appended. Save this file as createcdatanode_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the attribute value as Create CDATA Example. To create a new attribute node, the method setAttributeNode() is used. If the newly created attribute node exists in the element object, it is replaced by the new one. Syntax to use the createElement() method is as follows − var_name = xmldoc.createAttribute("tagname"); Where, var_name − is the user-defined variable name which holds the name of new attribute node. var_name − is the user-defined variable name which holds the name of new attribute node. ("tagname") − is the name of new attribute node to be created. ("tagname") − is the name of new attribute node to be created. The following example (createattributenode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new attribute node section in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_a = xmlDoc.createAttribute("section"); create_a.nodeValue = "A"; x = xmlDoc.getElementsByTagName("Employee"); x[0].setAttributeNode(create_a); document.write("New Attribute: "); document.write(x[0].getAttribute("section")); </script> </body> </html> In the above example − create_a=xmlDoc.createAttribute("Category") creates an attribute with the name <section>. create_a=xmlDoc.createAttribute("Category") creates an attribute with the name <section>. create_a.nodeValue="Management" creates the value "A" for the attribute <section>. create_a.nodeValue="Management" creates the value "A" for the attribute <section>. x[0].setAttributeNode(create_a) this attribute value is set to the node element <Employee> indexed at 0. x[0].setAttributeNode(create_a) this attribute value is set to the node element <Employee> indexed at 0. 41 Lectures 5 hours Abhishek And Pukhraj 33 Lectures 3.5 hours Abhishek And Pukhraj 15 Lectures 1 hours Zach Miller 15 Lectures 4 hours Prof. Paul Cline, Ed.D 13 Lectures 4 hours Prof. Paul Cline, Ed.D 17 Lectures 2 hours Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2663, "s": 2288, "text": "In this chapter, we will discuss how to create new nodes using a couple of methods of the document object. These methods provide a scope to create new element node, text node, comment node, CDATA section node and attribute node. If the newly created node already exists in the element object, it is replaced by the new one. Following sections demonstrate this with examples." }, { "code": null, "e": 2813, "s": 2663, "text": "The method createElement() creates a new element node. If the newly created element node exists in the element object, it is replaced by the new one." }, { "code": null, "e": 2870, "s": 2813, "text": "Syntax to use the createElement() method is as follows −" }, { "code": null, "e": 2915, "s": 2870, "text": "var_name = xmldoc.createElement(\"tagname\");\n" }, { "code": null, "e": 2922, "s": 2915, "text": "Where," }, { "code": null, "e": 3004, "s": 2922, "text": "var_name − is the user-defined variable name which holds the name of new element." }, { "code": null, "e": 3086, "s": 3004, "text": "var_name − is the user-defined variable name which holds the name of new element." }, { "code": null, "e": 3147, "s": 3086, "text": "(\"tagname\") − is the name of new element node to be created." }, { "code": null, "e": 3208, "s": 3147, "text": "(\"tagname\") − is the name of new element node to be created." }, { "code": null, "e": 3378, "s": 3208, "text": "The following example (createnewelement_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new element node PhoneNo in the XML document." }, { "code": null, "e": 4156, "s": 3378, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n new_element = xmlDoc.createElement(\"PhoneNo\");\n\n x = xmlDoc.getElementsByTagName(\"FirstName\")[0];\n x.appendChild(new_element);\n\n document.write(x.getElementsByTagName(\"PhoneNo\")[0].nodeName);\n </script>\n </body>\n</html>" }, { "code": null, "e": 4242, "s": 4156, "text": "new_element = xmlDoc.createElement(\"PhoneNo\"); creates the new element node <PhoneNo>" }, { "code": null, "e": 4328, "s": 4242, "text": "new_element = xmlDoc.createElement(\"PhoneNo\"); creates the new element node <PhoneNo>" }, { "code": null, "e": 4456, "s": 4328, "text": "x.appendChild(new_element); x holds the name of the specified child node <FirstName> to which the new element node is appended." }, { "code": null, "e": 4584, "s": 4456, "text": "x.appendChild(new_element); x holds the name of the specified child node <FirstName> to which the new element node is appended." }, { "code": null, "e": 4771, "s": 4584, "text": "Save this file as createnewelement_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output we get the attribute value as PhoneNo." }, { "code": null, "e": 4824, "s": 4771, "text": "The method createTextNode() creates a new text node." }, { "code": null, "e": 4871, "s": 4824, "text": "Syntax to use createTextNode() is as follows −" }, { "code": null, "e": 4917, "s": 4871, "text": "var_name = xmldoc.createTextNode(\"tagname\");\n" }, { "code": null, "e": 4924, "s": 4917, "text": "Where," }, { "code": null, "e": 5011, "s": 4924, "text": "var_name − it is the user-defined variable name which holds the name of new text node." }, { "code": null, "e": 5098, "s": 5011, "text": "var_name − it is the user-defined variable name which holds the name of new text node." }, { "code": null, "e": 5179, "s": 5098, "text": "(\"tagname\") − within the parenthesis is the name of new text node to be created." }, { "code": null, "e": 5260, "s": 5179, "text": "(\"tagname\") − within the parenthesis is the name of new text node to be created." }, { "code": null, "e": 5434, "s": 5260, "text": "The following example (createtextnode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new text node Im new text node in the XML document." }, { "code": null, "e": 6365, "s": 5434, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_e = xmlDoc.createElement(\"PhoneNo\");\n create_t = xmlDoc.createTextNode(\"Im new text node\");\n create_e.appendChild(create_t);\n\n x = xmlDoc.getElementsByTagName(\"Employee\")[0];\n x.appendChild(create_e);\n\n\n document.write(\" PhoneNO: \");\n document.write(x.getElementsByTagName(\"PhoneNo\")[0].childNodes[0].nodeValue);\n </script>\n </body>\n</html>" }, { "code": null, "e": 6406, "s": 6365, "text": "Details of the above code are as below −" }, { "code": null, "e": 6483, "s": 6406, "text": "create_e = xmlDoc.createElement(\"PhoneNo\"); creates a new element <PhoneNo>." }, { "code": null, "e": 6560, "s": 6483, "text": "create_e = xmlDoc.createElement(\"PhoneNo\"); creates a new element <PhoneNo>." }, { "code": null, "e": 6658, "s": 6560, "text": "create_t = xmlDoc.createTextNode(\"Im new text node\"); creates a new text node \"Im new text node\"." }, { "code": null, "e": 6756, "s": 6658, "text": "create_t = xmlDoc.createTextNode(\"Im new text node\"); creates a new text node \"Im new text node\"." }, { "code": null, "e": 6856, "s": 6756, "text": " x.appendChild(create_e); the text node, \"Im new text node\" is appended to the element, <PhoneNo>. " }, { "code": null, "e": 6955, "s": 6856, "text": " x.appendChild(create_e); the text node, \"Im new text node\" is appended to the element, <PhoneNo>." }, { "code": null, "e": 7090, "s": 6955, "text": "document.write(x.getElementsByTagName(\"PhoneNo\")[0].childNodes[0].nodeValue); writes the new text node value to the element <PhoneNo>." }, { "code": null, "e": 7225, "s": 7090, "text": "document.write(x.getElementsByTagName(\"PhoneNo\")[0].childNodes[0].nodeValue); writes the new text node value to the element <PhoneNo>." }, { "code": null, "e": 7434, "s": 7225, "text": "Save this file as createtextnode_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the attribute value as i.e. PhoneNO: Im new text node." }, { "code": null, "e": 7583, "s": 7434, "text": "The method createComment() creates a new comment node. Comment node is included in the program for the easy understanding of the code functionality." }, { "code": null, "e": 7629, "s": 7583, "text": "Syntax to use createComment() is as follows −" }, { "code": null, "e": 7674, "s": 7629, "text": "var_name = xmldoc.createComment(\"tagname\");\n" }, { "code": null, "e": 7681, "s": 7674, "text": "Where," }, { "code": null, "e": 7768, "s": 7681, "text": "var_name − is the user-defined variable name which holds the name of new comment node." }, { "code": null, "e": 7855, "s": 7768, "text": "var_name − is the user-defined variable name which holds the name of new comment node." }, { "code": null, "e": 7920, "s": 7855, "text": "(\"tagname\") − is the name of the new comment node to be created." }, { "code": null, "e": 7985, "s": 7920, "text": "(\"tagname\") − is the name of the new comment node to be created." }, { "code": null, "e": 8178, "s": 7985, "text": "The following example (createcommentnode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new comment node, \"Company is the parent node\" in the XML document." }, { "code": null, "e": 8968, "s": 8178, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n }\n else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_comment = xmlDoc.createComment(\"Company is the parent node\");\n\n x = xmlDoc.getElementsByTagName(\"Company\")[0];\n\n x.appendChild(create_comment);\n\n document.write(x.lastChild.nodeValue);\n </script>\n </body>\n</html>" }, { "code": null, "e": 8991, "s": 8968, "text": "In the above example −" }, { "code": null, "e": 9093, "s": 8991, "text": "create_comment = xmlDoc.createComment(\"Company is the parent node\") creates a specified comment line." }, { "code": null, "e": 9195, "s": 9093, "text": "create_comment = xmlDoc.createComment(\"Company is the parent node\") creates a specified comment line." }, { "code": null, "e": 9323, "s": 9195, "text": " x.appendChild(create_comment) In this line, 'x' holds the name of the element <Company> to which the comment line is appended." }, { "code": null, "e": 9451, "s": 9323, "text": " x.appendChild(create_comment) In this line, 'x' holds the name of the element <Company> to which the comment line is appended." }, { "code": null, "e": 9664, "s": 9451, "text": "Save this file as createcommentnode_example.htm on the server path (this file and the node.xml should be on the same path in your server). In the output, we get the attribute value as Company is the parent node ." }, { "code": null, "e": 9831, "s": 9664, "text": "The method createCDATASection() creates a new CDATA section node. If the newly created CDATA section node exists in the element object, it is replaced by the new one." }, { "code": null, "e": 9882, "s": 9831, "text": "Syntax to use createCDATASection() is as follows −" }, { "code": null, "e": 9932, "s": 9882, "text": "var_name = xmldoc.createCDATASection(\"tagname\");\n" }, { "code": null, "e": 9939, "s": 9932, "text": "Where," }, { "code": null, "e": 10036, "s": 9939, "text": "var_name − is the user-defined variable name which holds the name of new the CDATA section node." }, { "code": null, "e": 10133, "s": 10036, "text": "var_name − is the user-defined variable name which holds the name of new the CDATA section node." }, { "code": null, "e": 10200, "s": 10133, "text": "(\"tagname\") − is the name of new CDATA section node to be created." }, { "code": null, "e": 10267, "s": 10200, "text": "(\"tagname\") − is the name of new CDATA section node to be created." }, { "code": null, "e": 10458, "s": 10267, "text": "The following example (createcdatanode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new CDATA section node, \"Create CDATA Example\" in the XML document." }, { "code": null, "e": 11242, "s": 10458, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n }\n else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_CDATA = xmlDoc.createCDATASection(\"Create CDATA Example\");\n\n x = xmlDoc.getElementsByTagName(\"Employee\")[0];\n x.appendChild(create_CDATA);\n document.write(x.lastChild.nodeValue);\n </script>\n </body>\n</html>" }, { "code": null, "e": 11265, "s": 11242, "text": "In the above example −" }, { "code": null, "e": 11387, "s": 11265, "text": "create_CDATA = xmlDoc.createCDATASection(\"Create CDATA Example\") creates a new CDATA section node, \"Create CDATA Example\"" }, { "code": null, "e": 11509, "s": 11387, "text": "create_CDATA = xmlDoc.createCDATASection(\"Create CDATA Example\") creates a new CDATA section node, \"Create CDATA Example\"" }, { "code": null, "e": 11640, "s": 11509, "text": "x.appendChild(create_CDATA) here, x holds the specified element <Employee> indexed at 0 to which the CDATA node value is appended." }, { "code": null, "e": 11771, "s": 11640, "text": "x.appendChild(create_CDATA) here, x holds the specified element <Employee> indexed at 0 to which the CDATA node value is appended." }, { "code": null, "e": 11971, "s": 11771, "text": "Save this file as createcdatanode_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the attribute value as Create CDATA Example." }, { "code": null, "e": 12139, "s": 11971, "text": "To create a new attribute node, the method setAttributeNode() is used. If the newly created attribute node exists in the element object, it is replaced by the new one." }, { "code": null, "e": 12196, "s": 12139, "text": "Syntax to use the createElement() method is as follows −" }, { "code": null, "e": 12243, "s": 12196, "text": "var_name = xmldoc.createAttribute(\"tagname\");\n" }, { "code": null, "e": 12250, "s": 12243, "text": "Where," }, { "code": null, "e": 12339, "s": 12250, "text": "var_name − is the user-defined variable name which holds the name of new attribute node." }, { "code": null, "e": 12428, "s": 12339, "text": "var_name − is the user-defined variable name which holds the name of new attribute node." }, { "code": null, "e": 12491, "s": 12428, "text": "(\"tagname\") − is the name of new attribute node to be created." }, { "code": null, "e": 12554, "s": 12491, "text": "(\"tagname\") − is the name of new attribute node to be created." }, { "code": null, "e": 12729, "s": 12554, "text": "The following example (createattributenode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new attribute node section in the XML document." }, { "code": null, "e": 13569, "s": 12729, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_a = xmlDoc.createAttribute(\"section\");\n create_a.nodeValue = \"A\";\n\n x = xmlDoc.getElementsByTagName(\"Employee\");\n x[0].setAttributeNode(create_a);\n document.write(\"New Attribute: \");\n document.write(x[0].getAttribute(\"section\"));\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 13592, "s": 13569, "text": "In the above example −" }, { "code": null, "e": 13682, "s": 13592, "text": "create_a=xmlDoc.createAttribute(\"Category\") creates an attribute with the name <section>." }, { "code": null, "e": 13772, "s": 13682, "text": "create_a=xmlDoc.createAttribute(\"Category\") creates an attribute with the name <section>." }, { "code": null, "e": 13855, "s": 13772, "text": "create_a.nodeValue=\"Management\" creates the value \"A\" for the attribute <section>." }, { "code": null, "e": 13938, "s": 13855, "text": "create_a.nodeValue=\"Management\" creates the value \"A\" for the attribute <section>." }, { "code": null, "e": 14043, "s": 13938, "text": "x[0].setAttributeNode(create_a) this attribute value is set to the node element <Employee> indexed at 0." }, { "code": null, "e": 14148, "s": 14043, "text": "x[0].setAttributeNode(create_a) this attribute value is set to the node element <Employee> indexed at 0." }, { "code": null, "e": 14181, "s": 14148, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 14203, "s": 14181, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 14238, "s": 14203, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 14260, "s": 14238, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 14293, "s": 14260, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 14306, "s": 14293, "text": " Zach Miller" }, { "code": null, "e": 14339, "s": 14306, "text": "\n 15 Lectures \n 4 hours \n" }, { "code": null, "e": 14363, "s": 14339, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 14396, "s": 14363, "text": "\n 13 Lectures \n 4 hours \n" }, { "code": null, "e": 14420, "s": 14396, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 14453, "s": 14420, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 14470, "s": 14453, "text": " Laurence Svekis" }, { "code": null, "e": 14477, "s": 14470, "text": " Print" }, { "code": null, "e": 14488, "s": 14477, "text": " Add Notes" } ]
JUnit - Quick Guide
Testing is the process of checking the functionality of an application to ensure it runs as per requirements. Unit testing comes into picture at the developers’ level; it is the testing of single entity (class or method). Unit testing plays a critical role in helping a software company deliver quality products to its customers. Unit testing can be done in two ways − manual testing and automated testing. JUnit is a unit testing framework for Java programming language. It plays a crucial role test-driven development, and is a family of unit testing frameworks collectively known as xUnit. JUnit promotes the idea of "first testing then coding", which emphasizes on setting up the test data for a piece of code that can be tested first and then implemented. This approach is like "test a little, code a little, test a little, code a little." It increases the productivity of the programmer and the stability of program code, which in turn reduces the stress on the programmer and the time spent on debugging. JUnit is an open source framework, which is used for writing and running tests. JUnit is an open source framework, which is used for writing and running tests. Provides annotations to identify test methods. Provides annotations to identify test methods. Provides assertions for testing expected results. Provides assertions for testing expected results. Provides test runners for running tests. Provides test runners for running tests. JUnit tests allow you to write codes faster, which increases quality. JUnit tests allow you to write codes faster, which increases quality. JUnit is elegantly simple. It is less complex and takes less time. JUnit is elegantly simple. It is less complex and takes less time. JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results. JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results. JUnit tests can be organized into test suites containing test cases and even other test suites. JUnit tests can be organized into test suites containing test cases and even other test suites. JUnit shows test progress in a bar that is green if the test is running smoothly, and it turns red when a test fails. JUnit shows test progress in a bar that is green if the test is running smoothly, and it turns red when a test fails. A Unit Test Case is a part of code, which ensures that another part of code (method) works as expected. To achieve the desired results quickly, a test framework is required. JUnit is a perfect unit test framework for Java programming language. A formal written unit test case is characterized by a known input and an expected output, which is worked out before the test is executed. The known input should test a precondition and the expected output should test a post-condition. There must be at least two unit test cases for each requirement − one positive test and one negative test. If a requirement has sub-requirements, each sub-requirement must have at least two test cases as positive and negative. JUnit is a framework for Java, so the very first requirement is to have JDK installed in your machine. First of all, open the console and execute a java command based on the operating system you are working on. Let's verify the output for all the operating systems − java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link https://www.oracle.com. We are assuming Java 1.8.0_101 as the installed version for this tutorial. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example. Append Java compiler location to the System Path. Verify Java installation using the command java -version as explained above. Download the latest version of JUnit jar file from http://www.junit.org. At the time of writing this tutorial, we have downloaded Junit-4.12.jar and copied it into C:\>JUnit folder. Set the JUNIT_HOME environment variable to point to the base directory location where JUNIT jar is stored on your machine. Let’s assuming we've stored junit4.12.jar in the JUNIT folder. Windows Set the environment variable JUNIT_HOME to C:\JUNIT Linux export JUNIT_HOME = /usr/local/JUNIT Mac export JUNIT_HOME = /Library/JUNIT Set the CLASSPATH environment variable to point to the JUNIT jar location. Windows Set the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%\junit4.12.jar;.; Linux export CLASSPATH = $CLASSPATH:$JUNIT_HOME/junit4.12.jar:. Mac export CLASSPATH = $CLASSPATH:$JUNIT_HOME/junit4.12.jar:. Create a java class file name TestJunit in C:\>JUNIT_WORKSPACE import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { @Test public void testAdd() { String str = "Junit is working fine"; assertEquals("Junit is working fine",str); } } Create a java class file name TestRunner in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the classes using javac compiler as follows − C:\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java Now run the Test Runner to see the result as follows − C:\JUNIT_WORKSPACE>java TestRunner Verify the output. true JUnit is a Regression Testing Framework used by developers to implement unit testing in Java, and accelerate programming speed and increase the quality of code. JUnit Framework can be easily integrated with either of the following − Eclipse Ant Maven JUnit test framework provides the following important features − Fixtures Test suites Test runners JUnit classes Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well-known and fixed environment in which tests are run so that results are repeatable. It includes − setUp() method, which runs before every test invocation. tearDown() method, which runs after every test method. Let's check one example − import junit.framework.*; public class JavaTest extends TestCase { protected int value1, value2; // assigning the values protected void setUp(){ value1 = 3; value2 = 3; } // test method to add two values public void testAdd(){ double result = value1 + value2; assertTrue(result == 6); } } A test suite bundles a few unit test cases and runs them together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test. Given below is an example that uses TestJunit1 & TestJunit2 test classes. import org.junit.runner.RunWith; import org.junit.runners.Suite; //JUnit Suite Test @RunWith(Suite.class) @Suite.SuiteClasses({ TestJunit1.class ,TestJunit2.class }) public class JunitTestSuite { } import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit1 { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); assertEquals(message, messageUtil.printMessage()); } } import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit2 { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Robert"; assertEquals(message,messageUtil.salutationMessage()); } } Test runner is used for executing the test cases. Here is an example that assumes the test class TestJunit already exists. import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } JUnit classes are important classes, used in writing and testing JUnits. Some of the important classes are − Assert − Contains a set of assert methods. Assert − Contains a set of assert methods. TestCase − Contains a test case that defines the fixture to run multiple tests. TestCase − Contains a test case that defines the fixture to run multiple tests. TestResult − Contains methods to collect the results of executing a test case. TestResult − Contains methods to collect the results of executing a test case. Let us now have a basic example to demonstrate the step-by-step process of using JUnit. Create a java class to be tested, say, MessageUtil.java in C:\>JUNIT_WORKSPACE /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public String printMessage(){ System.out.println(message); return message; } } Create a java test class, say, TestJunit.java. Add a test method testPrintMessage() to your test class. Add an Annotaion @Test to method testPrintMessage(). Implement the test condition and check the condition using assertEquals API of JUnit. Create a java class file name TestJunit.java in C:\>JUNIT_WORKSPACE. import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { String message = "Hello World"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { assertEquals(message,messageUtil.printMessage()); } } Create a TestRunner java class. Use runClasses method of JUnitCore class of JUnit to run the test case of the above created test class. Get the result of test cases run in Result Object. Get failure(s) using the getFailures() method of Result object. Get Success result using the wasSuccessful() method of Result object. Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the MessageUtil, Test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. Hello World true Now update TestJunit in C:\>JUNIT_WORKSPACE so that the test fails. Change the message string. import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { String message = "Hello World"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { message = "New Word"; assertEquals(message,messageUtil.printMessage()); } } Let's keep the rest of the classes as is, and try to run the same Test Runner. import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. Hello World testPrintMessage(TestJunit): expected:<[New Wor]d> but was:<[Hello Worl]d> false The most important package in JUnit is junit.framework, which contains all the core classes. Some of the important classes are as follows − Following is the declaration for org.junit.Assert class − public class Assert extends java.lang.Object This class provides a set of assertion methods useful for writing tests. Only failed assertions are recorded. Some of the important methods of Assert class are as follows − void assertEquals(boolean expected, boolean actual) Checks that two primitives/objects are equal. void assertFalse(boolean condition) Checks that a condition is false. void assertNotNull(Object object) Checks that an object isn't null. void assertNull(Object object) Checks that an object is null. void assertTrue(boolean condition) Checks that a condition is true. void fail() Fails a test with no message. Let's use some of the above-mentioned methods in an example. Create a java class file named TestJunit1.java in C:\>JUNIT_WORKSPACE. import org.junit.Test; import static org.junit.Assert.*; public class TestJunit1 { @Test public void testAdd() { //test data int num = 5; String temp = null; String str = "Junit is working fine"; //check for equality assertEquals("Junit is working fine", str); //check for false condition assertFalse(num > 6); //check for not null value assertNotNull(temp); } } Next, create a java class file named TestRunner1.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner1 { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit1.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac TestJunit1.java TestRunner1.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner1 Verify the output. true Following is the declaration for org.junit.TestCase class − public abstract class TestCase extends Assert implements Test A test case defines the fixture to run multiple tests. Some of the important methods of TestCase class are as follows − int countTestCases() Counts the number of test cases executed by run(TestResult result). TestResult createResult() Creates a default TestResult object. String getName() Gets the name of a TestCase. TestResult run() A convenience method to run this test, collecting the results with a default TestResult object. void run(TestResult result) Runs the test case and collects the results in TestResult. void setName(String name) Sets the name of a TestCase. void setUp() Sets up the fixture, for example, open a network connection. void tearDown() Tears down the fixture, for example, close a network connection. String toString() Returns a string representation of the test case. Let's use some of the above-mentioned methods in an example. Create a java class file named TestJunit2.java in C:\>JUNIT_WORKSPACE. import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; public class TestJunit2 extends TestCase { protected double fValue1; protected double fValue2; @Before public void setUp() { fValue1 = 2.0; fValue2 = 3.0; } @Test public void testAdd() { //count the number of test cases System.out.println("No of Test Case = "+ this.countTestCases()); //test getName String name = this.getName(); System.out.println("Test Case Name = "+ name); //test setName this.setName("testNewAdd"); String newName = this.getName(); System.out.println("Updated Test Case Name = "+ newName); } //tearDown used to close the connection or clean up activities public void tearDown( ) { } } Next, create a java class file named TestRunner2.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner2 { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit2.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac TestJunit2.java TestRunner2.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner2 Verify the output. No of Test Case = 1 Test Case Name = testAdd Updated Test Case Name = testNewAdd true Following is the declaration for org.junit.TestResult class − public class TestResult extends Object A TestResult collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test framework distinguishes between failures and errors. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like an ArrayIndexOutOfBoundsException. Some of the important methods of TestResult class are as follows − void addError(Test test, Throwable t) Adds an error to the list of errors. void addFailure(Test test, AssertionFailedError t) Adds a failure to the list of failures. void endTest(Test test) Informs the result that a test was completed. int errorCount() Gets the number of detected errors. Enumeration<TestFailure> errors() Returns an Enumeration for the errors. int failureCount() Gets the number of detected failures. void run(TestCase test) Runs a TestCase. int runCount() Gets the number of run tests. void startTest(Test test) Informs the result that a test will be started. void stop() Marks that the test run should stop. Create a java class file named TestJunit3.java in C:\>JUNIT_WORKSPACE. import org.junit.Test; import junit.framework.AssertionFailedError; import junit.framework.TestResult; public class TestJunit3 extends TestResult { // add the error public synchronized void addError(Test test, Throwable t) { super.addError((junit.framework.Test) test, t); } // add the failure public synchronized void addFailure(Test test, AssertionFailedError t) { super.addFailure((junit.framework.Test) test, t); } @Test public void testAdd() { // add any test } // Marks that the test run should stop. public synchronized void stop() { //stop the test here } } Next, create a java class file named TestRunner3.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner3 { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit3.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac TestJunit3.java TestRunner3.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner3 Verify the output. true Following is the declaration for org.junit.TestSuite class: public class TestSuite extends Object implements Test A TestSuite is a Composite of tests. It runs a collection of test cases. Some of the important methods of TestSuite class are as follows − void addTest(Test test) Adds a test to the suite. void addTestSuite(Class<? extends TestCase> testClass) Adds the tests from the given class to the suite. int countTestCases() Counts the number of test cases that will be run by this test. String getName() Returns the name of the suite. void run(TestResult result) Runs the tests and collects their result in a TestResult. void setName(String name) Sets the name of the suite. Test testAt(int index) Returns the test at the given index. int testCount() Returns the number of tests in this suite. static Test warning(String message) Returns a test which will fail and log a warning message. Create a java class file named JunitTestSuite.java in C:\>JUNIT_WORKSPACE to create Test suite. import junit.framework.*; public class JunitTestSuite { public static void main(String[] a) { // add the test's in the suite TestSuite suite = new TestSuite(TestJunit1.class, TestJunit2.class, TestJunit3.class ); TestResult result = new TestResult(); suite.run(result); System.out.println("Number of test cases = " + result.runCount()); } } Compile the Test suite classes using javac. C:\JUNIT_WORKSPACE>javac JunitTestSuite.java Now run the Test Suite. C:\JUNIT_WORKSPACE>java JunitTestSuite Verify the output. No of Test Case = 1 Test Case Name = testAdd Updated Test Case Name = testNewAdd Number of test cases = 3 Here we will see one complete example of JUnit testing using POJO class, Business logic class, and a test class, which will be run by the test runner. Create EmployeeDetails.java in C:\>JUNIT_WORKSPACE, which is a POJO class. public class EmployeeDetails { private String name; private double monthlySalary; private int age; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the monthlySalary */ public double getMonthlySalary() { return monthlySalary; } /** * @param monthlySalary the monthlySalary to set */ public void setMonthlySalary(double monthlySalary) { this.monthlySalary = monthlySalary; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } } EmployeeDetails class is used to − get/set the value of employee's name. get/set the value of employee's monthly salary. get/set the value of employee's age. Create a file called EmpBusinessLogic.java in C:\>JUNIT_WORKSPACE, which contains the business logic. public class EmpBusinessLogic { // Calculate the yearly salary of employee public double calculateYearlySalary(EmployeeDetails employeeDetails) { double yearlySalary = 0; yearlySalary = employeeDetails.getMonthlySalary() * 12; return yearlySalary; } // Calculate the appraisal amount of employee public double calculateAppraisal(EmployeeDetails employeeDetails) { double appraisal = 0; if(employeeDetails.getMonthlySalary() < 10000){ appraisal = 500; }else{ appraisal = 1000; } return appraisal; } } EmpBusinessLogic class is used for calculating − the yearly salary of an employee. the appraisal amount of an employee. Create a file called TestEmployeeDetails.java in C:\>JUNIT_WORKSPACE, which contains the test cases to be tested. import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestEmployeeDetails { EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic(); EmployeeDetails employee = new EmployeeDetails(); //test to check appraisal @Test public void testCalculateAppriasal() { employee.setName("Rajeev"); employee.setAge(25); employee.setMonthlySalary(8000); double appraisal = empBusinessLogic.calculateAppraisal(employee); assertEquals(500, appraisal, 0.0); } // test to check yearly salary @Test public void testCalculateYearlySalary() { employee.setName("Rajeev"); employee.setAge(25); employee.setMonthlySalary(8000); double salary = empBusinessLogic.calculateYearlySalary(employee); assertEquals(96000, salary, 0.0); } } TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It tests the yearly salary of the employee. tests the appraisal amount of the employee. Next, create a java class filed named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestEmployeeDetails.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac EmployeeDetails.java EmpBusinessLogic.java TestEmployeeDetails.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. true All the assertions are in the Assert class. public class Assert extends java.lang.Object This class provides a set of assertion methods, useful for writing tests. Only failed assertions are recorded. Some of the important methods of Assert class are as follows − void assertEquals(boolean expected, boolean actual) Checks that two primitives/objects are equal. void assertTrue(boolean condition) Checks that a condition is true. void assertFalse(boolean condition) Checks that a condition is false. void assertNotNull(Object object) Checks that an object isn't null. void assertNull(Object object) Checks that an object is null. void assertSame(object1, object2) The assertSame() method tests if two object references point to the same object. void assertNotSame(object1, object2) The assertNotSame() method tests if two object references do not point to the same object. void assertArrayEquals(expectedArray, resultArray); The assertArrayEquals() method will test whether two arrays are equal to each other. Let's use some of the above-mentioned methods in an example. Create a java class file named TestAssertions.java in C:\>JUNIT_WORKSPACE. import org.junit.Test; import static org.junit.Assert.*; public class TestAssertions { @Test public void testAssertions() { //test data String str1 = new String ("abc"); String str2 = new String ("abc"); String str3 = null; String str4 = "abc"; String str5 = "abc"; int val1 = 5; int val2 = 6; String[] expectedArray = {"one", "two", "three"}; String[] resultArray = {"one", "two", "three"}; //Check that two objects are equal assertEquals(str1, str2); //Check that a condition is true assertTrue (val1 < val2); //Check that a condition is false assertFalse(val1 > val2); //Check that an object isn't null assertNotNull(str1); //Check that an object is null assertNull(str3); //Check if two object references point to the same object assertSame(str4,str5); //Check if two object references not point to the same object assertNotSame(str1,str3); //Check whether two arrays are equal to each other. assertArrayEquals(expectedArray, resultArray); } } Next, create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner2 { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestAssertions.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the Test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac TestAssertions.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. true Annotations are like meta-tags that you can add to your code, and apply them to methods or in class. These annotations in JUnit provide the following information about test methods − which methods are going to run before and after test methods. which methods run before and after all the methods, and. which methods or classes will be ignored during the execution. The following table provides a list of annotations and their meaning in JUnit − @Test The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. @Before Several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before each Test method. @After If you allocate external resources in a Before method, you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. @BeforeClass Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class. @AfterClass This will perform the method after all tests have finished. This can be used to perform clean-up activities. @Ignore The Ignore annotation is used to ignore the test and that test will not be executed. Create a java class file named JunitAnnotation.java in C:\>JUNIT_WORKSPACE to test annotation. import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class JunitAnnotation { //execute before class @BeforeClass public static void beforeClass() { System.out.println("in before class"); } //execute after class @AfterClass public static void afterClass() { System.out.println("in after class"); } //execute before test @Before public void before() { System.out.println("in before"); } //execute after test @After public void after() { System.out.println("in after"); } //test case @Test public void test() { System.out.println("in test"); } //test case ignore and will not execute @Ignore public void ignoreTest() { System.out.println("in ignore test"); } } Next, create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute annotations. import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(JunitAnnotation.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the Test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac JunitAnnotation.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. in before class in before in test in after in after class true This chapter explains the execution procedure of methods in JUnit, which defines the order of the methods called. Discussed below is the execution procedure of the JUnit test API methods with example. Create a java class file named ExecutionProcedureJunit.java in C:\>JUNIT_WORKSPACE to test annotation. import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class ExecutionProcedureJunit { //execute only once, in the starting @BeforeClass public static void beforeClass() { System.out.println("in before class"); } //execute only once, in the end @AfterClass public static void afterClass() { System.out.println("in after class"); } //execute for each test, before executing test @Before public void before() { System.out.println("in before"); } //execute for each test, after executing test @After public void after() { System.out.println("in after"); } //test case 1 @Test public void testCase1() { System.out.println("in test case 1"); } //test case 2 @Test public void testCase2() { System.out.println("in test case 2"); } } Next, create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute annotations. import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(ExecutionProcedureJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the Test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac ExecutionProcedureJunit.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. in before class in before in test case 1 in after in before in test case 2 in after in after class See the above output. The execution procedure is as follows − First of all, the beforeClass() method executes only once. The afterClass() method executes only once. The before() method executes for each test case, but before executing the test case. The after() method executes for each test case, but after the execution of test case. In between before() and after(), each test case executes. The test cases are executed using JUnitCore class. JUnitCore is a facade for running tests. It supports running JUnit 4 tests, JUnit 3.8.x tests, and mixtures. To run tests from the command line, run java org.junit.runner.JUnitCore <TestClass>. For one-shot test runs, use the static method runClasses(Class[]). Following is the declaration for org.junit.runner.JUnitCore class: public class JUnitCore extends java.lang.Object Here we will see how to execute the tests with the help of JUnitCore. Create a java class to be tested, say, MessageUtil.java, in C:\>JUNIT_WORKSPACE. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public String printMessage(){ System.out.println(message); return message; } } Create a java test class, say, TestJunit.java. Create a java test class, say, TestJunit.java. Add a test method testPrintMessage() to your test class. Add a test method testPrintMessage() to your test class. Add an Annotaion @Test to the method testPrintMessage(). Add an Annotaion @Test to the method testPrintMessage(). Implement the test condition and check the condition using assertEquals API of JUnit. Implement the test condition and check the condition using assertEquals API of JUnit. Create a java class file named TestJunit.java in C:\>JUNIT_WORKSPACE. import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { String message = "Hello World"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { assertEquals(message,messageUtil.printMessage()); } } Now create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter. import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the Test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. Hello World true Test suite is used to bundle a few unit test cases and run them together. In JUnit, both @RunWith and @Suite annotations are used to run the suite tests. This chapter takes an example having two test classes, TestJunit1 & TestJunit2, that run together using Test Suite. Create a java class to be tested, say, MessageUtil.java in C:\>JUNIT_WORKSPACE. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public String printMessage(){ System.out.println(message); return message; } // add "Hi!" to the message public String salutationMessage(){ message = "Hi!" + message; System.out.println(message); return message; } } Create a java class file named TestJunit1.java in C:\>JUNIT_WORKSPACE. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit1 { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); assertEquals(message, messageUtil.printMessage()); } } Create a java class file named TestJunit2.java in C:\>JUNIT_WORKSPACE. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit2 { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Robert"; assertEquals(message,messageUtil.salutationMessage()); } } Create a java class. Attach @RunWith(Suite.class) Annotation with the class. Add reference to JUnit test classes using @Suite.SuiteClasses annotation. Create a java class file named TestSuite.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestJunit1.class, TestJunit2.class }) public class JunitTestSuite { } Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(JunitTestSuite.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile all the java classes using javac. C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit1.java TestJunit2.java JunitTestSuite.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. Inside testPrintMessage() Robert Inside testSalutationMessage() Hi Robert true Sometimes it so happens that our code is not completely ready while running a test case. As a result, the test case fails. The @Ignore annotation helps in this scenario. A test method annotated with @Ignore will not be executed. A test method annotated with @Ignore will not be executed. If a test class is annotated with @Ignore, then none of its test methods will be executed. If a test class is annotated with @Ignore, then none of its test methods will be executed. Now let's see @Ignore in action. Create a java class to be tested, say, MessageUtil.java in C:\>JUNIT_WORKSPACE. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public String printMessage(){ System.out.println(message); return message; } // add "Hi!" to the message public String salutationMessage(){ message = "Hi!" + message; System.out.println(message); return message; } } Create a java test class, say, TestJunit.java. Create a java test class, say, TestJunit.java. Add a test method testPrintMessage() or testSalutationMessage() to your test class. Add a test method testPrintMessage() or testSalutationMessage() to your test class. Add an Annotaion @Ignore to method testPrintMessage(). Add an Annotaion @Ignore to method testPrintMessage(). Create a java class file named TestJunit.java in C:\ JUNIT_WORKSPACE. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Ignore @Test public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); message = "Robert"; assertEquals(message,messageUtil.printMessage()); } @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Robert"; assertEquals(message,messageUtil.salutationMessage()); } } Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the MessageUtil, Test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java Now run the Test Runner, which will not run the testPrintMessage() test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. testPrintMessage() test case is not tested. Inside testSalutationMessage() Hi!Robert true Now, update TestJunit in C:\>JUNIT_WORKSPACE to ignore all test cases. Add @Ignore at class level. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; @Ignore public class TestJunit { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); message = "Robert"; assertEquals(message,messageUtil.printMessage()); } @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Robert"; assertEquals(message,messageUtil.salutationMessage()); } } Compile the test case using javac. C:\JUNIT_WORKSPACE>javac TestJunit.java Keep your Test Runner unchanged as follows − import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Now run the Test Runner, which will not run any test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. No test case is tested. true JUnit provides a handy option of Timeout. If a test case takes more time than the specified number of milliseconds, then JUnit will automatically mark it as failed. The timeout parameter is used along with @Test annotation. Let us see the @Test(timeout) in action. Create a java class to be tested, say, MessageUtil.java in C:\>JUNIT_WORKSPACE. Add an infinite while loop inside the printMessage() method. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public void printMessage(){ System.out.println(message); while(true); } // add "Hi!" to the message public String salutationMessage(){ message = "Hi!" + message; System.out.println(message); return message; } } Create a java test class, say, TestJunit.java. Add a timeout of 1000 to testPrintMessage() test case. Create a java class file named TestJunit.java in C:\>JUNIT_WORKSPACE. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test(timeout = 1000) public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); messageUtil.printMessage(); } @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Robert"; assertEquals(message,messageUtil.salutationMessage()); } } Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the MessageUtil, Test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java Now run the Test Runner, which will run the test cases defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. testPrintMessage() test case will mark the unit testing failed. Inside testPrintMessage() Robert Inside testSalutationMessage() Hi!Robert testPrintMessage(TestJunit): test timed out after 1000 milliseconds false JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation. Let us see @Test(expected) in action. Create a java class to be tested, say, MessageUtil.java in C:\> JUNIT_WORKSPACE. Add an error condition inside the printMessage() method. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public void printMessage(){ System.out.println(message); int a = 0; int b = 1/a; } // add "Hi!" to the message public String salutationMessage(){ message = "Hi!" + message; System.out.println(message); return message; } } Create a java test class called TestJunit.java. Add an expected exception ArithmeticException to the testPrintMessage() test case. Create a java class file named TestJunit.java in C:\>JUNIT_WORKSPACE. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test(expected = ArithmeticException.class) public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); messageUtil.printMessage(); } @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Robert"; assertEquals(message,messageUtil.salutationMessage()); } } Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the MessageUtil, Test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java Now run the Test Runner, which will run the test cases defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. testPrintMessage() test case will be passed. Inside testPrintMessage() Robert Inside testSalutationMessage() Hi!Robert true JUnit 4 has introduced a new feature called parameterized tests. Parameterized tests allow a developer to run the same test over and over again using different values. There are five steps that you need to follow to create a parameterized test. Annotate test class with @RunWith(Parameterized.class). Annotate test class with @RunWith(Parameterized.class). Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set. Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set. Create a public constructor that takes in what is equivalent to one "row" of test data. Create a public constructor that takes in what is equivalent to one "row" of test data. Create an instance variable for each "column" of test data. Create an instance variable for each "column" of test data. Create your test case(s) using the instance variables as the source of the test data. Create your test case(s) using the instance variables as the source of the test data. The test case will be invoked once for each row of data. Let us see parameterized tests in action. Create a java class to be tested, say, PrimeNumberChecker.java in C:\>JUNIT_WORKSPACE. public class PrimeNumberChecker { public Boolean validate(final Integer primeNumber) { for (int i = 2; i < (primeNumber / 2); i++) { if (primeNumber % i == 0) { return false; } } return true; } } Create a java test class, say, PrimeNumberCheckerTest.java. Create a java class file named PrimeNumberCheckerTest.java in C:\>JUNIT_WORKSPACE. import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.Before; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class PrimeNumberCheckerTest { private Integer inputNumber; private Boolean expectedResult; private PrimeNumberChecker primeNumberChecker; @Before public void initialize() { primeNumberChecker = new PrimeNumberChecker(); } // Each parameter should be placed as an argument here // Every time runner triggers, it will pass the arguments // from parameters we defined in primeNumbers() method public PrimeNumberCheckerTest(Integer inputNumber, Boolean expectedResult) { this.inputNumber = inputNumber; this.expectedResult = expectedResult; } @Parameterized.Parameters public static Collection primeNumbers() { return Arrays.asList(new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false }, { 23, true } }); } // This test will run 4 times since we have 5 parameters defined @Test public void testPrimeNumberChecker() { System.out.println("Parameterized Number is : " + inputNumber); assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); } } Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(PrimeNumberCheckerTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the PrimeNumberChecker, PrimeNumberCheckerTest and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac PrimeNumberChecker.java PrimeNumberCheckerTest.java TestRunner.java Now run the Test Runner, which will run the test cases defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. Parameterized Number is : 2 Parameterized Number is : 6 Parameterized Number is : 19 Parameterized Number is : 22 Parameterized Number is : 23 true We will have an example to demonstrate how to run JUnit using ANT. Follow the steps given below. Download Apache Ant based on the operating system you are working on. Set the ANT_HOME environment variable to point to the base directory location, where the ANT libraries are stored on your machine. Let us assume the Ant libraries are stored in the folder apache-ant-1.8.4. Windows Set the environment variable ANT_HOME to C:\Program Files\Apache Software Foundation\apache-ant-1.8.4 Linux export ANT_HOME = /usr/local/apache-ant-1.8.4 Mac export ANT_HOME = /Library/apache-ant-1.8.4 Append Ant compiler location to the System Path as follows − Download a JUnit Archive that suits your operating system. Create a folder TestJunitWithAnt in C:\>JUNIT_WORKSPACE. Create a folder TestJunitWithAnt in C:\>JUNIT_WORKSPACE. Create a folder src in C:\>JUNIT_WORKSPACE>TestJunitWithAnt. Create a folder src in C:\>JUNIT_WORKSPACE>TestJunitWithAnt. Create a folder test in C:\>JUNIT_WORKSPACE>TestJunitWithAnt. Create a folder test in C:\>JUNIT_WORKSPACE>TestJunitWithAnt. Create a folder lib in C:\>JUNIT_WORKSPACE>TestJunitWithAnt. Create a folder lib in C:\>JUNIT_WORKSPACE>TestJunitWithAnt. Create MessageUtil class in C:\>JUNIT_WORKSPACE>TestJunitWithAnt> srcfolder. Create MessageUtil class in C:\>JUNIT_WORKSPACE>TestJunitWithAnt> srcfolder. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public String printMessage(){ System.out.println(message); return message; } // add "Hi!" to the message public String salutationMessage(){ message = "Hi!" + message; System.out.println(message); return message; } } Create TestMessageUtil class in the folder C:\>JUNIT_WORKSPACE>TestJunitWithAnt>src. import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestMessageUtil { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); assertEquals(message,messageUtil.printMessage()); } @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Robert"; assertEquals(message,messageUtil.salutationMessage()); } } Copy junit-4.10.jar onto the folder C:\>JUNIT_WORKSPACE>TestJunitWithAnt>lib. We'll be using <junit> task in Ant to execute our JUnit test cases. <project name = "JunitTest" default = "test" basedir = "."> <property name = "testdir" location = "test" /> <property name = "srcdir" location = "src" /> <property name = "full-compile" value = "true" /> <path id = "classpath.base"/> <path id = "classpath.test"> <pathelement location = "lib/junit-4.10.jar" /> <pathelement location = "${testdir}" /> <pathelement location = "${srcdir}" /> <path refid = "classpath.base" /> </path> <target name = "clean" > <delete verbose = "${full-compile}"> <fileset dir = "${testdir}" includes = "**/*.class" /> </delete> </target> <target name = "compile" depends = "clean"> <javac srcdir = "${srcdir}" destdir = "${testdir}" verbose = "${full-compile}"> <classpath refid = "classpath.test"/> </javac> </target> <target name = "test" depends = "compile"> <junit> <classpath refid = "classpath.test" /> <formatter type = "brief" usefile = "false" /> <test name = "TestMessageUtil" /> </junit> </target> </project> Run the following Ant command. C:\JUNIT_WORKSPACE\TestJunitWithAnt>ant Verify the output. Buildfile: C:\JUNIT_WORKSPACE\TestJunitWithAnt\build.xml clean: compile: [javac] Compiling 2 source files to C:\JUNIT_WORKSPACE\TestJunitWithAnt\test [javac] [parsing started C:\JUNIT_WORKSPACE\TestJunitWithAnt\src\ MessageUtil.java] [javac] [parsing completed 18ms] [javac] [parsing started C:\JUNIT_WORKSPACE\TestJunitWithAnt\src\ TestMessageUtil.java] [javac] [parsing completed 2ms] [javac] [search path for source files: C:\JUNIT_WORKSPACE\ TestJunitWithAnt\src] [javac] [loading java\lang\Object.class(java\lang:Object.class)] [javac] [loading java\lang\String.class(java\lang:String.class)] [javac] [loading org\junit\Test.class(org\junit:Test.class)] [javac] [loading org\junit\Ignore.class(org\junit:Ignore.class)] [javac] [loading org\junit\Assert.class(org\junit:Assert.class)] [javac] [loading java\lang\annotation\Retention.class (java\lang\annotation:Retention.class)] [javac] [loading java\lang\annotation\RetentionPolicy.class (java\lang\annotation:RetentionPolicy.class)] [javac] [loading java\lang\annotation\Target.class (java\lang\annotation:Target.class)] [javac] [loading java\lang\annotation\ElementType.class (java\lang\annotation:ElementType.class)] [javac] [loading java\lang\annotation\Annotation.class (java\lang\annotation:Annotation.class)] [javac] [checking MessageUtil] [javac] [loading java\lang\System.class(java\lang:System.class)] [javac] [loading java\io\PrintStream.class(java\io:PrintStream.class)] [javac] [loading java\io\FilterOutputStream.class (java\io:FilterOutputStream.class)] [javac] [loading java\io\OutputStream.class(java\io:OutputStream.class)] [javac] [loading java\lang\StringBuilder.class (java\lang:StringBuilder.class)] [javac] [loading java\lang\AbstractStringBuilder.class (java\lang:AbstractStringBuilder.class)] [javac] [loading java\lang\CharSequence.class(java\lang:CharSequence.class)] [javac] [loading java\io\Serializable.class(java\io:Serializable.class)] [javac] [loading java\lang\Comparable.class(java\lang:Comparable.class)] [javac] [loading java\lang\StringBuffer.class(java\lang:StringBuffer.class)] [javac] [wrote C:\JUNIT_WORKSPACE\TestJunitWithAnt\test\MessageUtil.class] [javac] [checking TestMessageUtil] [javac] [wrote C:\JUNIT_WORKSPACE\TestJunitWithAnt\test\TestMessageUtil.class] [javac] [total 281ms] test: [junit] Testsuite: TestMessageUtil [junit] Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 0.008 sec [junit] [junit] ------------- Standard Output --------------- [junit] Inside testPrintMessage() [junit] Robert [junit] Inside testSalutationMessage() [junit] Hi!Robert [junit] ------------- ---------------- --------------- BUILD SUCCESSFUL Total time: 0 seconds To set up JUnit with eclipse, follow the steps given below. Download a JUnit jar based on the operating system you have on your system. Assume you have copied the above JAR file onto the folder C:\>JUnit. Open eclipse → right click on project and click on property > Build Path > Configure Build Path and add the junit-4.10.jar in the libraries using the button Add External Jar. We assume that your Eclipse has inbuilt JUnit plugin. If it is not available in C:\>eclipse\plugins directory, then you can download it from JUnit Plugin. Unzip the downloaded zip file in the plugin folder of the Eclipse. Finally restart Eclipse. Now your Eclipse is ready for the development of JUnit test cases. Create a project TestJunit in Eclipse at any location. Then create a class MessageUtil to test in the project. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message){ this.message = message; } // prints the message public String printMessage(){ System.out.println(message); return message; } } Create a test class TestJunit in the project. import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { String message = "Hello World"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { assertEquals(message,messageUtil.printMessage()); } } Following should be the project structure − Finally, right click the program and run as JUnit to verify the output of the program. Verify the result. Following are the JUnit extensions − Cactus JWebUnit XMLUnit MockObject Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs, Filters). The intent of Cactus is to lower the cost of writing tests for server-side code. It uses JUnit and extends it. Cactus implements an in-container strategy that executes the tests inside a container. Cactus ecosystem is made of several components − Cactus Framework is the heart of Cactus. It is the engine that provides the API to write Cactus tests. Cactus Framework is the heart of Cactus. It is the engine that provides the API to write Cactus tests. Cactus Integration Modules are front-ends and frameworks that provide easy ways of using the Cactus Framework (Ant scripts, Eclipse plugin, and Maven plugin). Cactus Integration Modules are front-ends and frameworks that provide easy ways of using the Cactus Framework (Ant scripts, Eclipse plugin, and Maven plugin). The following code demonstrates how Cactus can be used. import org.apache.cactus.*; import junit.framework.*; public class TestSampleServlet extends ServletTestCase { @Test public void testServlet() { // Initialize class to test SampleServlet servlet = new SampleServlet(); // Set a variable in session as the doSomething() // method that we are testing session.setAttribute("name", "value"); // Call the method to test, passing an // HttpServletRequest object (for example) String result = servlet.doSomething(request); // Perform verification that test was successful assertEquals("something", result); assertEquals("otherValue", session.getAttribute("otherName")); } } JWebUnit is a Java-based testing framework for web applications. It wraps existing testing frameworks such as HtmlUnit and Selenium with a unified, simple testing interface to test the correctness of your web applications. JWebUnit provides a high-level Java API for navigating a web application combined with a set of assertions to verify the application's correctness. This includes navigation via links, form entry and submission, validation of table contents, and other typical business web application features. The simple navigation methods and ready-to-use assertions allow for more rapid test creation than using only JUnit or HtmlUnit. And if you want to switch from HtmlUnit to other plugins such as Selenium (available soon), there is no need to rewrite your tests. Here is a sample code. import junit.framework.TestCase; import net.sourceforge.jwebunit.WebTester; public class ExampleWebTestCase extends TestCase { private WebTester tester; public ExampleWebTestCase(String name) { super(name); tester = new WebTester(); } //set base url public void setUp() throws Exception { getTestContext().setBaseUrl("http://myserver:8080/myapp"); } // test base info @Test public void testInfoPage() { beginAt("/info.html"); } } XMLUnit provides a single JUnit extension class, XMLTestCase, and a set of supporting classes that allow assertions to be made about − The differences between two pieces of XML (via Diff and DetailedDiff classes). The differences between two pieces of XML (via Diff and DetailedDiff classes). The validity of a piece of XML (via Validator class). The validity of a piece of XML (via Validator class). The outcome of transforming a piece of XML using XSLT (via Transform class). The outcome of transforming a piece of XML using XSLT (via Transform class). The evaluation of an XPath expression on a piece of XML (via classes implementing the XpathEngine interface). The evaluation of an XPath expression on a piece of XML (via classes implementing the XpathEngine interface). Individual nodes in a piece of XML that are exposed by DOM Traversal (via NodeTest class). Individual nodes in a piece of XML that are exposed by DOM Traversal (via NodeTest class). Let us assume we have two pieces of XML that we wish to compare and assert that they are equal. We could write a simple test class like this − import org.custommonkey.xmlunit.XMLTestCase; public class MyXMLTestCase extends XMLTestCase { // this test method compare two pieces of the XML @Test public void testForXMLEquality() throws Exception { String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>"; String myTestXML = "<msg><localId>2376</localId></msg>"; assertXMLEqual("Comparing test xml to control xml", myControlXML, myTestXML); } } In a unit test, mock objects can simulate the behavior of complex, real (non-mock) objects and are therefore useful when a real object is impractical or impossible to incorporate into a unit test. The common coding style for testing with mock objects is to − Create instances of mock objects. Set state and expectations in the mock objects. Invoke domain code with mock objects as parameters. Verify consistency in the mock objects. Given below is an example of MockObject using Jmock. import org.jmock.Mockery; import org.jmock.Expectations; class PubTest extends TestCase { Mockery context = new Mockery(); public void testSubReceivesMessage() { // set up final Sub sub = context.mock(Sub.class); Pub pub = new Pub(); pub.add(sub); final String message = "message"; // expectations context.checking(new Expectations() { oneOf (sub).receive(message); }); // execute pub.publish(message); // verify context.assertIsSatisfied(); } } 24 Lectures 2.5 hours Nishita Bhatt 56 Lectures 7.5 hours Dinesh Varyani Print Add Notes Bookmark this page
[ { "code": null, "e": 2302, "s": 1972, "text": "Testing is the process of checking the functionality of an application to ensure it runs as per requirements. Unit testing comes into picture at the developers’ level; it is the testing of single entity (class or method). Unit testing plays a critical role in helping a software company deliver quality products to its customers." }, { "code": null, "e": 2379, "s": 2302, "text": "Unit testing can be done in two ways − manual testing and automated testing." }, { "code": null, "e": 2566, "s": 2379, "text": " JUnit is a unit testing framework for Java programming language. It plays a crucial role test-driven development, and is a family of unit testing frameworks collectively known as xUnit." }, { "code": null, "e": 2985, "s": 2566, "text": "JUnit promotes the idea of \"first testing then coding\", which emphasizes on setting up the test data for a piece of code that can be tested first and then implemented. This approach is like \"test a little, code a little, test a little, code a little.\" It increases the productivity of the programmer and the stability of program code, which in turn reduces the stress on the programmer and the time spent on debugging." }, { "code": null, "e": 3065, "s": 2985, "text": "JUnit is an open source framework, which is used for writing and running tests." }, { "code": null, "e": 3145, "s": 3065, "text": "JUnit is an open source framework, which is used for writing and running tests." }, { "code": null, "e": 3192, "s": 3145, "text": "Provides annotations to identify test methods." }, { "code": null, "e": 3239, "s": 3192, "text": "Provides annotations to identify test methods." }, { "code": null, "e": 3289, "s": 3239, "text": "Provides assertions for testing expected results." }, { "code": null, "e": 3339, "s": 3289, "text": "Provides assertions for testing expected results." }, { "code": null, "e": 3380, "s": 3339, "text": "Provides test runners for running tests." }, { "code": null, "e": 3421, "s": 3380, "text": "Provides test runners for running tests." }, { "code": null, "e": 3491, "s": 3421, "text": "JUnit tests allow you to write codes faster, which increases quality." }, { "code": null, "e": 3561, "s": 3491, "text": "JUnit tests allow you to write codes faster, which increases quality." }, { "code": null, "e": 3628, "s": 3561, "text": "JUnit is elegantly simple. It is less complex and takes less time." }, { "code": null, "e": 3695, "s": 3628, "text": "JUnit is elegantly simple. It is less complex and takes less time." }, { "code": null, "e": 3864, "s": 3695, "text": "JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results." }, { "code": null, "e": 4033, "s": 3864, "text": "JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results." }, { "code": null, "e": 4129, "s": 4033, "text": "JUnit tests can be organized into test suites containing test cases and even other test suites." }, { "code": null, "e": 4225, "s": 4129, "text": "JUnit tests can be organized into test suites containing test cases and even other test suites." }, { "code": null, "e": 4343, "s": 4225, "text": "JUnit shows test progress in a bar that is green if the test is running smoothly, and it turns red when a test fails." }, { "code": null, "e": 4461, "s": 4343, "text": "JUnit shows test progress in a bar that is green if the test is running smoothly, and it turns red when a test fails." }, { "code": null, "e": 4705, "s": 4461, "text": "A Unit Test Case is a part of code, which ensures that another part of code (method) works as expected. To achieve the desired results quickly, a test framework is required. JUnit is a perfect unit test framework for Java programming language." }, { "code": null, "e": 4941, "s": 4705, "text": "A formal written unit test case is characterized by a known input and an expected output, which is worked out before the test is executed. The known input should test a precondition and the expected output should test a post-condition." }, { "code": null, "e": 5168, "s": 4941, "text": "There must be at least two unit test cases for each requirement − one positive test and one negative test. If a requirement has sub-requirements, each sub-requirement must have at least two test cases as positive and negative." }, { "code": null, "e": 5271, "s": 5168, "text": "JUnit is a framework for Java, so the very first requirement is to have JDK installed in your machine." }, { "code": null, "e": 5379, "s": 5271, "text": "First of all, open the console and execute a java command based on the operating system you are working on." }, { "code": null, "e": 5435, "s": 5379, "text": "Let's verify the output for all the operating systems −" }, { "code": null, "e": 5460, "s": 5435, "text": "java version \"1.8.0_101\"" }, { "code": null, "e": 5510, "s": 5460, "text": "Java(TM) SE Runtime Environment (build 1.8.0_101)" }, { "code": null, "e": 5535, "s": 5510, "text": "java version \"1.8.0_101\"" }, { "code": null, "e": 5585, "s": 5535, "text": "Java(TM) SE Runtime Environment (build 1.8.0_101)" }, { "code": null, "e": 5610, "s": 5585, "text": "java version \"1.8.0_101\"" }, { "code": null, "e": 5660, "s": 5610, "text": "Java(TM) SE Runtime Environment (build 1.8.0_101)" }, { "code": null, "e": 5887, "s": 5660, "text": "If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link https://www.oracle.com. We are assuming Java 1.8.0_101 as the installed version for this tutorial." }, { "code": null, "e": 6020, "s": 5887, "text": "Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example." }, { "code": null, "e": 6070, "s": 6020, "text": "Append Java compiler location to the System Path." }, { "code": null, "e": 6147, "s": 6070, "text": "Verify Java installation using the command java -version as explained above." }, { "code": null, "e": 6329, "s": 6147, "text": "Download the latest version of JUnit jar file from http://www.junit.org. At the time of writing this tutorial, we have downloaded Junit-4.12.jar and copied it into C:\\>JUnit folder." }, { "code": null, "e": 6515, "s": 6329, "text": "Set the JUNIT_HOME environment variable to point to the base directory location where JUNIT jar is stored on your machine. Let’s assuming we've stored junit4.12.jar in the JUNIT folder." }, { "code": null, "e": 6523, "s": 6515, "text": "Windows" }, { "code": null, "e": 6575, "s": 6523, "text": "Set the environment variable JUNIT_HOME to C:\\JUNIT" }, { "code": null, "e": 6581, "s": 6575, "text": "Linux" }, { "code": null, "e": 6618, "s": 6581, "text": "export JUNIT_HOME = /usr/local/JUNIT" }, { "code": null, "e": 6622, "s": 6618, "text": "Mac" }, { "code": null, "e": 6657, "s": 6622, "text": "export JUNIT_HOME = /Library/JUNIT" }, { "code": null, "e": 6732, "s": 6657, "text": "Set the CLASSPATH environment variable to point to the JUNIT jar location." }, { "code": null, "e": 6740, "s": 6732, "text": "Windows" }, { "code": null, "e": 6824, "s": 6740, "text": "Set the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%\\junit4.12.jar;.;" }, { "code": null, "e": 6830, "s": 6824, "text": "Linux" }, { "code": null, "e": 6888, "s": 6830, "text": "export CLASSPATH = $CLASSPATH:$JUNIT_HOME/junit4.12.jar:." }, { "code": null, "e": 6892, "s": 6888, "text": "Mac" }, { "code": null, "e": 6950, "s": 6892, "text": "export CLASSPATH = $CLASSPATH:$JUNIT_HOME/junit4.12.jar:." }, { "code": null, "e": 7013, "s": 6950, "text": "Create a java class file name TestJunit in C:\\>JUNIT_WORKSPACE" }, { "code": null, "e": 7245, "s": 7013, "text": "import org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n @Test\n\t\n public void testAdd() {\n String str = \"Junit is working fine\";\n assertEquals(\"Junit is working fine\",str);\n }\n}" }, { "code": null, "e": 7334, "s": 7245, "text": "Create a java class file name TestRunner in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 7755, "s": 7334, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 7809, "s": 7755, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 7866, "s": 7809, "text": "C:\\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java\n" }, { "code": null, "e": 7921, "s": 7866, "text": "Now run the Test Runner to see the result as follows −" }, { "code": null, "e": 7957, "s": 7921, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 7976, "s": 7957, "text": "Verify the output." }, { "code": null, "e": 7982, "s": 7976, "text": "true\n" }, { "code": null, "e": 8215, "s": 7982, "text": "JUnit is a Regression Testing Framework used by developers to implement unit testing in Java, and accelerate programming speed and increase the quality of code. JUnit Framework can be easily integrated with either of the following −" }, { "code": null, "e": 8223, "s": 8215, "text": "Eclipse" }, { "code": null, "e": 8227, "s": 8223, "text": "Ant" }, { "code": null, "e": 8233, "s": 8227, "text": "Maven" }, { "code": null, "e": 8298, "s": 8233, "text": "JUnit test framework provides the following important features −" }, { "code": null, "e": 8307, "s": 8298, "text": "Fixtures" }, { "code": null, "e": 8319, "s": 8307, "text": "Test suites" }, { "code": null, "e": 8332, "s": 8319, "text": "Test runners" }, { "code": null, "e": 8346, "s": 8332, "text": "JUnit classes" }, { "code": null, "e": 8591, "s": 8346, "text": "Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well-known and fixed environment in which tests are run so that results are repeatable. It includes −" }, { "code": null, "e": 8648, "s": 8591, "text": "setUp() method, which runs before every test invocation." }, { "code": null, "e": 8703, "s": 8648, "text": "tearDown() method, which runs after every test method." }, { "code": null, "e": 8729, "s": 8703, "text": "Let's check one example −" }, { "code": null, "e": 9069, "s": 8729, "text": "import junit.framework.*;\n\npublic class JavaTest extends TestCase {\n protected int value1, value2;\n \n // assigning the values\n protected void setUp(){\n value1 = 3;\n value2 = 3;\n }\n\n // test method to add two values\n public void testAdd(){\n double result = value1 + value2;\n assertTrue(result == 6);\n }\n}" }, { "code": null, "e": 9288, "s": 9069, "text": "A test suite bundles a few unit test cases and runs them together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test. Given below is an example that uses TestJunit1 & TestJunit2 test classes." }, { "code": null, "e": 9493, "s": 9288, "text": "import org.junit.runner.RunWith;\nimport org.junit.runners.Suite;\n\n//JUnit Suite Test\n@RunWith(Suite.class)\n\[email protected]({ \n TestJunit1.class ,TestJunit2.class\n})\n\npublic class JunitTestSuite {\n}" }, { "code": null, "e": 9878, "s": 9493, "text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit1 {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test\n public void testPrintMessage() {\t\n System.out.println(\"Inside testPrintMessage()\"); \n assertEquals(message, messageUtil.printMessage()); \n }\n}" }, { "code": null, "e": 10299, "s": 9878, "text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit2 {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n}" }, { "code": null, "e": 10422, "s": 10299, "text": "Test runner is used for executing the test cases. Here is an example that assumes the test class TestJunit already exists." }, { "code": null, "e": 10840, "s": 10422, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n}" }, { "code": null, "e": 10949, "s": 10840, "text": "JUnit classes are important classes, used in writing and testing JUnits. Some of the important classes are −" }, { "code": null, "e": 10992, "s": 10949, "text": "Assert − Contains a set of assert methods." }, { "code": null, "e": 11035, "s": 10992, "text": "Assert − Contains a set of assert methods." }, { "code": null, "e": 11115, "s": 11035, "text": "TestCase − Contains a test case that defines the fixture to run multiple tests." }, { "code": null, "e": 11195, "s": 11115, "text": "TestCase − Contains a test case that defines the fixture to run multiple tests." }, { "code": null, "e": 11274, "s": 11195, "text": "TestResult − Contains methods to collect the results of executing a test case." }, { "code": null, "e": 11353, "s": 11274, "text": "TestResult − Contains methods to collect the results of executing a test case." }, { "code": null, "e": 11441, "s": 11353, "text": "Let us now have a basic example to demonstrate the step-by-step process of using JUnit." }, { "code": null, "e": 11520, "s": 11441, "text": "Create a java class to be tested, say, MessageUtil.java in C:\\>JUNIT_WORKSPACE" }, { "code": null, "e": 11894, "s": 11520, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n\t\n public MessageUtil(String message){\n this.message = message;\n }\n \n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n} " }, { "code": null, "e": 11941, "s": 11894, "text": "Create a java test class, say, TestJunit.java." }, { "code": null, "e": 11998, "s": 11941, "text": "Add a test method testPrintMessage() to your test class." }, { "code": null, "e": 12051, "s": 11998, "text": "Add an Annotaion @Test to method testPrintMessage()." }, { "code": null, "e": 12137, "s": 12051, "text": "Implement the test condition and check the condition using assertEquals API of JUnit." }, { "code": null, "e": 12206, "s": 12137, "text": "Create a java class file name TestJunit.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 12502, "s": 12206, "text": "import org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\t\n String message = \"Hello World\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testPrintMessage() {\n assertEquals(message,messageUtil.printMessage());\n }\n}" }, { "code": null, "e": 12534, "s": 12502, "text": "Create a TestRunner java class." }, { "code": null, "e": 12638, "s": 12534, "text": "Use runClasses method of JUnitCore class of JUnit to run the test case of the above created test class." }, { "code": null, "e": 12689, "s": 12638, "text": "Get the result of test cases run in Result Object." }, { "code": null, "e": 12753, "s": 12689, "text": "Get failure(s) using the getFailures() method of Result object." }, { "code": null, "e": 12823, "s": 12753, "text": "Get Success result using the wasSuccessful() method of Result object." }, { "code": null, "e": 12918, "s": 12823, "text": "Create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 13339, "s": 12918, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 13411, "s": 13339, "text": "Compile the MessageUtil, Test case and Test Runner classes using javac." }, { "code": null, "e": 13485, "s": 13411, "text": "C:\\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java\n" }, { "code": null, "e": 13580, "s": 13485, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 13616, "s": 13580, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 13635, "s": 13616, "text": "Verify the output." }, { "code": null, "e": 13653, "s": 13635, "text": "Hello World\ntrue\n" }, { "code": null, "e": 13748, "s": 13653, "text": "Now update TestJunit in C:\\>JUNIT_WORKSPACE so that the test fails. Change the message string." }, { "code": null, "e": 14072, "s": 13748, "text": "import org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\t\n String message = \"Hello World\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testPrintMessage() {\n message = \"New Word\";\n assertEquals(message,messageUtil.printMessage());\n }\n}" }, { "code": null, "e": 14151, "s": 14072, "text": "Let's keep the rest of the classes as is, and try to run the same Test Runner." }, { "code": null, "e": 14570, "s": 14151, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n}" }, { "code": null, "e": 14665, "s": 14570, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 14701, "s": 14665, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 14720, "s": 14701, "text": "Verify the output." }, { "code": null, "e": 14814, "s": 14720, "text": "Hello World\ntestPrintMessage(TestJunit): expected:<[New Wor]d> but was:<[Hello Worl]d>\nfalse\n" }, { "code": null, "e": 14954, "s": 14814, "text": "The most important package in JUnit is junit.framework, which contains all the core classes. Some of the important classes are as follows −" }, { "code": null, "e": 15012, "s": 14954, "text": "Following is the declaration for org.junit.Assert class −" }, { "code": null, "e": 15058, "s": 15012, "text": "public class Assert extends java.lang.Object\n" }, { "code": null, "e": 15231, "s": 15058, "text": "This class provides a set of assertion methods useful for writing tests. Only failed assertions are recorded. Some of the important methods of Assert class are as follows −" }, { "code": null, "e": 15283, "s": 15231, "text": "void assertEquals(boolean expected, boolean actual)" }, { "code": null, "e": 15329, "s": 15283, "text": "Checks that two primitives/objects are equal." }, { "code": null, "e": 15365, "s": 15329, "text": "void assertFalse(boolean condition)" }, { "code": null, "e": 15399, "s": 15365, "text": "Checks that a condition is false." }, { "code": null, "e": 15433, "s": 15399, "text": "void assertNotNull(Object object)" }, { "code": null, "e": 15467, "s": 15433, "text": "Checks that an object isn't null." }, { "code": null, "e": 15498, "s": 15467, "text": "void assertNull(Object object)" }, { "code": null, "e": 15529, "s": 15498, "text": "Checks that an object is null." }, { "code": null, "e": 15564, "s": 15529, "text": "void assertTrue(boolean condition)" }, { "code": null, "e": 15597, "s": 15564, "text": "Checks that a condition is true." }, { "code": null, "e": 15609, "s": 15597, "text": "void fail()" }, { "code": null, "e": 15639, "s": 15609, "text": "Fails a test with no message." }, { "code": null, "e": 15771, "s": 15639, "text": "Let's use some of the above-mentioned methods in an example. Create a java class file named TestJunit1.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 16213, "s": 15771, "text": "import org.junit.Test;\nimport static org.junit.Assert.*;\n\npublic class TestJunit1 {\n @Test\n public void testAdd() {\n //test data\n int num = 5;\n String temp = null;\n String str = \"Junit is working fine\";\n\n //check for equality\n assertEquals(\"Junit is working fine\", str);\n \n //check for false condition\n assertFalse(num > 6);\n\n //check for not null value\n assertNotNull(temp);\n }\n}" }, { "code": null, "e": 16315, "s": 16213, "text": "Next, create a java class file named TestRunner1.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 16738, "s": 16315, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner1 {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit1.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 16797, "s": 16738, "text": "Compile the test case and Test Runner classes using javac." }, { "code": null, "e": 16856, "s": 16797, "text": "C:\\JUNIT_WORKSPACE>javac TestJunit1.java TestRunner1.java\n" }, { "code": null, "e": 16951, "s": 16856, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 16988, "s": 16951, "text": "C:\\JUNIT_WORKSPACE>java TestRunner1\n" }, { "code": null, "e": 17007, "s": 16988, "text": "Verify the output." }, { "code": null, "e": 17013, "s": 17007, "text": "true\n" }, { "code": null, "e": 17073, "s": 17013, "text": "Following is the declaration for org.junit.TestCase class −" }, { "code": null, "e": 17136, "s": 17073, "text": "public abstract class TestCase extends Assert implements Test\n" }, { "code": null, "e": 17256, "s": 17136, "text": "A test case defines the fixture to run multiple tests. Some of the important methods of TestCase class are as follows −" }, { "code": null, "e": 17277, "s": 17256, "text": "int countTestCases()" }, { "code": null, "e": 17345, "s": 17277, "text": "Counts the number of test cases executed by run(TestResult result)." }, { "code": null, "e": 17371, "s": 17345, "text": "TestResult createResult()" }, { "code": null, "e": 17408, "s": 17371, "text": "Creates a default TestResult object." }, { "code": null, "e": 17425, "s": 17408, "text": "String getName()" }, { "code": null, "e": 17454, "s": 17425, "text": "Gets the name of a TestCase." }, { "code": null, "e": 17471, "s": 17454, "text": "TestResult run()" }, { "code": null, "e": 17567, "s": 17471, "text": "A convenience method to run this test, collecting the results with a default TestResult object." }, { "code": null, "e": 17595, "s": 17567, "text": "void run(TestResult result)" }, { "code": null, "e": 17654, "s": 17595, "text": "Runs the test case and collects the results in TestResult." }, { "code": null, "e": 17680, "s": 17654, "text": "void setName(String name)" }, { "code": null, "e": 17709, "s": 17680, "text": "Sets the name of a TestCase." }, { "code": null, "e": 17722, "s": 17709, "text": "void setUp()" }, { "code": null, "e": 17783, "s": 17722, "text": "Sets up the fixture, for example, open a network connection." }, { "code": null, "e": 17799, "s": 17783, "text": "void tearDown()" }, { "code": null, "e": 17864, "s": 17799, "text": "Tears down the fixture, for example, close a network connection." }, { "code": null, "e": 17882, "s": 17864, "text": "String toString()" }, { "code": null, "e": 17932, "s": 17882, "text": "Returns a string representation of the test case." }, { "code": null, "e": 18064, "s": 17932, "text": "Let's use some of the above-mentioned methods in an example. Create a java class file named TestJunit2.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 18867, "s": 18064, "text": "import junit.framework.TestCase;\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class TestJunit2 extends TestCase {\n protected double fValue1;\n protected double fValue2;\n \n @Before \n public void setUp() {\n fValue1 = 2.0;\n fValue2 = 3.0;\n }\n\t\n @Test\n public void testAdd() {\n //count the number of test cases\n System.out.println(\"No of Test Case = \"+ this.countTestCases());\n\t\t\n //test getName \n String name = this.getName();\n System.out.println(\"Test Case Name = \"+ name);\n\n //test setName\n this.setName(\"testNewAdd\");\n String newName = this.getName();\n System.out.println(\"Updated Test Case Name = \"+ newName);\n }\n\t\n //tearDown used to close the connection or clean up activities\n public void tearDown( ) {\n }\n}" }, { "code": null, "e": 18969, "s": 18867, "text": "Next, create a java class file named TestRunner2.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 19390, "s": 18969, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner2 {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit2.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} " }, { "code": null, "e": 19449, "s": 19390, "text": "Compile the test case and Test Runner classes using javac." }, { "code": null, "e": 19508, "s": 19449, "text": "C:\\JUNIT_WORKSPACE>javac TestJunit2.java TestRunner2.java\n" }, { "code": null, "e": 19603, "s": 19508, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 19640, "s": 19603, "text": "C:\\JUNIT_WORKSPACE>java TestRunner2\n" }, { "code": null, "e": 19659, "s": 19640, "text": "Verify the output." }, { "code": null, "e": 19746, "s": 19659, "text": "No of Test Case = 1\nTest Case Name = testAdd\nUpdated Test Case Name = testNewAdd\ntrue\n" }, { "code": null, "e": 19808, "s": 19746, "text": "Following is the declaration for org.junit.TestResult class −" }, { "code": null, "e": 19848, "s": 19808, "text": "public class TestResult extends Object\n" }, { "code": null, "e": 20224, "s": 19848, "text": "A TestResult collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test framework distinguishes between failures and errors. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like an ArrayIndexOutOfBoundsException. Some of the important methods of TestResult class are as follows −" }, { "code": null, "e": 20262, "s": 20224, "text": "void addError(Test test, Throwable t)" }, { "code": null, "e": 20299, "s": 20262, "text": "Adds an error to the list of errors." }, { "code": null, "e": 20350, "s": 20299, "text": "void addFailure(Test test, AssertionFailedError t)" }, { "code": null, "e": 20390, "s": 20350, "text": "Adds a failure to the list of failures." }, { "code": null, "e": 20414, "s": 20390, "text": "void endTest(Test test)" }, { "code": null, "e": 20460, "s": 20414, "text": "Informs the result that a test was completed." }, { "code": null, "e": 20477, "s": 20460, "text": "int errorCount()" }, { "code": null, "e": 20513, "s": 20477, "text": "Gets the number of detected errors." }, { "code": null, "e": 20547, "s": 20513, "text": "Enumeration<TestFailure> errors()" }, { "code": null, "e": 20586, "s": 20547, "text": "Returns an Enumeration for the errors." }, { "code": null, "e": 20605, "s": 20586, "text": "int failureCount()" }, { "code": null, "e": 20643, "s": 20605, "text": "Gets the number of detected failures." }, { "code": null, "e": 20667, "s": 20643, "text": "void run(TestCase test)" }, { "code": null, "e": 20684, "s": 20667, "text": "Runs a TestCase." }, { "code": null, "e": 20699, "s": 20684, "text": "int runCount()" }, { "code": null, "e": 20729, "s": 20699, "text": "Gets the number of run tests." }, { "code": null, "e": 20755, "s": 20729, "text": "void startTest(Test test)" }, { "code": null, "e": 20803, "s": 20755, "text": "Informs the result that a test will be started." }, { "code": null, "e": 20815, "s": 20803, "text": "void stop()" }, { "code": null, "e": 20852, "s": 20815, "text": "Marks that the test run should stop." }, { "code": null, "e": 20924, "s": 20852, "text": "Create a java class file named TestJunit3.java in C:\\>JUNIT_WORKSPACE.\n" }, { "code": null, "e": 21558, "s": 20924, "text": "import org.junit.Test;\nimport junit.framework.AssertionFailedError;\nimport junit.framework.TestResult;\n\npublic class TestJunit3 extends TestResult {\n // add the error\n public synchronized void addError(Test test, Throwable t) {\n super.addError((junit.framework.Test) test, t);\n }\n\n // add the failure\n public synchronized void addFailure(Test test, AssertionFailedError t) {\n super.addFailure((junit.framework.Test) test, t);\n }\n\t\n @Test\n public void testAdd() {\n // add any test\n }\n \n // Marks that the test run should stop.\n public synchronized void stop() {\n //stop the test here\n }\n}" }, { "code": null, "e": 21660, "s": 21558, "text": "Next, create a java class file named TestRunner3.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 22081, "s": 21660, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner3 {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit3.class);\n\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 22140, "s": 22081, "text": "Compile the test case and Test Runner classes using javac." }, { "code": null, "e": 22199, "s": 22140, "text": "C:\\JUNIT_WORKSPACE>javac TestJunit3.java TestRunner3.java\n" }, { "code": null, "e": 22294, "s": 22199, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 22331, "s": 22294, "text": "C:\\JUNIT_WORKSPACE>java TestRunner3\n" }, { "code": null, "e": 22350, "s": 22331, "text": "Verify the output." }, { "code": null, "e": 22356, "s": 22350, "text": "true\n" }, { "code": null, "e": 22416, "s": 22356, "text": "Following is the declaration for org.junit.TestSuite class:" }, { "code": null, "e": 22471, "s": 22416, "text": "public class TestSuite extends Object implements Test\n" }, { "code": null, "e": 22610, "s": 22471, "text": "A TestSuite is a Composite of tests. It runs a collection of test cases. Some of the important methods of TestSuite class are as follows −" }, { "code": null, "e": 22634, "s": 22610, "text": "void addTest(Test test)" }, { "code": null, "e": 22660, "s": 22634, "text": "Adds a test to the suite." }, { "code": null, "e": 22715, "s": 22660, "text": "void addTestSuite(Class<? extends TestCase> testClass)" }, { "code": null, "e": 22765, "s": 22715, "text": "Adds the tests from the given class to the suite." }, { "code": null, "e": 22786, "s": 22765, "text": "int countTestCases()" }, { "code": null, "e": 22849, "s": 22786, "text": "Counts the number of test cases that will be run by this test." }, { "code": null, "e": 22866, "s": 22849, "text": "String getName()" }, { "code": null, "e": 22897, "s": 22866, "text": "Returns the name of the suite." }, { "code": null, "e": 22925, "s": 22897, "text": "void run(TestResult result)" }, { "code": null, "e": 22983, "s": 22925, "text": "Runs the tests and collects their result in a TestResult." }, { "code": null, "e": 23009, "s": 22983, "text": "void setName(String name)" }, { "code": null, "e": 23037, "s": 23009, "text": "Sets the name of the suite." }, { "code": null, "e": 23060, "s": 23037, "text": "Test testAt(int index)" }, { "code": null, "e": 23097, "s": 23060, "text": "Returns the test at the given index." }, { "code": null, "e": 23113, "s": 23097, "text": "int testCount()" }, { "code": null, "e": 23156, "s": 23113, "text": "Returns the number of tests in this suite." }, { "code": null, "e": 23192, "s": 23156, "text": "static Test warning(String message)" }, { "code": null, "e": 23250, "s": 23192, "text": "Returns a test which will fail and log a warning message." }, { "code": null, "e": 23346, "s": 23250, "text": "Create a java class file named JunitTestSuite.java in C:\\>JUNIT_WORKSPACE to create Test suite." }, { "code": null, "e": 23724, "s": 23346, "text": "import junit.framework.*;\n\npublic class JunitTestSuite {\n public static void main(String[] a) {\n // add the test's in the suite\n TestSuite suite = new TestSuite(TestJunit1.class, TestJunit2.class, TestJunit3.class );\n TestResult result = new TestResult();\n suite.run(result);\n System.out.println(\"Number of test cases = \" + result.runCount());\n }\n}" }, { "code": null, "e": 23768, "s": 23724, "text": "Compile the Test suite classes using javac." }, { "code": null, "e": 23815, "s": 23768, "text": "C:\\JUNIT_WORKSPACE>javac JunitTestSuite.java \n" }, { "code": null, "e": 23839, "s": 23815, "text": "Now run the Test Suite." }, { "code": null, "e": 23879, "s": 23839, "text": "C:\\JUNIT_WORKSPACE>java JunitTestSuite\n" }, { "code": null, "e": 23898, "s": 23879, "text": "Verify the output." }, { "code": null, "e": 24005, "s": 23898, "text": "No of Test Case = 1\nTest Case Name = testAdd\nUpdated Test Case Name = testNewAdd\nNumber of test cases = 3\n" }, { "code": null, "e": 24156, "s": 24005, "text": "Here we will see one complete example of JUnit testing using POJO class, Business logic class, and a test class, which will be run by the test runner." }, { "code": null, "e": 24231, "s": 24156, "text": "Create EmployeeDetails.java in C:\\>JUNIT_WORKSPACE, which is a POJO class." }, { "code": null, "e": 25033, "s": 24231, "text": "public class EmployeeDetails {\n\n private String name;\n private double monthlySalary;\n private int age;\n \n /**\n * @return the name\n */\n\t\n public String getName() {\n return name;\n }\n\t\n /**\n * @param name the name to set\n */\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n /**\n * @return the monthlySalary\n */\n\t\n public double getMonthlySalary() {\n return monthlySalary;\n }\n\t\n /**\n * @param monthlySalary the monthlySalary to set\n */\n\t\n public void setMonthlySalary(double monthlySalary) {\n this.monthlySalary = monthlySalary;\n }\n\t\n /**\n * @return the age\n */\n public int getAge() {\n return age;\n }\n\t\n /**\n * @param age the age to set\n */\n public void setAge(int age) {\n this.age = age;\n }\n}" }, { "code": null, "e": 25068, "s": 25033, "text": "EmployeeDetails class is used to −" }, { "code": null, "e": 25106, "s": 25068, "text": "get/set the value of employee's name." }, { "code": null, "e": 25154, "s": 25106, "text": "get/set the value of employee's monthly salary." }, { "code": null, "e": 25191, "s": 25154, "text": "get/set the value of employee's age." }, { "code": null, "e": 25293, "s": 25191, "text": "Create a file called EmpBusinessLogic.java in C:\\>JUNIT_WORKSPACE, which contains the business logic." }, { "code": null, "e": 25885, "s": 25293, "text": "public class EmpBusinessLogic {\n // Calculate the yearly salary of employee\n public double calculateYearlySalary(EmployeeDetails employeeDetails) {\n double yearlySalary = 0;\n yearlySalary = employeeDetails.getMonthlySalary() * 12;\n return yearlySalary;\n }\n\t\n // Calculate the appraisal amount of employee\n public double calculateAppraisal(EmployeeDetails employeeDetails) {\n double appraisal = 0;\n\t\t\n if(employeeDetails.getMonthlySalary() < 10000){\n appraisal = 500;\n }else{\n appraisal = 1000;\n }\n\t\t\n return appraisal;\n }\n}" }, { "code": null, "e": 25934, "s": 25885, "text": "EmpBusinessLogic class is used for calculating −" }, { "code": null, "e": 25968, "s": 25934, "text": "the yearly salary of an employee." }, { "code": null, "e": 26005, "s": 25968, "text": "the appraisal amount of an employee." }, { "code": null, "e": 26119, "s": 26005, "text": "Create a file called TestEmployeeDetails.java in C:\\>JUNIT_WORKSPACE, which contains the test cases to be tested." }, { "code": null, "e": 26952, "s": 26119, "text": "import org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestEmployeeDetails {\n EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic();\n EmployeeDetails employee = new EmployeeDetails();\n\n //test to check appraisal\n @Test\n public void testCalculateAppriasal() {\n employee.setName(\"Rajeev\");\n employee.setAge(25);\n employee.setMonthlySalary(8000);\n\t\t\n double appraisal = empBusinessLogic.calculateAppraisal(employee);\n assertEquals(500, appraisal, 0.0);\n }\n\n // test to check yearly salary\n @Test\n public void testCalculateYearlySalary() {\n employee.setName(\"Rajeev\");\n employee.setAge(25);\n employee.setMonthlySalary(8000);\n\t\t\n double salary = empBusinessLogic.calculateYearlySalary(employee);\n assertEquals(96000, salary, 0.0);\n }\n}" }, { "code": null, "e": 27040, "s": 26952, "text": "TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It" }, { "code": null, "e": 27081, "s": 27040, "text": "tests the yearly salary of the employee." }, { "code": null, "e": 27125, "s": 27081, "text": "tests the appraisal amount of the employee." }, { "code": null, "e": 27227, "s": 27125, "text": "Next, create a java class filed named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 27656, "s": 27227, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestEmployeeDetails.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} " }, { "code": null, "e": 27715, "s": 27656, "text": "Compile the test case and Test Runner classes using javac." }, { "code": null, "e": 27826, "s": 27715, "text": "C:\\JUNIT_WORKSPACE>javac EmployeeDetails.java \nEmpBusinessLogic.java TestEmployeeDetails.java TestRunner.java\n" }, { "code": null, "e": 27921, "s": 27826, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 27957, "s": 27921, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 27976, "s": 27957, "text": "Verify the output." }, { "code": null, "e": 27982, "s": 27976, "text": "true\n" }, { "code": null, "e": 28026, "s": 27982, "text": "All the assertions are in the Assert class." }, { "code": null, "e": 28072, "s": 28026, "text": "public class Assert extends java.lang.Object\n" }, { "code": null, "e": 28246, "s": 28072, "text": "This class provides a set of assertion methods, useful for writing tests. Only failed assertions are recorded. Some of the important methods of Assert class are as follows −" }, { "code": null, "e": 28298, "s": 28246, "text": "void assertEquals(boolean expected, boolean actual)" }, { "code": null, "e": 28344, "s": 28298, "text": "Checks that two primitives/objects are equal." }, { "code": null, "e": 28379, "s": 28344, "text": "void assertTrue(boolean condition)" }, { "code": null, "e": 28412, "s": 28379, "text": "Checks that a condition is true." }, { "code": null, "e": 28448, "s": 28412, "text": "void assertFalse(boolean condition)" }, { "code": null, "e": 28482, "s": 28448, "text": "Checks that a condition is false." }, { "code": null, "e": 28516, "s": 28482, "text": "void assertNotNull(Object object)" }, { "code": null, "e": 28550, "s": 28516, "text": "Checks that an object isn't null." }, { "code": null, "e": 28581, "s": 28550, "text": "void assertNull(Object object)" }, { "code": null, "e": 28612, "s": 28581, "text": "Checks that an object is null." }, { "code": null, "e": 28646, "s": 28612, "text": "void assertSame(object1, object2)" }, { "code": null, "e": 28727, "s": 28646, "text": "The assertSame() method tests if two object references point to the same object." }, { "code": null, "e": 28764, "s": 28727, "text": "void assertNotSame(object1, object2)" }, { "code": null, "e": 28855, "s": 28764, "text": "The assertNotSame() method tests if two object references do not point to the same object." }, { "code": null, "e": 28907, "s": 28855, "text": "void assertArrayEquals(expectedArray, resultArray);" }, { "code": null, "e": 28992, "s": 28907, "text": "The assertArrayEquals() method will test whether two arrays are equal to each other." }, { "code": null, "e": 29128, "s": 28992, "text": "Let's use some of the above-mentioned methods in an example. Create a java class file named TestAssertions.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 30256, "s": 29128, "text": "import org.junit.Test;\nimport static org.junit.Assert.*;\n\npublic class TestAssertions {\n\n @Test\n public void testAssertions() {\n //test data\n String str1 = new String (\"abc\");\n String str2 = new String (\"abc\");\n String str3 = null;\n String str4 = \"abc\";\n String str5 = \"abc\";\n\t\t\n int val1 = 5;\n int val2 = 6;\n\n String[] expectedArray = {\"one\", \"two\", \"three\"};\n String[] resultArray = {\"one\", \"two\", \"three\"};\n\n //Check that two objects are equal\n assertEquals(str1, str2);\n\n //Check that a condition is true\n assertTrue (val1 < val2);\n\n //Check that a condition is false\n assertFalse(val1 > val2);\n\n //Check that an object isn't null\n assertNotNull(str1);\n\n //Check that an object is null\n assertNull(str3);\n\n //Check if two object references point to the same object\n assertSame(str4,str5);\n\n //Check if two object references not point to the same object\n assertNotSame(str1,str3);\n\n //Check whether two arrays are equal to each other.\n assertArrayEquals(expectedArray, resultArray);\n }\n}" }, { "code": null, "e": 30357, "s": 30256, "text": "Next, create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 30782, "s": 30357, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner2 {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestAssertions.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} " }, { "code": null, "e": 30841, "s": 30782, "text": "Compile the Test case and Test Runner classes using javac." }, { "code": null, "e": 30903, "s": 30841, "text": "C:\\JUNIT_WORKSPACE>javac TestAssertions.java TestRunner.java\n" }, { "code": null, "e": 30998, "s": 30903, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 31034, "s": 30998, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 31053, "s": 31034, "text": "Verify the output." }, { "code": null, "e": 31059, "s": 31053, "text": "true\n" }, { "code": null, "e": 31242, "s": 31059, "text": "Annotations are like meta-tags that you can add to your code, and apply them to methods or in class. These annotations in JUnit provide the following information about test methods −" }, { "code": null, "e": 31304, "s": 31242, "text": "which methods are going to run before and after test methods." }, { "code": null, "e": 31361, "s": 31304, "text": "which methods run before and after all the methods, and." }, { "code": null, "e": 31424, "s": 31361, "text": "which methods or classes will be ignored during the execution." }, { "code": null, "e": 31504, "s": 31424, "text": "The following table provides a list of annotations and their meaning in JUnit −" }, { "code": null, "e": 31510, "s": 31504, "text": "@Test" }, { "code": null, "e": 31621, "s": 31510, "text": "The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case." }, { "code": null, "e": 31629, "s": 31621, "text": "@Before" }, { "code": null, "e": 31792, "s": 31629, "text": "Several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before each Test method." }, { "code": null, "e": 31799, "s": 31792, "text": "@After" }, { "code": null, "e": 31996, "s": 31799, "text": "If you allocate external resources in a Before method, you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method." }, { "code": null, "e": 32009, "s": 31996, "text": "@BeforeClass" }, { "code": null, "e": 32136, "s": 32009, "text": "Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class." }, { "code": null, "e": 32148, "s": 32136, "text": "@AfterClass" }, { "code": null, "e": 32257, "s": 32148, "text": "This will perform the method after all tests have finished. This can be used to perform clean-up activities." }, { "code": null, "e": 32265, "s": 32257, "text": "@Ignore" }, { "code": null, "e": 32350, "s": 32265, "text": "The Ignore annotation is used to ignore the test and that test will not be executed." }, { "code": null, "e": 32445, "s": 32350, "text": "Create a java class file named JunitAnnotation.java in C:\\>JUNIT_WORKSPACE to test annotation." }, { "code": null, "e": 33335, "s": 32445, "text": "import org.junit.After;\nimport org.junit.AfterClass;\n\nimport org.junit.Before;\nimport org.junit.BeforeClass;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\n\npublic class JunitAnnotation {\n\t\n //execute before class\n @BeforeClass\n public static void beforeClass() {\n System.out.println(\"in before class\");\n }\n\n //execute after class\n @AfterClass\n public static void afterClass() {\n System.out.println(\"in after class\");\n }\n\n //execute before test\n @Before\n public void before() {\n System.out.println(\"in before\");\n }\n\t\n //execute after test\n @After\n public void after() {\n System.out.println(\"in after\");\n }\n\t\n //test case\n @Test\n public void test() {\n System.out.println(\"in test\");\n }\n\t\n //test case ignore and will not execute\n @Ignore\n public void ignoreTest() {\n System.out.println(\"in ignore test\");\n }\n}" }, { "code": null, "e": 33435, "s": 33335, "text": "Next, create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute annotations." }, { "code": null, "e": 33860, "s": 33435, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(JunitAnnotation.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} " }, { "code": null, "e": 33919, "s": 33860, "text": "Compile the Test case and Test Runner classes using javac." }, { "code": null, "e": 33982, "s": 33919, "text": "C:\\JUNIT_WORKSPACE>javac JunitAnnotation.java TestRunner.java\n" }, { "code": null, "e": 34077, "s": 33982, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 34113, "s": 34077, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 34132, "s": 34113, "text": "Verify the output." }, { "code": null, "e": 34196, "s": 34132, "text": "in before class\nin before\nin test\nin after\nin after class\ntrue\n" }, { "code": null, "e": 34397, "s": 34196, "text": "This chapter explains the execution procedure of methods in JUnit, which defines the order of the methods called. Discussed below is the execution procedure of the JUnit test API methods with example." }, { "code": null, "e": 34500, "s": 34397, "text": "Create a java class file named ExecutionProcedureJunit.java in C:\\>JUNIT_WORKSPACE to test annotation." }, { "code": null, "e": 35457, "s": 34500, "text": "import org.junit.After;\nimport org.junit.AfterClass;\n\nimport org.junit.Before;\nimport org.junit.BeforeClass;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\n\npublic class ExecutionProcedureJunit {\n\t\n //execute only once, in the starting \n @BeforeClass\n public static void beforeClass() {\n System.out.println(\"in before class\");\n }\n\n //execute only once, in the end\n @AfterClass\n public static void afterClass() {\n System.out.println(\"in after class\");\n }\n\n //execute for each test, before executing test\n @Before\n public void before() {\n System.out.println(\"in before\");\n }\n\t\n //execute for each test, after executing test\n @After\n public void after() {\n System.out.println(\"in after\");\n }\n\t\n //test case 1\n @Test\n public void testCase1() {\n System.out.println(\"in test case 1\");\n }\n\n //test case 2\n @Test\n public void testCase2() {\n System.out.println(\"in test case 2\");\n }\n}" }, { "code": null, "e": 35557, "s": 35457, "text": "Next, create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute annotations." }, { "code": null, "e": 35988, "s": 35557, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(ExecutionProcedureJunit.class);\n\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} " }, { "code": null, "e": 36047, "s": 35988, "text": "Compile the Test case and Test Runner classes using javac." }, { "code": null, "e": 36118, "s": 36047, "text": "C:\\JUNIT_WORKSPACE>javac ExecutionProcedureJunit.java TestRunner.java\n" }, { "code": null, "e": 36213, "s": 36118, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 36249, "s": 36213, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 36268, "s": 36249, "text": "Verify the output." }, { "code": null, "e": 36368, "s": 36268, "text": "in before class\nin before\nin test case 1\nin after\nin before\nin test case 2\nin after\nin after class\n" }, { "code": null, "e": 36430, "s": 36368, "text": "See the above output. The execution procedure is as follows −" }, { "code": null, "e": 36489, "s": 36430, "text": "First of all, the beforeClass() method executes only once." }, { "code": null, "e": 36533, "s": 36489, "text": "The afterClass() method executes only once." }, { "code": null, "e": 36618, "s": 36533, "text": "The before() method executes for each test case, but before executing the test case." }, { "code": null, "e": 36704, "s": 36618, "text": "The after() method executes for each test case, but after the execution of test case." }, { "code": null, "e": 36762, "s": 36704, "text": "In between before() and after(), each test case executes." }, { "code": null, "e": 37074, "s": 36762, "text": "The test cases are executed using JUnitCore class. JUnitCore is a facade for running tests. It supports running JUnit 4 tests, JUnit 3.8.x tests, and mixtures. To run tests from the command line, run java org.junit.runner.JUnitCore <TestClass>. For one-shot test runs, use the static method runClasses(Class[])." }, { "code": null, "e": 37141, "s": 37074, "text": "Following is the declaration for org.junit.runner.JUnitCore class:" }, { "code": null, "e": 37190, "s": 37141, "text": "public class JUnitCore extends java.lang.Object\n" }, { "code": null, "e": 37260, "s": 37190, "text": "Here we will see how to execute the tests with the help of JUnitCore." }, { "code": null, "e": 37341, "s": 37260, "text": "Create a java class to be tested, say, MessageUtil.java, in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 37715, "s": 37341, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message;\n }\n \n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n\t\n} " }, { "code": null, "e": 37762, "s": 37715, "text": "Create a java test class, say, TestJunit.java." }, { "code": null, "e": 37809, "s": 37762, "text": "Create a java test class, say, TestJunit.java." }, { "code": null, "e": 37866, "s": 37809, "text": "Add a test method testPrintMessage() to your test class." }, { "code": null, "e": 37923, "s": 37866, "text": "Add a test method testPrintMessage() to your test class." }, { "code": null, "e": 37980, "s": 37923, "text": "Add an Annotaion @Test to the method testPrintMessage()." }, { "code": null, "e": 38037, "s": 37980, "text": "Add an Annotaion @Test to the method testPrintMessage()." }, { "code": null, "e": 38123, "s": 38037, "text": "Implement the test condition and check the condition using assertEquals API of JUnit." }, { "code": null, "e": 38209, "s": 38123, "text": "Implement the test condition and check the condition using assertEquals API of JUnit." }, { "code": null, "e": 38279, "s": 38209, "text": "Create a java class file named TestJunit.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 38575, "s": 38279, "text": "import org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\t\n String message = \"Hello World\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testPrintMessage() {\n assertEquals(message,messageUtil.printMessage());\n }\n}" }, { "code": null, "e": 38787, "s": 38575, "text": "Now create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s). It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter." }, { "code": null, "e": 39208, "s": 38787, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 39267, "s": 39208, "text": "Compile the Test case and Test Runner classes using javac." }, { "code": null, "e": 39341, "s": 39267, "text": "C:\\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java\n" }, { "code": null, "e": 39436, "s": 39341, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 39472, "s": 39436, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 39491, "s": 39472, "text": "Verify the output." }, { "code": null, "e": 39509, "s": 39491, "text": "Hello World\ntrue\n" }, { "code": null, "e": 39779, "s": 39509, "text": "Test suite is used to bundle a few unit test cases and run them together. In JUnit, both @RunWith and @Suite annotations are used to run the suite tests. This chapter takes an example having two test classes, TestJunit1 & TestJunit2, that run together using Test Suite." }, { "code": null, "e": 39859, "s": 39779, "text": "Create a java class to be tested, say, MessageUtil.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 40395, "s": 39859, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message; \n }\n\n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n\n // add \"Hi!\" to the message\n public String salutationMessage(){\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n } \n} \t" }, { "code": null, "e": 40466, "s": 40395, "text": "Create a java class file named TestJunit1.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 40851, "s": 40466, "text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit1 {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test\n public void testPrintMessage() {\t\n System.out.println(\"Inside testPrintMessage()\"); \n assertEquals(message, messageUtil.printMessage()); \n }\n}" }, { "code": null, "e": 40922, "s": 40851, "text": "Create a java class file named TestJunit2.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 41343, "s": 40922, "text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit2 {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n}" }, { "code": null, "e": 41364, "s": 41343, "text": "Create a java class." }, { "code": null, "e": 41420, "s": 41364, "text": "Attach @RunWith(Suite.class) Annotation with the class." }, { "code": null, "e": 41494, "s": 41420, "text": "Add reference to JUnit test classes using @Suite.SuiteClasses annotation." }, { "code": null, "e": 41588, "s": 41494, "text": "Create a java class file named TestSuite.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 41782, "s": 41588, "text": "import org.junit.runner.RunWith;\nimport org.junit.runners.Suite;\n\n@RunWith(Suite.class)\n\[email protected]({\n TestJunit1.class,\n TestJunit2.class\n})\n\npublic class JunitTestSuite { \n} \t" }, { "code": null, "e": 41877, "s": 41782, "text": "Create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 42301, "s": 41877, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(JunitTestSuite.class);\n\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 42343, "s": 42301, "text": "Compile all the java classes using javac." }, { "code": null, "e": 42455, "s": 42343, "text": "C:\\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit1.java \nTestJunit2.java JunitTestSuite.java TestRunner.java\n" }, { "code": null, "e": 42550, "s": 42455, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 42586, "s": 42550, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 42605, "s": 42586, "text": "Verify the output." }, { "code": null, "e": 42685, "s": 42605, "text": "Inside testPrintMessage()\nRobert\nInside testSalutationMessage()\nHi Robert\ntrue\n" }, { "code": null, "e": 42855, "s": 42685, "text": "Sometimes it so happens that our code is not completely ready while running a test case. As a result, the test case fails. The @Ignore annotation helps in this scenario." }, { "code": null, "e": 42914, "s": 42855, "text": "A test method annotated with @Ignore will not be executed." }, { "code": null, "e": 42973, "s": 42914, "text": "A test method annotated with @Ignore will not be executed." }, { "code": null, "e": 43064, "s": 42973, "text": "If a test class is annotated with @Ignore, then none of its test methods will be executed." }, { "code": null, "e": 43155, "s": 43064, "text": "If a test class is annotated with @Ignore, then none of its test methods will be executed." }, { "code": null, "e": 43188, "s": 43155, "text": "Now let's see @Ignore in action." }, { "code": null, "e": 43268, "s": 43188, "text": "Create a java class to be tested, say, MessageUtil.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 43805, "s": 43268, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message; \n }\n\n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n\n // add \"Hi!\" to the message\n public String salutationMessage(){\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n } \n\t\n} " }, { "code": null, "e": 43852, "s": 43805, "text": "Create a java test class, say, TestJunit.java." }, { "code": null, "e": 43899, "s": 43852, "text": "Create a java test class, say, TestJunit.java." }, { "code": null, "e": 43983, "s": 43899, "text": "Add a test method testPrintMessage() or testSalutationMessage() to your test class." }, { "code": null, "e": 44067, "s": 43983, "text": "Add a test method testPrintMessage() or testSalutationMessage() to your test class." }, { "code": null, "e": 44122, "s": 44067, "text": "Add an Annotaion @Ignore to method testPrintMessage()." }, { "code": null, "e": 44177, "s": 44122, "text": "Add an Annotaion @Ignore to method testPrintMessage()." }, { "code": null, "e": 44247, "s": 44177, "text": "Create a java class file named TestJunit.java in C:\\ JUNIT_WORKSPACE." }, { "code": null, "e": 44870, "s": 44247, "text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Ignore\n @Test\n public void testPrintMessage() {\n System.out.println(\"Inside testPrintMessage()\");\n message = \"Robert\";\n assertEquals(message,messageUtil.printMessage());\n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n\t\n}" }, { "code": null, "e": 44965, "s": 44870, "text": "Create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 45384, "s": 44965, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 45456, "s": 45384, "text": "Compile the MessageUtil, Test case and Test Runner classes using javac." }, { "code": null, "e": 45530, "s": 45456, "text": "C:\\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java\n" }, { "code": null, "e": 45648, "s": 45530, "text": "Now run the Test Runner, which will not run the testPrintMessage() test case defined in the provided Test Case class." }, { "code": null, "e": 45684, "s": 45648, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 45747, "s": 45684, "text": "Verify the output. testPrintMessage() test case is not tested." }, { "code": null, "e": 45794, "s": 45747, "text": "Inside testSalutationMessage()\nHi!Robert\ntrue\n" }, { "code": null, "e": 45893, "s": 45794, "text": "Now, update TestJunit in C:\\>JUNIT_WORKSPACE to ignore all test cases. Add @Ignore at class level." }, { "code": null, "e": 46515, "s": 45893, "text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\n@Ignore\npublic class TestJunit {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test\n public void testPrintMessage() {\n System.out.println(\"Inside testPrintMessage()\");\n message = \"Robert\";\n assertEquals(message,messageUtil.printMessage());\n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n\t\n}" }, { "code": null, "e": 46550, "s": 46515, "text": "Compile the test case using javac." }, { "code": null, "e": 46591, "s": 46550, "text": "C:\\JUNIT_WORKSPACE>javac TestJunit.java\n" }, { "code": null, "e": 46636, "s": 46591, "text": "Keep your Test Runner unchanged as follows −" }, { "code": null, "e": 47054, "s": 46636, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n}" }, { "code": null, "e": 47153, "s": 47054, "text": "Now run the Test Runner, which will not run any test case defined in the provided Test Case class." }, { "code": null, "e": 47189, "s": 47153, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 47232, "s": 47189, "text": "Verify the output. No test case is tested." }, { "code": null, "e": 47238, "s": 47232, "text": "true\n" }, { "code": null, "e": 47503, "s": 47238, "text": "JUnit provides a handy option of Timeout. If a test case takes more time than the specified number of milliseconds, then JUnit will automatically mark it as failed. The timeout parameter is used along with @Test annotation. Let us see the @Test(timeout) in action." }, { "code": null, "e": 47583, "s": 47503, "text": "Create a java class to be tested, say, MessageUtil.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 47644, "s": 47583, "text": "Add an infinite while loop inside the printMessage() method." }, { "code": null, "e": 48175, "s": 47644, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message; \n }\n\n // prints the message\n public void printMessage(){\n System.out.println(message);\n while(true);\n } \n\n // add \"Hi!\" to the message\n public String salutationMessage(){\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n } \n} \t" }, { "code": null, "e": 48277, "s": 48175, "text": "Create a java test class, say, TestJunit.java. Add a timeout of 1000 to testPrintMessage() test case." }, { "code": null, "e": 48347, "s": 48277, "text": "Create a java class file named TestJunit.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 48936, "s": 48347, "text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test(timeout = 1000)\n public void testPrintMessage() {\t\n System.out.println(\"Inside testPrintMessage()\"); \n messageUtil.printMessage(); \n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n}" }, { "code": null, "e": 49031, "s": 48936, "text": "Create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 49452, "s": 49031, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 49524, "s": 49452, "text": "Compile the MessageUtil, Test case and Test Runner classes using javac." }, { "code": null, "e": 49598, "s": 49524, "text": "C:\\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java\n" }, { "code": null, "e": 49694, "s": 49598, "text": "Now run the Test Runner, which will run the test cases defined in the provided Test Case class." }, { "code": null, "e": 49730, "s": 49694, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 49813, "s": 49730, "text": "Verify the output. testPrintMessage() test case will mark the unit testing failed." }, { "code": null, "e": 49962, "s": 49813, "text": "Inside testPrintMessage()\nRobert\nInside testSalutationMessage()\nHi!Robert\ntestPrintMessage(TestJunit): test timed out after 1000 milliseconds\nfalse\n" }, { "code": null, "e": 50193, "s": 49962, "text": "JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation. Let us see @Test(expected) in action." }, { "code": null, "e": 50274, "s": 50193, "text": "Create a java class to be tested, say, MessageUtil.java in C:\\> JUNIT_WORKSPACE." }, { "code": null, "e": 50331, "s": 50274, "text": "Add an error condition inside the printMessage() method." }, { "code": null, "e": 50879, "s": 50331, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message; \n }\n\n // prints the message\n public void printMessage(){\n System.out.println(message);\n int a = 0;\n int b = 1/a;\n } \n\n // add \"Hi!\" to the message\n public String salutationMessage(){\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n } \n} \t" }, { "code": null, "e": 51010, "s": 50879, "text": "Create a java test class called TestJunit.java. Add an expected exception ArithmeticException to the testPrintMessage() test case." }, { "code": null, "e": 51080, "s": 51010, "text": "Create a java class file named TestJunit.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 51691, "s": 51080, "text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test(expected = ArithmeticException.class)\n public void testPrintMessage() {\t\n System.out.println(\"Inside testPrintMessage()\"); \n messageUtil.printMessage(); \n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n}" }, { "code": null, "e": 51786, "s": 51691, "text": "Create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 52207, "s": 51786, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 52279, "s": 52207, "text": "Compile the MessageUtil, Test case and Test Runner classes using javac." }, { "code": null, "e": 52353, "s": 52279, "text": "C:\\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java\n" }, { "code": null, "e": 52449, "s": 52353, "text": "Now run the Test Runner, which will run the test cases defined in the provided Test Case class." }, { "code": null, "e": 52485, "s": 52449, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 52549, "s": 52485, "text": "Verify the output. testPrintMessage() test case will be passed." }, { "code": null, "e": 52629, "s": 52549, "text": "Inside testPrintMessage()\nRobert\nInside testSalutationMessage()\nHi!Robert\ntrue\n" }, { "code": null, "e": 52874, "s": 52629, "text": "JUnit 4 has introduced a new feature called parameterized tests. Parameterized tests allow a developer to run the same test over and over again using different values. There are five steps that you need to follow to create a parameterized test." }, { "code": null, "e": 52930, "s": 52874, "text": "Annotate test class with @RunWith(Parameterized.class)." }, { "code": null, "e": 52986, "s": 52930, "text": "Annotate test class with @RunWith(Parameterized.class)." }, { "code": null, "e": 53109, "s": 52986, "text": "Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set." }, { "code": null, "e": 53232, "s": 53109, "text": "Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set." }, { "code": null, "e": 53320, "s": 53232, "text": "Create a public constructor that takes in what is equivalent to one \"row\" of test data." }, { "code": null, "e": 53408, "s": 53320, "text": "Create a public constructor that takes in what is equivalent to one \"row\" of test data." }, { "code": null, "e": 53468, "s": 53408, "text": "Create an instance variable for each \"column\" of test data." }, { "code": null, "e": 53528, "s": 53468, "text": "Create an instance variable for each \"column\" of test data." }, { "code": null, "e": 53614, "s": 53528, "text": "Create your test case(s) using the instance variables as the source of the test data." }, { "code": null, "e": 53700, "s": 53614, "text": "Create your test case(s) using the instance variables as the source of the test data." }, { "code": null, "e": 53799, "s": 53700, "text": "The test case will be invoked once for each row of data. Let us see parameterized tests in action." }, { "code": null, "e": 53886, "s": 53799, "text": "Create a java class to be tested, say, PrimeNumberChecker.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 54136, "s": 53886, "text": "public class PrimeNumberChecker {\n public Boolean validate(final Integer primeNumber) {\n for (int i = 2; i < (primeNumber / 2); i++) {\n if (primeNumber % i == 0) {\n return false;\n }\n }\n return true;\n }\n}" }, { "code": null, "e": 54279, "s": 54136, "text": "Create a java test class, say, PrimeNumberCheckerTest.java. Create a java class file named PrimeNumberCheckerTest.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 55716, "s": 54279, "text": "import java.util.Arrays;\nimport java.util.Collection;\n \nimport org.junit.Test;\nimport org.junit.Before;\n\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\nimport org.junit.runner.RunWith;\nimport static org.junit.Assert.assertEquals;\n\n@RunWith(Parameterized.class)\npublic class PrimeNumberCheckerTest {\n private Integer inputNumber;\n private Boolean expectedResult;\n private PrimeNumberChecker primeNumberChecker;\n\n @Before\n public void initialize() {\n primeNumberChecker = new PrimeNumberChecker();\n }\n\n // Each parameter should be placed as an argument here\n // Every time runner triggers, it will pass the arguments\n // from parameters we defined in primeNumbers() method\n\t\n public PrimeNumberCheckerTest(Integer inputNumber, Boolean expectedResult) {\n this.inputNumber = inputNumber;\n this.expectedResult = expectedResult;\n }\n\n @Parameterized.Parameters\n public static Collection primeNumbers() {\n return Arrays.asList(new Object[][] {\n { 2, true },\n { 6, false },\n { 19, true },\n { 22, false },\n { 23, true }\n });\n }\n\n // This test will run 4 times since we have 5 parameters defined\n @Test\n public void testPrimeNumberChecker() {\n System.out.println(\"Parameterized Number is : \" + inputNumber);\n assertEquals(expectedResult, \n primeNumberChecker.validate(inputNumber));\n }\n}" }, { "code": null, "e": 55811, "s": 55716, "text": "Create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 56243, "s": 55811, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(PrimeNumberCheckerTest.class);\n\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 56335, "s": 56243, "text": "Compile the PrimeNumberChecker, PrimeNumberCheckerTest and Test Runner classes using javac." }, { "code": null, "e": 56429, "s": 56335, "text": "C:\\JUNIT_WORKSPACE>javac PrimeNumberChecker.java PrimeNumberCheckerTest.java\nTestRunner.java\n" }, { "code": null, "e": 56525, "s": 56429, "text": "Now run the Test Runner, which will run the test cases defined in the provided Test Case class." }, { "code": null, "e": 56561, "s": 56525, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 56580, "s": 56561, "text": "Verify the output." }, { "code": null, "e": 56729, "s": 56580, "text": "Parameterized Number is : 2\nParameterized Number is : 6\nParameterized Number is : 19\nParameterized Number is : 22\nParameterized Number is : 23\ntrue\n" }, { "code": null, "e": 56826, "s": 56729, "text": "We will have an example to demonstrate how to run JUnit using ANT. Follow the steps given below." }, { "code": null, "e": 56896, "s": 56826, "text": "Download Apache Ant based on the operating system you are working on." }, { "code": null, "e": 57102, "s": 56896, "text": "Set the ANT_HOME environment variable to point to the base directory location, where the ANT libraries are stored on your machine. Let us assume the Ant libraries are stored in the folder apache-ant-1.8.4." }, { "code": null, "e": 57110, "s": 57102, "text": "Windows" }, { "code": null, "e": 57212, "s": 57110, "text": "Set the environment variable ANT_HOME to C:\\Program Files\\Apache Software Foundation\\apache-ant-1.8.4" }, { "code": null, "e": 57218, "s": 57212, "text": "Linux" }, { "code": null, "e": 57264, "s": 57218, "text": "export ANT_HOME = /usr/local/apache-ant-1.8.4" }, { "code": null, "e": 57268, "s": 57264, "text": "Mac" }, { "code": null, "e": 57312, "s": 57268, "text": "export ANT_HOME = /Library/apache-ant-1.8.4" }, { "code": null, "e": 57373, "s": 57312, "text": "Append Ant compiler location to the System Path as follows −" }, { "code": null, "e": 57432, "s": 57373, "text": "Download a JUnit Archive that suits your operating system." }, { "code": null, "e": 57489, "s": 57432, "text": "Create a folder TestJunitWithAnt in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 57546, "s": 57489, "text": "Create a folder TestJunitWithAnt in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 57607, "s": 57546, "text": "Create a folder src in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt." }, { "code": null, "e": 57668, "s": 57607, "text": "Create a folder src in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt." }, { "code": null, "e": 57730, "s": 57668, "text": "Create a folder test in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt." }, { "code": null, "e": 57792, "s": 57730, "text": "Create a folder test in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt." }, { "code": null, "e": 57853, "s": 57792, "text": "Create a folder lib in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt." }, { "code": null, "e": 57914, "s": 57853, "text": "Create a folder lib in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt." }, { "code": null, "e": 57991, "s": 57914, "text": "Create MessageUtil class in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt> srcfolder." }, { "code": null, "e": 58068, "s": 57991, "text": "Create MessageUtil class in C:\\>JUNIT_WORKSPACE>TestJunitWithAnt> srcfolder." }, { "code": null, "e": 58604, "s": 58068, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message; \n }\n\n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n\n // add \"Hi!\" to the message\n public String salutationMessage(){\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n } \n} \t" }, { "code": null, "e": 58689, "s": 58604, "text": "Create TestMessageUtil class in the folder C:\\>JUNIT_WORKSPACE>TestJunitWithAnt>src." }, { "code": null, "e": 59285, "s": 58689, "text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestMessageUtil {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test\n public void testPrintMessage() {\t\n System.out.println(\"Inside testPrintMessage()\"); \n assertEquals(message,messageUtil.printMessage());\n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n}" }, { "code": null, "e": 59363, "s": 59285, "text": "Copy junit-4.10.jar onto the folder C:\\>JUNIT_WORKSPACE>TestJunitWithAnt>lib." }, { "code": null, "e": 59431, "s": 59363, "text": "We'll be using <junit> task in Ant to execute our JUnit test cases." }, { "code": null, "e": 60545, "s": 59431, "text": "<project name = \"JunitTest\" default = \"test\" basedir = \".\">\n <property name = \"testdir\" location = \"test\" />\n <property name = \"srcdir\" location = \"src\" />\n <property name = \"full-compile\" value = \"true\" />\n\t\n <path id = \"classpath.base\"/>\n\t\n <path id = \"classpath.test\">\n <pathelement location = \"lib/junit-4.10.jar\" />\n <pathelement location = \"${testdir}\" />\n <pathelement location = \"${srcdir}\" />\n <path refid = \"classpath.base\" />\n </path>\n\t\n <target name = \"clean\" >\n <delete verbose = \"${full-compile}\">\n <fileset dir = \"${testdir}\" includes = \"**/*.class\" />\n </delete>\n </target>\n\t\n <target name = \"compile\" depends = \"clean\">\n <javac srcdir = \"${srcdir}\" destdir = \"${testdir}\" \n verbose = \"${full-compile}\">\n <classpath refid = \"classpath.test\"/>\n </javac>\n </target>\n\t\n <target name = \"test\" depends = \"compile\">\n <junit>\n <classpath refid = \"classpath.test\" />\n <formatter type = \"brief\" usefile = \"false\" />\n <test name = \"TestMessageUtil\" />\n </junit>\n </target>\n\t\n</project>" }, { "code": null, "e": 60576, "s": 60545, "text": "Run the following Ant command." }, { "code": null, "e": 60617, "s": 60576, "text": "C:\\JUNIT_WORKSPACE\\TestJunitWithAnt>ant\n" }, { "code": null, "e": 60636, "s": 60617, "text": "Verify the output." }, { "code": null, "e": 63501, "s": 60636, "text": "Buildfile: C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\build.xml\n\nclean: \n\ncompile: \n [javac] Compiling 2 source files to C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\test\n [javac] [parsing started C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\src\\\n MessageUtil.java]\n [javac] [parsing completed 18ms]\n [javac] [parsing started C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\src\\\n TestMessageUtil.java]\n [javac] [parsing completed 2ms]\n [javac] [search path for source files: C:\\JUNIT_WORKSPACE\\\n TestJunitWithAnt\\src] \n [javac] [loading java\\lang\\Object.class(java\\lang:Object.class)]\n [javac] [loading java\\lang\\String.class(java\\lang:String.class)]\n [javac] [loading org\\junit\\Test.class(org\\junit:Test.class)]\n [javac] [loading org\\junit\\Ignore.class(org\\junit:Ignore.class)]\n [javac] [loading org\\junit\\Assert.class(org\\junit:Assert.class)]\n [javac] [loading java\\lang\\annotation\\Retention.class\n (java\\lang\\annotation:Retention.class)]\n [javac] [loading java\\lang\\annotation\\RetentionPolicy.class\n (java\\lang\\annotation:RetentionPolicy.class)]\n [javac] [loading java\\lang\\annotation\\Target.class\n (java\\lang\\annotation:Target.class)]\n [javac] [loading java\\lang\\annotation\\ElementType.class\n (java\\lang\\annotation:ElementType.class)]\n [javac] [loading java\\lang\\annotation\\Annotation.class\n (java\\lang\\annotation:Annotation.class)]\n [javac] [checking MessageUtil]\n [javac] [loading java\\lang\\System.class(java\\lang:System.class)]\n [javac] [loading java\\io\\PrintStream.class(java\\io:PrintStream.class)]\n [javac] [loading java\\io\\FilterOutputStream.class\n (java\\io:FilterOutputStream.class)]\n [javac] [loading java\\io\\OutputStream.class(java\\io:OutputStream.class)]\n [javac] [loading java\\lang\\StringBuilder.class\n (java\\lang:StringBuilder.class)]\n [javac] [loading java\\lang\\AbstractStringBuilder.class\n (java\\lang:AbstractStringBuilder.class)]\n [javac] [loading java\\lang\\CharSequence.class(java\\lang:CharSequence.class)]\n [javac] [loading java\\io\\Serializable.class(java\\io:Serializable.class)]\n [javac] [loading java\\lang\\Comparable.class(java\\lang:Comparable.class)]\n [javac] [loading java\\lang\\StringBuffer.class(java\\lang:StringBuffer.class)]\n [javac] [wrote C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\test\\MessageUtil.class]\n [javac] [checking TestMessageUtil]\n [javac] [wrote C:\\JUNIT_WORKSPACE\\TestJunitWithAnt\\test\\TestMessageUtil.class]\n [javac] [total 281ms]\n\ntest:\n [junit] Testsuite: TestMessageUtil\n [junit] Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 0.008 sec\n [junit]\n [junit] ------------- Standard Output ---------------\n [junit] Inside testPrintMessage()\n [junit] Robert\n [junit] Inside testSalutationMessage()\n [junit] Hi!Robert\n [junit] ------------- ---------------- ---------------\n\nBUILD SUCCESSFUL\nTotal time: 0 seconds\n" }, { "code": null, "e": 63561, "s": 63501, "text": "To set up JUnit with eclipse, follow the steps given below." }, { "code": null, "e": 63637, "s": 63561, "text": "Download a JUnit jar based on the operating system you have on your system." }, { "code": null, "e": 63706, "s": 63637, "text": "Assume you have copied the above JAR file onto the folder C:\\>JUnit." }, { "code": null, "e": 63881, "s": 63706, "text": "Open eclipse → right click on project and click on property > Build Path > Configure Build Path and add the junit-4.10.jar in the libraries using the button Add External Jar." }, { "code": null, "e": 64128, "s": 63881, "text": "We assume that your Eclipse has inbuilt JUnit plugin. If it is not available in C:\\>eclipse\\plugins directory, then you can download it from JUnit Plugin. Unzip the downloaded zip file in the plugin folder of the Eclipse. Finally restart Eclipse." }, { "code": null, "e": 64195, "s": 64128, "text": "Now your Eclipse is ready for the development of JUnit test cases." }, { "code": null, "e": 64306, "s": 64195, "text": "Create a project TestJunit in Eclipse at any location. Then create a class MessageUtil to test in the project." }, { "code": null, "e": 64681, "s": 64306, "text": " \n/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message;\n }\n \n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n} " }, { "code": null, "e": 64727, "s": 64681, "text": "Create a test class TestJunit in the project." }, { "code": null, "e": 65030, "s": 64727, "text": " \nimport org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\t\n String message = \"Hello World\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testPrintMessage() {\t \n assertEquals(message,messageUtil.printMessage());\n }\n}" }, { "code": null, "e": 65074, "s": 65030, "text": "Following should be the project structure −" }, { "code": null, "e": 65161, "s": 65074, "text": "Finally, right click the program and run as JUnit to verify the output of the program." }, { "code": null, "e": 65180, "s": 65161, "text": "Verify the result." }, { "code": null, "e": 65217, "s": 65180, "text": "Following are the JUnit extensions −" }, { "code": null, "e": 65224, "s": 65217, "text": "Cactus" }, { "code": null, "e": 65233, "s": 65224, "text": "JWebUnit" }, { "code": null, "e": 65241, "s": 65233, "text": "XMLUnit" }, { "code": null, "e": 65252, "s": 65241, "text": "MockObject" }, { "code": null, "e": 65560, "s": 65252, "text": "Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs, Filters). The intent of Cactus is to lower the cost of writing tests for server-side code. It uses JUnit and extends it. Cactus implements an in-container strategy that executes the tests inside a container." }, { "code": null, "e": 65609, "s": 65560, "text": "Cactus ecosystem is made of several components −" }, { "code": null, "e": 65712, "s": 65609, "text": "Cactus Framework is the heart of Cactus. It is the engine that provides the API to write Cactus tests." }, { "code": null, "e": 65815, "s": 65712, "text": "Cactus Framework is the heart of Cactus. It is the engine that provides the API to write Cactus tests." }, { "code": null, "e": 65974, "s": 65815, "text": "Cactus Integration Modules are front-ends and frameworks that provide easy ways of using the Cactus Framework (Ant scripts, Eclipse plugin, and Maven plugin)." }, { "code": null, "e": 66133, "s": 65974, "text": "Cactus Integration Modules are front-ends and frameworks that provide easy ways of using the Cactus Framework (Ant scripts, Eclipse plugin, and Maven plugin)." }, { "code": null, "e": 66189, "s": 66133, "text": "The following code demonstrates how Cactus can be used." }, { "code": null, "e": 66886, "s": 66189, "text": "import org.apache.cactus.*;\nimport junit.framework.*;\n\npublic class TestSampleServlet extends ServletTestCase {\n @Test\n public void testServlet() {\n // Initialize class to test\n SampleServlet servlet = new SampleServlet();\n\n // Set a variable in session as the doSomething()\n // method that we are testing \n session.setAttribute(\"name\", \"value\");\n\n // Call the method to test, passing an \n // HttpServletRequest object (for example)\n String result = servlet.doSomething(request);\n\n // Perform verification that test was successful\n assertEquals(\"something\", result);\n assertEquals(\"otherValue\", session.getAttribute(\"otherName\"));\n }\n}" }, { "code": null, "e": 67109, "s": 66886, "text": "JWebUnit is a Java-based testing framework for web applications. It wraps existing testing frameworks such as HtmlUnit and Selenium with a unified, simple testing interface to test the correctness of your web applications." }, { "code": null, "e": 67403, "s": 67109, "text": "JWebUnit provides a high-level Java API for navigating a web application combined with a set of assertions to verify the application's correctness. This includes navigation via links, form entry and submission, validation of table contents, and other typical business web application features." }, { "code": null, "e": 67663, "s": 67403, "text": "The simple navigation methods and ready-to-use assertions allow for more rapid test creation than using only JUnit or HtmlUnit. And if you want to switch from HtmlUnit to other plugins such as Selenium (available soon), there is no need to rewrite your tests." }, { "code": null, "e": 67686, "s": 67663, "text": "Here is a sample code." }, { "code": null, "e": 68179, "s": 67686, "text": "import junit.framework.TestCase;\nimport net.sourceforge.jwebunit.WebTester;\n\npublic class ExampleWebTestCase extends TestCase {\n private WebTester tester;\n \n public ExampleWebTestCase(String name) {\n super(name);\n tester = new WebTester();\n }\n\t\n //set base url\n public void setUp() throws Exception {\n getTestContext().setBaseUrl(\"http://myserver:8080/myapp\");\n }\n\t\n // test base info\n @Test\n public void testInfoPage() {\n beginAt(\"/info.html\");\n }\n}" }, { "code": null, "e": 68314, "s": 68179, "text": "XMLUnit provides a single JUnit extension class, XMLTestCase, and a set of supporting classes that allow assertions to be made about −" }, { "code": null, "e": 68393, "s": 68314, "text": "The differences between two pieces of XML (via Diff and DetailedDiff classes)." }, { "code": null, "e": 68472, "s": 68393, "text": "The differences between two pieces of XML (via Diff and DetailedDiff classes)." }, { "code": null, "e": 68526, "s": 68472, "text": "The validity of a piece of XML (via Validator class)." }, { "code": null, "e": 68580, "s": 68526, "text": "The validity of a piece of XML (via Validator class)." }, { "code": null, "e": 68657, "s": 68580, "text": "The outcome of transforming a piece of XML using XSLT (via Transform class)." }, { "code": null, "e": 68734, "s": 68657, "text": "The outcome of transforming a piece of XML using XSLT (via Transform class)." }, { "code": null, "e": 68844, "s": 68734, "text": "The evaluation of an XPath expression on a piece of XML (via classes implementing the XpathEngine interface)." }, { "code": null, "e": 68954, "s": 68844, "text": "The evaluation of an XPath expression on a piece of XML (via classes implementing the XpathEngine interface)." }, { "code": null, "e": 69045, "s": 68954, "text": "Individual nodes in a piece of XML that are exposed by DOM Traversal (via NodeTest class)." }, { "code": null, "e": 69136, "s": 69045, "text": "Individual nodes in a piece of XML that are exposed by DOM Traversal (via NodeTest class)." }, { "code": null, "e": 69279, "s": 69136, "text": "Let us assume we have two pieces of XML that we wish to compare and assert that they are equal. We could write a simple test class like this −" }, { "code": null, "e": 69712, "s": 69279, "text": "import org.custommonkey.xmlunit.XMLTestCase;\n\npublic class MyXMLTestCase extends XMLTestCase {\n\n // this test method compare two pieces of the XML\n @Test\n public void testForXMLEquality() throws Exception {\n String myControlXML = \"<msg><uuid>0x00435A8C</uuid></msg>\";\n String myTestXML = \"<msg><localId>2376</localId></msg>\";\n assertXMLEqual(\"Comparing test xml to control xml\", myControlXML, myTestXML);\n }\n}" }, { "code": null, "e": 69909, "s": 69712, "text": "In a unit test, mock objects can simulate the behavior of complex, real (non-mock) objects and are therefore useful when a real object is impractical or impossible to incorporate into a unit test." }, { "code": null, "e": 69971, "s": 69909, "text": "The common coding style for testing with mock objects is to −" }, { "code": null, "e": 70005, "s": 69971, "text": "Create instances of mock objects." }, { "code": null, "e": 70053, "s": 70005, "text": "Set state and expectations in the mock objects." }, { "code": null, "e": 70105, "s": 70053, "text": "Invoke domain code with mock objects as parameters." }, { "code": null, "e": 70145, "s": 70105, "text": "Verify consistency in the mock objects." }, { "code": null, "e": 70198, "s": 70145, "text": "Given below is an example of MockObject using Jmock." }, { "code": null, "e": 70756, "s": 70198, "text": "import org.jmock.Mockery;\nimport org.jmock.Expectations;\n\nclass PubTest extends TestCase {\n Mockery context = new Mockery();\n public void testSubReceivesMessage() {\n // set up\n final Sub sub = context.mock(Sub.class);\n\n Pub pub = new Pub();\n pub.add(sub);\n \n final String message = \"message\";\n \n // expectations\n context.checking(new Expectations() {\n oneOf (sub).receive(message);\n });\n\n // execute\n pub.publish(message);\n \n // verify\n context.assertIsSatisfied();\n }\n}" }, { "code": null, "e": 70791, "s": 70756, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 70806, "s": 70791, "text": " Nishita Bhatt" }, { "code": null, "e": 70841, "s": 70806, "text": "\n 56 Lectures \n 7.5 hours \n" }, { "code": null, "e": 70857, "s": 70841, "text": " Dinesh Varyani" }, { "code": null, "e": 70864, "s": 70857, "text": " Print" }, { "code": null, "e": 70875, "s": 70864, "text": " Add Notes" } ]
Program to count maximum number of distinct pairs whose differences are larger than target in Python
Suppose we have a list of numbers called nums and another value target. We have to find the maximum number of pairs where for each pair i < j, i and j are not in any other pair, and |nums[i] - nums[j]| >= target. So, if the input is like nums = [2, 4, 6, 10, 11], target = 5, then the output will be 2, as we can get pairs: (2, 6), (5, 10) To solve this, we will follow these steps − N := size of A sort the list A ans := 0 j := N / 2 for i in range 0 to N / 2, dowhile j < N and A[j] - A[i] < target, doj := j + 1if j < N, thenans := ans + 1j := j + 1 while j < N and A[j] - A[i] < target, doj := j + 1 j := j + 1 if j < N, thenans := ans + 1j := j + 1 ans := ans + 1 j := j + 1 return ans Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, A, target): N = len(A) A.sort() ans = 0 j = N >> 1 for i in range(N >> 1): while j < N and A[j] - A[i] < target: j += 1 if j < N: ans += 1 j += 1 return ans ob = Solution() nums = [2, 4, 6, 10, 11] target = 5 print(ob.solve(nums, target)) [2, 4, 6, 10, 11], 5 2
[ { "code": null, "e": 1275, "s": 1062, "text": "Suppose we have a list of numbers called nums and another value target. We have to find the maximum number of pairs where for each pair i < j, i and j are not in any other pair, and |nums[i] - nums[j]| >= target." }, { "code": null, "e": 1402, "s": 1275, "text": "So, if the input is like nums = [2, 4, 6, 10, 11], target = 5, then the output will be 2, as we can get pairs: (2, 6), (5, 10)" }, { "code": null, "e": 1446, "s": 1402, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1461, "s": 1446, "text": "N := size of A" }, { "code": null, "e": 1477, "s": 1461, "text": "sort the list A" }, { "code": null, "e": 1486, "s": 1477, "text": "ans := 0" }, { "code": null, "e": 1497, "s": 1486, "text": "j := N / 2" }, { "code": null, "e": 1615, "s": 1497, "text": "for i in range 0 to N / 2, dowhile j < N and A[j] - A[i] < target, doj := j + 1if j < N, thenans := ans + 1j := j + 1" }, { "code": null, "e": 1666, "s": 1615, "text": "while j < N and A[j] - A[i] < target, doj := j + 1" }, { "code": null, "e": 1677, "s": 1666, "text": "j := j + 1" }, { "code": null, "e": 1716, "s": 1677, "text": "if j < N, thenans := ans + 1j := j + 1" }, { "code": null, "e": 1731, "s": 1716, "text": "ans := ans + 1" }, { "code": null, "e": 1742, "s": 1731, "text": "j := j + 1" }, { "code": null, "e": 1753, "s": 1742, "text": "return ans" }, { "code": null, "e": 1823, "s": 1753, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1834, "s": 1823, "text": " Live Demo" }, { "code": null, "e": 2198, "s": 1834, "text": "class Solution:\n def solve(self, A, target):\n N = len(A)\n A.sort()\n ans = 0\n j = N >> 1\n for i in range(N >> 1):\n while j < N and A[j] - A[i] < target:\n j += 1\n if j < N:\n ans += 1\n j += 1\n return ans\nob = Solution()\nnums = [2, 4, 6, 10, 11]\ntarget = 5\nprint(ob.solve(nums, target))" }, { "code": null, "e": 2219, "s": 2198, "text": "[2, 4, 6, 10, 11], 5" }, { "code": null, "e": 2221, "s": 2219, "text": "2" } ]
Formatting float column of Dataframe in Pandas - GeeksforGeeks
21 Aug, 2020 While presenting the data, showing the data in the required format is also an important and crucial part. Sometimes, the value is so big that we want to show only desired part of this or we can say in some desired format. Let’s see different methods of formatting integer column of Dataframe in Pandas. Code #1 : Round off the column values to two decimal places. # import pandas lib as pdimport pandas as pd # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'], 'Expense': [ 21525220.653, 31125840.875, 23135428.768, 56245263.942]} # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense']) print("Given Dataframe :\n", dataframe) # round to two decimal places in python pandaspd.options.display.float_format = '{:.2f}'.format print('\nResult :\n', dataframe) Output: Code #2 : Format ‘Expense’ column with commas and round off to two decimal places. # import pandas lib as pdimport pandas as pd # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'], 'Expense':[ 21525220.653, 31125840.875, 23135428.768, 56245263.942]} # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense']) print("Given Dataframe :\n", dataframe) # Format with commas and round off to two decimal places in pandaspd.options.display.float_format = '{:, .2f}'.format print('\nResult :\n', dataframe) Output: Code #3 : Format ‘Expense’ column with commas and Dollar sign with two decimal places. # import pandas lib as pdimport pandas as pd # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'], 'Expense':[ 21525220.653, 31125840.875, 23135428.768, 56245263.942]} # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense']) print("Given Dataframe :\n", dataframe) # Format with dollars, commas and round off# to two decimal places in pandaspd.options.display.float_format = '${:, .2f}'.format print('\nResult :\n', dataframe) Output: varun bankapur pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe sum() function in Python
[ { "code": null, "e": 24894, "s": 24866, "text": "\n21 Aug, 2020" }, { "code": null, "e": 25116, "s": 24894, "text": "While presenting the data, showing the data in the required format is also an important and crucial part. Sometimes, the value is so big that we want to show only desired part of this or we can say in some desired format." }, { "code": null, "e": 25197, "s": 25116, "text": "Let’s see different methods of formatting integer column of Dataframe in Pandas." }, { "code": null, "e": 25258, "s": 25197, "text": "Code #1 : Round off the column values to two decimal places." }, { "code": "# import pandas lib as pdimport pandas as pd # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'], 'Expense': [ 21525220.653, 31125840.875, 23135428.768, 56245263.942]} # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense']) print(\"Given Dataframe :\\n\", dataframe) # round to two decimal places in python pandaspd.options.display.float_format = '{:.2f}'.format print('\\nResult :\\n', dataframe)", "e": 25725, "s": 25258, "text": null }, { "code": null, "e": 25733, "s": 25725, "text": "Output:" }, { "code": null, "e": 25817, "s": 25733, "text": " Code #2 : Format ‘Expense’ column with commas and round off to two decimal places." }, { "code": "# import pandas lib as pdimport pandas as pd # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'], 'Expense':[ 21525220.653, 31125840.875, 23135428.768, 56245263.942]} # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense']) print(\"Given Dataframe :\\n\", dataframe) # Format with commas and round off to two decimal places in pandaspd.options.display.float_format = '{:, .2f}'.format print('\\nResult :\\n', dataframe)", "e": 26308, "s": 25817, "text": null }, { "code": null, "e": 26316, "s": 26308, "text": "Output:" }, { "code": null, "e": 26404, "s": 26316, "text": " Code #3 : Format ‘Expense’ column with commas and Dollar sign with two decimal places." }, { "code": "# import pandas lib as pdimport pandas as pd # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'], 'Expense':[ 21525220.653, 31125840.875, 23135428.768, 56245263.942]} # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense']) print(\"Given Dataframe :\\n\", dataframe) # Format with dollars, commas and round off# to two decimal places in pandaspd.options.display.float_format = '${:, .2f}'.format print('\\nResult :\\n', dataframe)", "e": 26906, "s": 26404, "text": null }, { "code": null, "e": 26914, "s": 26906, "text": "Output:" }, { "code": null, "e": 26929, "s": 26914, "text": "varun bankapur" }, { "code": null, "e": 26954, "s": 26929, "text": "pandas-dataframe-program" }, { "code": null, "e": 26961, "s": 26954, "text": "Picked" }, { "code": null, "e": 26985, "s": 26961, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26999, "s": 26985, "text": "Python-pandas" }, { "code": null, "e": 27023, "s": 26999, "text": "Technical Scripter 2018" }, { "code": null, "e": 27030, "s": 27023, "text": "Python" }, { "code": null, "e": 27049, "s": 27030, "text": "Technical Scripter" }, { "code": null, "e": 27147, "s": 27049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27165, "s": 27147, "text": "Python Dictionary" }, { "code": null, "e": 27187, "s": 27165, "text": "Enumerate() in Python" }, { "code": null, "e": 27219, "s": 27187, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27261, "s": 27219, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27298, "s": 27261, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27342, "s": 27298, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27371, "s": 27342, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27413, "s": 27371, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27469, "s": 27413, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Python 3 - List insert() Method
The insert() method inserts object obj into list at offset index. Following is the syntax for insert() method − list.insert(index, obj) index − This is the Index where the object obj need to be inserted. index − This is the Index where the object obj need to be inserted. obj − This is the Object to be inserted into the given list. obj − This is the Object to be inserted into the given list. This method does not return any value but it inserts the given element at the given index. The following example shows the usage of insert() method. #!/usr/bin/python3 list1 = ['physics', 'chemistry', 'maths'] list1.insert(1, 'Biology') print ('Final list : ', list1) When we run above program, it produces the following result − Final list : ['physics', 'Biology', 'chemistry', 'maths'] 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2406, "s": 2340, "text": "The insert() method inserts object obj into list at offset index." }, { "code": null, "e": 2452, "s": 2406, "text": "Following is the syntax for insert() method −" }, { "code": null, "e": 2477, "s": 2452, "text": "list.insert(index, obj)\n" }, { "code": null, "e": 2545, "s": 2477, "text": "index − This is the Index where the object obj need to be inserted." }, { "code": null, "e": 2613, "s": 2545, "text": "index − This is the Index where the object obj need to be inserted." }, { "code": null, "e": 2674, "s": 2613, "text": "obj − This is the Object to be inserted into the given list." }, { "code": null, "e": 2735, "s": 2674, "text": "obj − This is the Object to be inserted into the given list." }, { "code": null, "e": 2826, "s": 2735, "text": "This method does not return any value but it inserts the given element at the given index." }, { "code": null, "e": 2884, "s": 2826, "text": "The following example shows the usage of insert() method." }, { "code": null, "e": 3004, "s": 2884, "text": "#!/usr/bin/python3\n\nlist1 = ['physics', 'chemistry', 'maths']\nlist1.insert(1, 'Biology')\nprint ('Final list : ', list1)" }, { "code": null, "e": 3066, "s": 3004, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 3126, "s": 3066, "text": "Final list : ['physics', 'Biology', 'chemistry', 'maths']\n" }, { "code": null, "e": 3163, "s": 3126, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3179, "s": 3163, "text": " Malhar Lathkar" }, { "code": null, "e": 3212, "s": 3179, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3231, "s": 3212, "text": " Arnab Chakraborty" }, { "code": null, "e": 3266, "s": 3231, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3288, "s": 3266, "text": " In28Minutes Official" }, { "code": null, "e": 3322, "s": 3288, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3350, "s": 3322, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3385, "s": 3350, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3399, "s": 3385, "text": " Lets Kode It" }, { "code": null, "e": 3432, "s": 3399, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3449, "s": 3432, "text": " Abhilash Nelson" }, { "code": null, "e": 3456, "s": 3449, "text": " Print" }, { "code": null, "e": 3467, "s": 3456, "text": " Add Notes" } ]
How to delete element from linked list for listview in Android?
This example demonstrate about How to delete element from linked list for listview 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"?> <LinearLayoutxmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/name" android:layout_width = "match_parent" android:hint = "Enter Name" android:layout_height = "wrap_content" /> <LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content"> <Button android:id = "@+id/save" android:text = "Save" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <Button android:id = "@+id/refresh" android:text = "Refresh" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <Button android:id = "@+id/delete" android:text = "Delete" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> <ListView android:id = "@+id/listView" android:layout_width = "match_parent" android:layout_height = "wrap_content"> </ListView> </LinearLayout> In the above code, we have taken name as Edit text, when user click on save button it will store the data into arraylist. Click on delete button to delete the record from listview. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.LinkedList; public class MainActivityextends AppCompatActivity { Button save, refresh; EditTextname; ArrayAdapterarrayAdapter; LinkedList<String>link_list; private ListViewlistView; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); link_list = new LinkedList<String>(); name = findViewById(R.id.name); listView = findViewById(R.id.listView); findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { arrayAdapter.notifyDataSetChanged(); listView.invalidateViews(); listView.refreshDrawableState(); } }); findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (link_list.size() >0) { if (!name.getText().toString().isEmpty()) { link_list.remove(name.getText().toString()); arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, link_list); listView.setAdapter(arrayAdapter); Toast.makeText(MainActivity.this, "deleted", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(MainActivity.this, "There is no element to delete", Toast.LENGTH_LONG).show(); } } }); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty()) { link_list.add(name.getText().toString()); arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, link_list); listView.setAdapter(arrayAdapter); Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); } else { name.setError("Enter NAME"); } } }); } } 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 – In the above result, we are inserting name into linked list and displaying name in listview. Now same element we are deleting from listivew by clicking delete button. Click here to download the project code
[ { "code": null, "e": 1156, "s": 1062, "text": "This example demonstrate about How to delete element from linked list for listview in Android" }, { "code": null, "e": 1285, "s": 1156, "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": 1350, "s": 1285, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2680, "s": 1350, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayoutxmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\">\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/refresh\"\n android:text = \"Refresh\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/delete\"\n android:text = \"Delete\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 2861, "s": 2680, "text": "In the above code, we have taken name as Edit text, when user click on save button it will store the data into arraylist. Click on delete button to delete the record from listview." }, { "code": null, "e": 2918, "s": 2861, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5362, "s": 2918, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.LinkedList;\npublic class MainActivityextends AppCompatActivity {\n Button save, refresh;\n EditTextname;\n ArrayAdapterarrayAdapter;\n LinkedList<String>link_list;\n private ListViewlistView;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n link_list = new LinkedList<String>();\n name = findViewById(R.id.name);\n listView = findViewById(R.id.listView);\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (link_list.size() >0) {\n if (!name.getText().toString().isEmpty()) {\n link_list.remove(name.getText().toString());\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, link_list);\n listView.setAdapter(arrayAdapter);\n Toast.makeText(MainActivity.this, \"deleted\", Toast.LENGTH_LONG).show();\n }\n } else {\n Toast.makeText(MainActivity.this, \"There is no element to delete\", Toast.LENGTH_LONG).show();\n }\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n link_list.add(name.getText().toString());\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, link_list);\n listView.setAdapter(arrayAdapter);\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n name.setError(\"Enter NAME\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 5709, "s": 5362, "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": 5802, "s": 5709, "text": "In the above result, we are inserting name into linked list and displaying name in listview." }, { "code": null, "e": 5876, "s": 5802, "text": "Now same element we are deleting from listivew by clicking delete button." }, { "code": null, "e": 5918, "s": 5876, "text": "Click here to download the project code" } ]
Opening and reading a file with askopenfilename in Tkinter?
When a user wants to open a file from a directory, the preferred way to do this is to display a popup where the user selects a file to Open. Like most tools and widgets, Tkinter provides us a way to open a dialog for opening a file, reading a file, saving a file. All these functionalities are part of filedialog Module in Python. Just like other widgets, filedialog needs to be imported explicitly in the notebook. There are certain other modules that contain the filedialog such as, askdirectory, askopenfilename, askopenfile, askopenfilenames, asksaveasfilename, etc. In this example, we will define a function to open and read the file using askopenfilename. We will define an application which contains a button to open a file and will pack the content of the file in a Label widget. In order to read the file content, we will use the read() method along with the filename. #Import tkinter library from tkinter import * from tkinter import ttk from tkinter import filedialog #Create an instance of tkinter frame or window win= Tk() win.geometry("750x150") #Define a function to Opening the specific file using filedialog def open_files(): path= filedialog.askopenfilename(title="Select a file", filetypes=(("text files","*.txt"), ("all files","*.*"))) file= open(path,'r') txt= file.read() label.config(text=txt, font=('Courier 13 bold')) file.close() button.config(state=DISABLED) win.geometry("750x450") #Create an Empty Label to Read the content of the File label= Label(win,text="", font=('Courier 13 bold')) label.pack() #Create a button for opening files button=ttk.Button(win, text="Open",command=open_files) button.pack(pady=30) win.mainloop() Running the above code will display a window which contains a button which when clicked, will open a new window to load and read the file content. Click the "Open" button to open the file(text, "*") in the window.
[ { "code": null, "e": 1633, "s": 1062, "text": "When a user wants to open a file from a directory, the preferred way to do this is to display a popup where the user selects a file to Open. Like most tools and widgets, Tkinter provides us a way to open a dialog for opening a file, reading a file, saving a file. All these functionalities are part of filedialog Module in Python. Just like other widgets, filedialog needs to be imported explicitly in the notebook. There are certain other modules that contain the filedialog such as, askdirectory, askopenfilename, askopenfile, askopenfilenames, asksaveasfilename, etc." }, { "code": null, "e": 1725, "s": 1633, "text": "In this example, we will define a function to open and read the file using askopenfilename." }, { "code": null, "e": 1941, "s": 1725, "text": "We will define an application which contains a button to open a file and will pack the content of the file in a Label widget. In order to read the file content, we will use the read() method along with the filename." }, { "code": null, "e": 2741, "s": 1941, "text": "#Import tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\n#Create an instance of tkinter frame or window\nwin= Tk()\nwin.geometry(\"750x150\")\n#Define a function to Opening the specific file using filedialog\ndef open_files():\n path= filedialog.askopenfilename(title=\"Select a file\", filetypes=((\"text files\",\"*.txt\"),\n(\"all files\",\"*.*\")))\n\n file= open(path,'r')\n txt= file.read()\n label.config(text=txt, font=('Courier 13 bold'))\n file.close()\n button.config(state=DISABLED)\n win.geometry(\"750x450\")\n#Create an Empty Label to Read the content of the File\nlabel= Label(win,text=\"\", font=('Courier 13 bold'))\nlabel.pack()\n#Create a button for opening files\nbutton=ttk.Button(win, text=\"Open\",command=open_files)\nbutton.pack(pady=30)\nwin.mainloop()" }, { "code": null, "e": 2888, "s": 2741, "text": "Running the above code will display a window which contains a button which when clicked, will open a new window to load and read the file content." }, { "code": null, "e": 2955, "s": 2888, "text": "Click the \"Open\" button to open the file(text, \"*\") in the window." } ]
Lambda Expressions in C#
A lambda expression in C# describes a pattern. Lambda Expressions has the token => in an expression context. This is read as “goes to” operator and used when a lambda expression is declared. Here, we are finding the first occurrence of the element greater than 50 from a list. list.FindIndex(x => x > 50); Above the token => is used. The same is shown below − Live Demo using System; using System.Collections.Generic; class Demo { static void Main() { List<int> list = new List<int> { 44, 6, 34, 23, 78 }; int res = list.FindIndex(x => x > 50); Console.WriteLine("Index: "+res); } } Index: 4
[ { "code": null, "e": 1109, "s": 1062, "text": "A lambda expression in C# describes a pattern." }, { "code": null, "e": 1253, "s": 1109, "text": "Lambda Expressions has the token => in an expression context. This is read as “goes to” operator and used when a lambda expression is declared." }, { "code": null, "e": 1339, "s": 1253, "text": "Here, we are finding the first occurrence of the element greater than 50 from a list." }, { "code": null, "e": 1368, "s": 1339, "text": "list.FindIndex(x => x > 50);" }, { "code": null, "e": 1422, "s": 1368, "text": "Above the token => is used. The same is shown below −" }, { "code": null, "e": 1433, "s": 1422, "text": " Live Demo" }, { "code": null, "e": 1672, "s": 1433, "text": "using System;\nusing System.Collections.Generic;\n\nclass Demo {\n static void Main() {\n List<int> list = new List<int> { 44, 6, 34, 23, 78 };\n\n int res = list.FindIndex(x => x > 50);\n Console.WriteLine(\"Index: \"+res);\n }\n}" }, { "code": null, "e": 1681, "s": 1672, "text": "Index: 4" } ]
ARIMA Model Python Example — Time Series Forecasting | by Cory Maklin | Towards Data Science
The ability to make predictions based upon historical observations creates a competitive advantage. For example, if an organization has the capacity to better forecast the sales quantities of a product, it will be in a more favourable position to optimize inventory levels. This can result in an increased liquidity of the organizations cash reserves, decrease of working capital and improved customer satisfaction by decreasing the backlog of orders. In the domain of machine learning, there’s a specific collection of methods and techniques particularly well suited for predicting the value of a dependent variable according to time. In the proceeding article, we’ll cover AutoRegressive Integrated Moving Average (ARIMA). We refer to a series of data points indexed (or graphed) in time order as a time series. A time series can be broken down into 3 components. Trend: Upward & downward movement of the data with time over a large period of time (i.e. house appreciation) Seasonality: Seasonal variance (i.e. an increase in demand for ice cream during summer) Noise: Spikes & troughs at random intervals Before applying any statistical model on a time series, we want to ensure it’s stationary. If a time series is stationary and has a particular behaviour over a given time interval, then it is safe to assume that it will have same behaviour at some later point in time. Most statistical modelling methods assume or require the time series to be stationary. The statsmodels library provides a suite of functions for working with time series data. import numpy as npimport pandas as pdfrom matplotlib import pyplot as pltfrom statsmodels.tsa.stattools import adfullerfrom statsmodels.tsa.seasonal import seasonal_decomposefrom statsmodels.tsa.arima_model import ARIMAfrom pandas.plotting import register_matplotlib_convertersregister_matplotlib_converters() We’ll be working with a dataset that contains the number of airplane passengers on a given day. df = pd.read_csv('air_passengers.csv', parse_dates = ['Month'], index_col = ['Month'])df.head()plt.xlabel('Date')plt.ylabel('Number of air passengers')plt.plot(df) As mentioned previously, before we can build a model, we must ensure that the time series is stationary. There are two primary way to determine whether a given time series is stationary. Rolling Statistics: Plot the rolling mean and rolling standard deviation. The time series is stationary if they remain constant with time (with the naked eye look to see if the lines are straight and parallel to the x-axis). Augmented Dickey-Fuller Test: The time series is considered stationary if the p-value is low (according to the null hypothesis) and the critical values at 1%, 5%, 10% confidence intervals are as close as possible to the ADF Statistics For those who don’t understand the difference between average and rolling average, a 10-day rolling average would average out the closing prices for the first 10 days as the first data point. The next data point would drop the earliest price, add the price on day 11 and take the average, and so on as shown below. rolling_mean = df.rolling(window = 12).mean()rolling_std = df.rolling(window = 12).std()plt.plot(df, color = 'blue', label = 'Original')plt.plot(rolling_mean, color = 'red', label = 'Rolling Mean')plt.plot(rolling_std, color = 'black', label = 'Rolling Std')plt.legend(loc = 'best')plt.title('Rolling Mean & Rolling Standard Deviation')plt.show() As you can see, the rolling mean and rolling standard deviation increase with time. Therefore, we can conclude that the time series is not stationary. result = adfuller(df['Passengers'])print('ADF Statistic: {}'.format(result[0]))print('p-value: {}'.format(result[1]))print('Critical Values:')for key, value in result[4].items(): print('\t{}: {}'.format(key, value)) The ADF Statistic is far from the critical values and the p-value is greater than the threshold (0.05). Thus, we can conclude that the time series is not stationary. Taking the log of the dependent variable is as simple way of lowering the rate at which rolling mean increases. df_log = np.log(df)plt.plot(df_log) Let’s create a function to run the two tests which determine whether a given time series is stationary. def get_stationarity(timeseries): # rolling statistics rolling_mean = timeseries.rolling(window=12).mean() rolling_std = timeseries.rolling(window=12).std() # rolling statistics plot original = plt.plot(timeseries, color='blue', label='Original') mean = plt.plot(rolling_mean, color='red', label='Rolling Mean') std = plt.plot(rolling_std, color='black', label='Rolling Std') plt.legend(loc='best') plt.title('Rolling Mean & Standard Deviation') plt.show(block=False) # Dickey–Fuller test: result = adfuller(timeseries['Passengers']) print('ADF Statistic: {}'.format(result[0])) print('p-value: {}'.format(result[1])) print('Critical Values:') for key, value in result[4].items(): print('\t{}: {}'.format(key, value)) There are multiple transformations that we can apply to a time series to render it stationary. For instance, we subtract the rolling mean. rolling_mean = df_log.rolling(window=12).mean()df_log_minus_mean = df_log - rolling_meandf_log_minus_mean.dropna(inplace=True)get_stationarity(df_log_minus_mean) As we can see, after subtracting the mean, the rolling mean and standard deviation are approximately horizontal. The p-value is below the threshold of 0.05 and the ADF Statistic is close to the critical values. Therefore, the time series is stationary. Applying exponential decay is another way of transforming a time series such that it is stationary. rolling_mean_exp_decay = df_log.ewm(halflife=12, min_periods=0, adjust=True).mean()df_log_exp_decay = df_log - rolling_mean_exp_decaydf_log_exp_decay.dropna(inplace=True)get_stationarity(df_log_exp_decay) Exponential decay performed worse than subtracting the rolling mean. However, it is still more stationary than the original. Let’s try one more method to determine whether an even better solution exists. When applying time shifting, we subtract every the point by the one that preceded it. null, (x1−x0), (x2−x1), (x3−x2), (x4−x3), ..., (xn−xn−1) df_log_shift = df_log - df_log.shift()df_log_shift.dropna(inplace=True)get_stationarity(df_log_shift) Time shifting performed worse than subtracting the rolling mean. However, it is still more stationary than the original. Autoregressive models operate under the premise that past values have an effect on current values. AR models are commonly used in analyzing nature, economics, and other time-varying processes. As long as the assumption holds, we can build a linear regression model that attempts to predict value of a dependent variable today, given the values it had on previous days. The order of the AR model corresponds to the number of days incorporated in the formula. Assumes the value of the dependent variable on the current day depends on the previous days error terms. The formula can be expressed as: You’ll also come across the equation written as: where μ is the mean of the series, the θ1, ..., θq are the parameters of the model and the εt, εt−1,..., εt−q are white noise error terms. The value of q is called the order of the MA model. The ARMA model is simply the combination of the AR and MA models. The ARIMA (aka Box-Jenkins) model adds differencing to an ARMA model. Differencing subtracts the current value from the previous and can be used to transform a time series into one that’s stationary. For example, first-order differencing addresses linear trends, and employs the transformation zi = yi — yi-1. Second-order differencing addresses quadratic trends and employs a first-order difference of a first-order difference, namely zi = (yi — yi-1) — (yi-1 — yi-2), and so on. Three integers (p, d, q) are typically used to parametrize ARIMA models. p: number of autoregressive terms (AR order) d: number of nonseasonal differences (differencing order) q: number of moving-average terms (MA order) The correlation between the observations at the current point in time and the observations at all previous points in time. We can use ACF to determine the optimal number of MA terms. The number of terms determines the order of the model. As the name implies, PACF is a subset of ACF. PACF expresses the correlation between observations made at two points in time while accounting for any influence from other data points. We can use PACF to determine the optimal number of terms to use in the AR model. The number of terms determines the order of the model. Let’s take a look at an example. Recall, that PACF can be used to figure out the best order of the AR model. The horizontal blue dashed lines represent the significance thresholds. The vertical lines represent the ACF and PACF values at in point in time. Only the vertical lines that exceed the horizontal lines are considered significant. Thus, we’d use the preceding two days in the autoregression equation. Recall, that ACF can be used to figure out the best order of the MA model. Thus, we’d only use yesterday in the moving average equation. Going back to our example, we can create and fit an ARIMA model with AR of order 2, differencing of order 1 and MA of order 2. decomposition = seasonal_decompose(df_log) model = ARIMA(df_log, order=(2,1,2))results = model.fit(disp=-1)plt.plot(df_log_shift)plt.plot(results.fittedvalues, color='red') Then, we can see how the model compares to the original time series. predictions_ARIMA_diff = pd.Series(results.fittedvalues, copy=True)predictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum()predictions_ARIMA_log = pd.Series(df_log['Passengers'].iloc[0], index=df_log.index)predictions_ARIMA_log = predictions_ARIMA_log.add(predictions_ARIMA_diff_cumsum, fill_value=0)predictions_ARIMA = np.exp(predictions_ARIMA_log)plt.plot(df)plt.plot(predictions_ARIMA) Given that we have data going for every month going back 12 years and want to forecast the number of passengers for the next 10 years, we use (12 x12)+ (12 x 10) = 264. results.plot_predict(1,264) In the domain of machine learning, there is a collection techniques for manipulating and interpreting variables that depend on time. Among these include ARIMA which can remove the trend component in order to accurately predict future values.
[ { "code": null, "e": 624, "s": 172, "text": "The ability to make predictions based upon historical observations creates a competitive advantage. For example, if an organization has the capacity to better forecast the sales quantities of a product, it will be in a more favourable position to optimize inventory levels. This can result in an increased liquidity of the organizations cash reserves, decrease of working capital and improved customer satisfaction by decreasing the backlog of orders." }, { "code": null, "e": 897, "s": 624, "text": "In the domain of machine learning, there’s a specific collection of methods and techniques particularly well suited for predicting the value of a dependent variable according to time. In the proceeding article, we’ll cover AutoRegressive Integrated Moving Average (ARIMA)." }, { "code": null, "e": 1038, "s": 897, "text": "We refer to a series of data points indexed (or graphed) in time order as a time series. A time series can be broken down into 3 components." }, { "code": null, "e": 1148, "s": 1038, "text": "Trend: Upward & downward movement of the data with time over a large period of time (i.e. house appreciation)" }, { "code": null, "e": 1236, "s": 1148, "text": "Seasonality: Seasonal variance (i.e. an increase in demand for ice cream during summer)" }, { "code": null, "e": 1280, "s": 1236, "text": "Noise: Spikes & troughs at random intervals" }, { "code": null, "e": 1371, "s": 1280, "text": "Before applying any statistical model on a time series, we want to ensure it’s stationary." }, { "code": null, "e": 1636, "s": 1371, "text": "If a time series is stationary and has a particular behaviour over a given time interval, then it is safe to assume that it will have same behaviour at some later point in time. Most statistical modelling methods assume or require the time series to be stationary." }, { "code": null, "e": 1725, "s": 1636, "text": "The statsmodels library provides a suite of functions for working with time series data." }, { "code": null, "e": 2035, "s": 1725, "text": "import numpy as npimport pandas as pdfrom matplotlib import pyplot as pltfrom statsmodels.tsa.stattools import adfullerfrom statsmodels.tsa.seasonal import seasonal_decomposefrom statsmodels.tsa.arima_model import ARIMAfrom pandas.plotting import register_matplotlib_convertersregister_matplotlib_converters()" }, { "code": null, "e": 2131, "s": 2035, "text": "We’ll be working with a dataset that contains the number of airplane passengers on a given day." }, { "code": null, "e": 2295, "s": 2131, "text": "df = pd.read_csv('air_passengers.csv', parse_dates = ['Month'], index_col = ['Month'])df.head()plt.xlabel('Date')plt.ylabel('Number of air passengers')plt.plot(df)" }, { "code": null, "e": 2482, "s": 2295, "text": "As mentioned previously, before we can build a model, we must ensure that the time series is stationary. There are two primary way to determine whether a given time series is stationary." }, { "code": null, "e": 2707, "s": 2482, "text": "Rolling Statistics: Plot the rolling mean and rolling standard deviation. The time series is stationary if they remain constant with time (with the naked eye look to see if the lines are straight and parallel to the x-axis)." }, { "code": null, "e": 2942, "s": 2707, "text": "Augmented Dickey-Fuller Test: The time series is considered stationary if the p-value is low (according to the null hypothesis) and the critical values at 1%, 5%, 10% confidence intervals are as close as possible to the ADF Statistics" }, { "code": null, "e": 3257, "s": 2942, "text": "For those who don’t understand the difference between average and rolling average, a 10-day rolling average would average out the closing prices for the first 10 days as the first data point. The next data point would drop the earliest price, add the price on day 11 and take the average, and so on as shown below." }, { "code": null, "e": 3604, "s": 3257, "text": "rolling_mean = df.rolling(window = 12).mean()rolling_std = df.rolling(window = 12).std()plt.plot(df, color = 'blue', label = 'Original')plt.plot(rolling_mean, color = 'red', label = 'Rolling Mean')plt.plot(rolling_std, color = 'black', label = 'Rolling Std')plt.legend(loc = 'best')plt.title('Rolling Mean & Rolling Standard Deviation')plt.show()" }, { "code": null, "e": 3755, "s": 3604, "text": "As you can see, the rolling mean and rolling standard deviation increase with time. Therefore, we can conclude that the time series is not stationary." }, { "code": null, "e": 3974, "s": 3755, "text": "result = adfuller(df['Passengers'])print('ADF Statistic: {}'.format(result[0]))print('p-value: {}'.format(result[1]))print('Critical Values:')for key, value in result[4].items(): print('\\t{}: {}'.format(key, value))" }, { "code": null, "e": 4140, "s": 3974, "text": "The ADF Statistic is far from the critical values and the p-value is greater than the threshold (0.05). Thus, we can conclude that the time series is not stationary." }, { "code": null, "e": 4252, "s": 4140, "text": "Taking the log of the dependent variable is as simple way of lowering the rate at which rolling mean increases." }, { "code": null, "e": 4288, "s": 4252, "text": "df_log = np.log(df)plt.plot(df_log)" }, { "code": null, "e": 4392, "s": 4288, "text": "Let’s create a function to run the two tests which determine whether a given time series is stationary." }, { "code": null, "e": 5177, "s": 4392, "text": "def get_stationarity(timeseries): # rolling statistics rolling_mean = timeseries.rolling(window=12).mean() rolling_std = timeseries.rolling(window=12).std() # rolling statistics plot original = plt.plot(timeseries, color='blue', label='Original') mean = plt.plot(rolling_mean, color='red', label='Rolling Mean') std = plt.plot(rolling_std, color='black', label='Rolling Std') plt.legend(loc='best') plt.title('Rolling Mean & Standard Deviation') plt.show(block=False) # Dickey–Fuller test: result = adfuller(timeseries['Passengers']) print('ADF Statistic: {}'.format(result[0])) print('p-value: {}'.format(result[1])) print('Critical Values:') for key, value in result[4].items(): print('\\t{}: {}'.format(key, value))" }, { "code": null, "e": 5316, "s": 5177, "text": "There are multiple transformations that we can apply to a time series to render it stationary. For instance, we subtract the rolling mean." }, { "code": null, "e": 5478, "s": 5316, "text": "rolling_mean = df_log.rolling(window=12).mean()df_log_minus_mean = df_log - rolling_meandf_log_minus_mean.dropna(inplace=True)get_stationarity(df_log_minus_mean)" }, { "code": null, "e": 5731, "s": 5478, "text": "As we can see, after subtracting the mean, the rolling mean and standard deviation are approximately horizontal. The p-value is below the threshold of 0.05 and the ADF Statistic is close to the critical values. Therefore, the time series is stationary." }, { "code": null, "e": 5831, "s": 5731, "text": "Applying exponential decay is another way of transforming a time series such that it is stationary." }, { "code": null, "e": 6036, "s": 5831, "text": "rolling_mean_exp_decay = df_log.ewm(halflife=12, min_periods=0, adjust=True).mean()df_log_exp_decay = df_log - rolling_mean_exp_decaydf_log_exp_decay.dropna(inplace=True)get_stationarity(df_log_exp_decay)" }, { "code": null, "e": 6161, "s": 6036, "text": "Exponential decay performed worse than subtracting the rolling mean. However, it is still more stationary than the original." }, { "code": null, "e": 6326, "s": 6161, "text": "Let’s try one more method to determine whether an even better solution exists. When applying time shifting, we subtract every the point by the one that preceded it." }, { "code": null, "e": 6383, "s": 6326, "text": "null, (x1−x0), (x2−x1), (x3−x2), (x4−x3), ..., (xn−xn−1)" }, { "code": null, "e": 6485, "s": 6383, "text": "df_log_shift = df_log - df_log.shift()df_log_shift.dropna(inplace=True)get_stationarity(df_log_shift)" }, { "code": null, "e": 6606, "s": 6485, "text": "Time shifting performed worse than subtracting the rolling mean. However, it is still more stationary than the original." }, { "code": null, "e": 6975, "s": 6606, "text": "Autoregressive models operate under the premise that past values have an effect on current values. AR models are commonly used in analyzing nature, economics, and other time-varying processes. As long as the assumption holds, we can build a linear regression model that attempts to predict value of a dependent variable today, given the values it had on previous days." }, { "code": null, "e": 7064, "s": 6975, "text": "The order of the AR model corresponds to the number of days incorporated in the formula." }, { "code": null, "e": 7202, "s": 7064, "text": "Assumes the value of the dependent variable on the current day depends on the previous days error terms. The formula can be expressed as:" }, { "code": null, "e": 7251, "s": 7202, "text": "You’ll also come across the equation written as:" }, { "code": null, "e": 7442, "s": 7251, "text": "where μ is the mean of the series, the θ1, ..., θq are the parameters of the model and the εt, εt−1,..., εt−q are white noise error terms. The value of q is called the order of the MA model." }, { "code": null, "e": 7508, "s": 7442, "text": "The ARMA model is simply the combination of the AR and MA models." }, { "code": null, "e": 7989, "s": 7508, "text": "The ARIMA (aka Box-Jenkins) model adds differencing to an ARMA model. Differencing subtracts the current value from the previous and can be used to transform a time series into one that’s stationary. For example, first-order differencing addresses linear trends, and employs the transformation zi = yi — yi-1. Second-order differencing addresses quadratic trends and employs a first-order difference of a first-order difference, namely zi = (yi — yi-1) — (yi-1 — yi-2), and so on." }, { "code": null, "e": 8062, "s": 7989, "text": "Three integers (p, d, q) are typically used to parametrize ARIMA models." }, { "code": null, "e": 8107, "s": 8062, "text": "p: number of autoregressive terms (AR order)" }, { "code": null, "e": 8165, "s": 8107, "text": "d: number of nonseasonal differences (differencing order)" }, { "code": null, "e": 8210, "s": 8165, "text": "q: number of moving-average terms (MA order)" }, { "code": null, "e": 8448, "s": 8210, "text": "The correlation between the observations at the current point in time and the observations at all previous points in time. We can use ACF to determine the optimal number of MA terms. The number of terms determines the order of the model." }, { "code": null, "e": 8768, "s": 8448, "text": "As the name implies, PACF is a subset of ACF. PACF expresses the correlation between observations made at two points in time while accounting for any influence from other data points. We can use PACF to determine the optimal number of terms to use in the AR model. The number of terms determines the order of the model." }, { "code": null, "e": 9108, "s": 8768, "text": "Let’s take a look at an example. Recall, that PACF can be used to figure out the best order of the AR model. The horizontal blue dashed lines represent the significance thresholds. The vertical lines represent the ACF and PACF values at in point in time. Only the vertical lines that exceed the horizontal lines are considered significant." }, { "code": null, "e": 9178, "s": 9108, "text": "Thus, we’d use the preceding two days in the autoregression equation." }, { "code": null, "e": 9253, "s": 9178, "text": "Recall, that ACF can be used to figure out the best order of the MA model." }, { "code": null, "e": 9315, "s": 9253, "text": "Thus, we’d only use yesterday in the moving average equation." }, { "code": null, "e": 9442, "s": 9315, "text": "Going back to our example, we can create and fit an ARIMA model with AR of order 2, differencing of order 1 and MA of order 2." }, { "code": null, "e": 9615, "s": 9442, "text": "decomposition = seasonal_decompose(df_log) model = ARIMA(df_log, order=(2,1,2))results = model.fit(disp=-1)plt.plot(df_log_shift)plt.plot(results.fittedvalues, color='red')" }, { "code": null, "e": 9684, "s": 9615, "text": "Then, we can see how the model compares to the original time series." }, { "code": null, "e": 10080, "s": 9684, "text": "predictions_ARIMA_diff = pd.Series(results.fittedvalues, copy=True)predictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum()predictions_ARIMA_log = pd.Series(df_log['Passengers'].iloc[0], index=df_log.index)predictions_ARIMA_log = predictions_ARIMA_log.add(predictions_ARIMA_diff_cumsum, fill_value=0)predictions_ARIMA = np.exp(predictions_ARIMA_log)plt.plot(df)plt.plot(predictions_ARIMA)" }, { "code": null, "e": 10249, "s": 10080, "text": "Given that we have data going for every month going back 12 years and want to forecast the number of passengers for the next 10 years, we use (12 x12)+ (12 x 10) = 264." }, { "code": null, "e": 10277, "s": 10249, "text": "results.plot_predict(1,264)" } ]
Prime numbers within a range in JavaScript
We are required to write a JavaScript function that takes in two numbers, say, a and b and returns the total number of prime numbers between a and b (including a and b, if they are prime). For example: If a = 21, and b = 38. The prime numbers between them are 23, 29, 31, 37 The prime numbers between them are 23, 29, 31, 37 And their count is 4 And their count is 4 Our function should return 4 Our function should return 4 The code for this will be − const isPrime = num => { let count = 2; while(count < (num / 2)+1){ if(num % count !== 0){ count++; continue; }; return false; }; return true; }; const primeBetween = (a, b) => { let count = 0; for(let i = Math.min(a, b); i <= Math.max(a, b); i++){ if(isPrime(i)){ count++; }; }; return count; }; console.log(primeBetween(21, 38)); The output in the console − 4
[ { "code": null, "e": 1251, "s": 1062, "text": "We are required to write a JavaScript function that takes in two numbers, say, a and b and\nreturns the total number of prime numbers between a and b (including a and b, if they are\nprime)." }, { "code": null, "e": 1287, "s": 1251, "text": "For example: If a = 21, and b = 38." }, { "code": null, "e": 1337, "s": 1287, "text": "The prime numbers between them are 23, 29, 31, 37" }, { "code": null, "e": 1387, "s": 1337, "text": "The prime numbers between them are 23, 29, 31, 37" }, { "code": null, "e": 1408, "s": 1387, "text": "And their count is 4" }, { "code": null, "e": 1429, "s": 1408, "text": "And their count is 4" }, { "code": null, "e": 1458, "s": 1429, "text": "Our function should return 4" }, { "code": null, "e": 1487, "s": 1458, "text": "Our function should return 4" }, { "code": null, "e": 1515, "s": 1487, "text": "The code for this will be −" }, { "code": null, "e": 1928, "s": 1515, "text": "const isPrime = num => {\n let count = 2;\n while(count < (num / 2)+1){\n if(num % count !== 0){\n count++;\n continue;\n };\n return false;\n };\n return true;\n};\nconst primeBetween = (a, b) => {\n let count = 0;\n for(let i = Math.min(a, b); i <= Math.max(a, b); i++){\n if(isPrime(i)){\n count++;\n };\n };\n return count;\n};\nconsole.log(primeBetween(21, 38));" }, { "code": null, "e": 1956, "s": 1928, "text": "The output in the console −" }, { "code": null, "e": 1958, "s": 1956, "text": "4" } ]
Tune the hyperparameters of your deep learning networks in Python using Keras and Talos | by Yefeng Xia | Towards Data Science
With the development of Deep Learning frameworks, it’s more convenient and easy for many people to design the architecture for an artificial neural network. The 3 most popular frameworks, Tensorflow, Keras, and Pytorch, are used more frequently. To improve the performance of our neural networks, there are many approaches, e.g. improve the data quality, using data augmentation. However, data quality is the source of data science. To get better data quality is usually extra expensive, time- and human resource-consuming. Therewith, we prefer to handle the hyperparameters/parameters of a model🏄🏼. Let’s start it! A model parameter is a configuration variable that is internal to the model. It’s dependent on the model’s training data. The parameter of a model can be estimated by fitting the given data to the model. A model hyperparameter is a configuration that is external to the model. The hyperparameters are to help us find model parameters, which are not dependent on training data. On the contrary, we find the model’s parameter by setting a series of hyperparameters properly, which optimize the training process and make the best use of data. It means that we can manually give hyperparameters values and they can’t be updated during the training. But parameters are something instinct of the model, which updates continuously during the training. An inappropriate analogy, if we regard a student as a model, his knowledge, characters, skills are more like the model’s parameter. The way we train him to get these abilities and features can be treated as hyperparameters. Since Hyperparameters are the key to the model’s parameters, we should pay a lot of attention to them. How to select the model’s hyperparameters? To deal with the question requires enough knowledge and patience. There are typically 5 different optimization techniques: Manual Search: we choose some model hyperparameters based on our judgment/experience. We then train the model, evaluate its accuracy and start the process again. This loop is repeated until a satisfactory accuracy is scored.Grid search: a grid of hyperparameters and train/test our model on each of the possible combinations over a given subset of the hyperparameters space of the training algorithm. It’s the traditional method of hyperparameters optimization.Random Search: it overrides the complete selection of all combinations by their random selection. Therewith, it can reduce the number of search iterations by selecting some random combination of these hyperparameters.Bayesian Optimization: is a sequential design strategy for global optimization of black-box functions. It reduces the number of search iterations by choosing the input values bearing in mind the past outcomes.Evolutionary Algorithm: create a population of N Machine Learning models with some predefined Hyperparameters. It generates some offsprings having similar Hyperparameters to the ones of the best models so that to get again a population of N models. Just the best models will survive at the end of the process by sequentially selecting, combining, and varying parameters using mechanisms that resemble biological evolution. It simulates the process of natural selection which means those species who can adapt to changes in their environment can survive and reproduce and go to the next generation. Manual Search: we choose some model hyperparameters based on our judgment/experience. We then train the model, evaluate its accuracy and start the process again. This loop is repeated until a satisfactory accuracy is scored. Grid search: a grid of hyperparameters and train/test our model on each of the possible combinations over a given subset of the hyperparameters space of the training algorithm. It’s the traditional method of hyperparameters optimization. Random Search: it overrides the complete selection of all combinations by their random selection. Therewith, it can reduce the number of search iterations by selecting some random combination of these hyperparameters. Bayesian Optimization: is a sequential design strategy for global optimization of black-box functions. It reduces the number of search iterations by choosing the input values bearing in mind the past outcomes. Evolutionary Algorithm: create a population of N Machine Learning models with some predefined Hyperparameters. It generates some offsprings having similar Hyperparameters to the ones of the best models so that to get again a population of N models. Just the best models will survive at the end of the process by sequentially selecting, combining, and varying parameters using mechanisms that resemble biological evolution. It simulates the process of natural selection which means those species who can adapt to changes in their environment can survive and reproduce and go to the next generation. In our work, we used often grid search. Grid search suffers from high dimensional spaces, but often can easily be parallelized, since the hyperparameter values that the algorithm works with are usually independent of each other. Besides, we write the code on the platform Colab, which allows us to write and execute Python in your browser: Zero configuration required Free access to GPUs Easy sharing If you want to quickly build and test a neural network with minimal lines of code, then Keras is what you need. Keras is an open-source neural network library written in Python that is an API designed for human beings, not machines. Since Tensorflow 2 comes up with a tight integration of Keras and an intuitive high-level API tf. keras, there are 2 ways to use Keras, either directly import Keras or from tf import Keras. Talos was released on May 11, 2018 and has since been upgraded seven times. When running the code with Talos in the scan-command, all possible combinations are tested in an experiment. Important: Talos radically changes the ordinary Keras workflow by fully automating hyperparameter tuning and model evaluation. Talos exposes Keras functionality entirely and there is no new syntax or templates to learn. we can install talos with one line of command: pip install talos To make our result visible and intuitive, we take a simple case to classify whether images contain either a dog or a cat with CNN, the ancient problem in Computer Vision😆. I downloaded the image dataset from Kaggle. The dataset is in the ZIP file format after you download it from the link. from google.colab import drivedrive.mount('/content/gdrive/')!mkdir -p dataset!unzip /content/gdrive/My\ Drive/Colab\ Notebooks/blogs_medium/cat_dog.zip -d dataset/ We can use a few lines of code to unzip the file directly in Google Colab. Here we use LeNet-5, which is the 22-year-old neural network, usually as a teaching sample. Now we start our code for building LeNet-5 with Keras. To get reproducible results in Keras, setting the random seeds is necessary. import osimport tensorflow as tfimport numpy as npimport random as python_randomnp.random.seed(42)python_random.seed(42)tf.random.set_random_seed(42) Then we can focus on the image data. We need to read them with keras.preprocessing.image into train and validation array, which flow in CNN later for training and validation. There must be a uniform size for all pictures, e.g. (100,100,3). Although images of dogs or cats in the dataset are different with size, some big and some small, we can make them with equal-size by resizing. import kerasimport globimport osfrom keras.preprocessing.image import ImageDataGenerator,load_img,img_to_array, array_to_imgfrom keras.layers import Dense, Conv2D, MaxPool2D, Flatten,Dropoutfrom keras import optimizersfrom keras.models import Sequentialimport numpy as npimage_size=(100,100)train_cats = glob.glob('dataset/training_set/training_set/cats/*.jpg')train_dogs = glob.glob('dataset/training_set/training_set/dogs/*.jpg')train_files = [fn for fn in train_cats]+[fn for fn in train_dogs]print(len(train_files))train_imgs = [img_to_array(load_img(img, target_size=image_size)) for img in train_files]train_imgs = np.array(train_imgs)print(train_imgs.shape)train_labels= [0 for i in range(len(train_cats))]+[1 for i in range(len(train_dogs))]val_cats = glob.glob('dataset/test_set/test_set/cats/*.jpg')val_dogs = glob.glob('dataset/test_set/test_set/dogs/*.jpg')val_files = [fn for fn in val_cats]+[fn for fn in val_dogs]val_imgs = [img_to_array(load_img(img, target_size=image_size)) for img in val_files]val_imgs = np.array(val_imgs)print(val_imgs.shape)val_labels= [0 for i in range(len(val_cats))]+[1 for i in range(len(val_dogs))] with the above code, all “dogs” and “cats” are in Array, either train set or validation set. Additionally, we label dogs with digit 1 and cats with digit 0. Next, we encode categorical integer features 0 and 1 using a one-hot-encoding. num_classes = 2epochs = 10input_shape = (100,100,3)# encode text category labelsfrom sklearn.preprocessing import OneHotEncoder, LabelEncodertrain_labels_array = np.array(train_labels)le = LabelEncoder()train_integer_encoded = le.fit_transform(train_labels_array)ohe = OneHotEncoder(sparse=False)train_integer_encoded = train_integer_encoded.reshape(len(train_integer_encoded), 1)train_labels_ohe = ohe.fit_transform(train_integer_encoded)validation_labels_array = np.array(val_labels)validation_integer_encoded = le.fit_transform(validation_labels_array)ohe = OneHotEncoder(sparse=False)validation_integer_encoded = validation_integer_encoded.reshape(len(validation_integer_encoded), 1)validation_labels_ohe = ohe.fit_transform(validation_integer_encoded) The data must be normalized so that the model can be converged faster. train_imgs_scaled = train_imgs.astype('float32')validation_imgs_scaled = val_imgs.astype('float32')train_imgs_scaled /= 255validation_imgs_scaled /= 255 Then build a model structure from keras import layersfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropoutfrom keras.models import Modelfrom keras import optimizersdef lenet_5(in_shape=(100,100,3), n_classes=2):in_layer = layers.Input(in_shape)conv1 = layers.Conv2D(filters=20, kernel_size=5,padding='same', activation='relu')(in_layer)pool1 = layers.MaxPool2D()(conv1)conv2 = layers.Conv2D(filters=50, kernel_size=5,padding='same', activation='relu')(pool1)pool2 = layers.MaxPool2D()(conv2)flatten = layers.Flatten()(pool2)dense1 = layers.Dense(500, activation='relu',kernel_initializer='glorot_uniform')(flatten)preds = layers.Dense(2, activation='softmax',kernel_initializer='glorot_uniform')(dense1)opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)model = Model(in_layer, preds)model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])return modelif __name__ == '__main__':model = lenet_5()print(model.summary()) Here we trained the model for 10 epochs and defined batch_size 200. from keras.callbacks import ModelCheckpointcheckpoint = ModelCheckpoint("lenet.h5",monitor='val_acc',verbose=1,save_best_only=True, save_weights_only= False, mode ='auto',period=1)history = model.fit(x=train_imgs_scaled, y=train_labels_ohe, validation_data=(validation_imgs_scaled, validation_labels_ohe), batch_size=200, epochs=10, callbacks=[checkpoint], shuffle=True) After a long time waiting, we can get a training/validation diagram. The above diagram shows that the model improves not much after 5 epochs. But it hasn’t overfitted. Therefore we can still use the obtained model. We want to make more efforts to train a better LeNet-5 model for our dog-cat classifier, so we focus on the model’s hyperparameters to improve the model🎑. Here we define a new function that has the same structure as LeNet-5, but some hyperparameters in the model are variable. We save these variable hyperparameters in the dictionary “p”. p = {'first_hidden_layer': [500],'opt': [Adam, sgd],'dropout': [0,0.5],'weight_regulizer':[None],'lr': [1],'emb_output_dims': [None],'kernel_initializer':["glorot_uniform"]} To reduce the computer calculation and program running time, in the dictionary we have only set ‘opt’ and ‘dropout’ variable, optimizer with 2 options (Adam or sgd) and dropout with 2 possible values. There is a total of 4 combinations. from keras.optimizers import Adam,sgdfrom keras.models import load_modelfrom keras.utils import CustomObjectScopefrom keras.initializers import glorot_uniformimport talosfrom talos.model.normalizers import lr_normalizerdef lenet_model(x_train, y_train,x_val, y_val, params):in_layer = layers.Input((100,100,3))conv1 = layers.Conv2D(filters=20, kernel_size=5,padding='same', activation='relu')(in_layer)pool1 = layers.MaxPool2D()(conv1)conv2 = layers.Conv2D(filters=50, kernel_size=5,padding='same', activation='relu')(pool1)pool2 = layers.MaxPool2D()(conv2)flatten = layers.Flatten()(pool2)dense1 = layers.Dense(params['first_hidden_layer'], activation='relu')(flatten)dropout1 = layers.Dropout(params['dropout'])(dense1)preds = layers.Dense(2, activation='softmax')(dropout1)model = Model(in_layer, preds)model.compile(loss="categorical_crossentropy", optimizer=params['opt'](lr=lr_normalizer(params['lr'],params['opt'])), metrics=["acc"])steps_per_epoch = int(np.ceil(train_imgs.shape[0] / 20)) - 1history = model.fit(x=train_imgs_scaled, y=train_labels_ohe, validation_data=(validation_imgs_scaled, validation_labels_ohe), batch_size=200, epochs=10, callbacks=[talos.utils.ExperimentLogCallback('kgt', params)], verbose=1)return history, modelt = talos.Scan(x=train_imgs_scaled, y=train_labels_ohe, model=lenet_model, experiment_name= 'kgt', params=p) With the help of the Scan command (talos.Scan), we start configuring the experiment. It will last a longer time than training the last basic LeNet-5 model. The experiment reports are saved in csv. file format. we can read the csv. file to show the results in the table. By plotting the validation_accuracy (top) and validation_loss (bottom), we can conclude that the trained models of the zeroth and third experiments are much better than those of the second and fourth experiments. Comparing the experimental parameter information, we found the models with adam have a better performance. The dropout method played a little roll in training LeNet-5. All things considered, the model 0 has the best performance, which uses Adam but doesn’t have a dropout. In this story, we introduced how to use talos to tune hyperparameters of a with Keras built CNN. In the beginning, there is some basic knowledge for parameters and hyperparameters, and a review of usual methods to optimize hyperparameters. In the rest of the story, we built a LeNet-5 based cat-dog classifier and scanned all hyperparameter combinations of interest. by observing the metric of validation, we can know which hyperparameter has the most influence and which combination gives the best result🏁. The code is available in my GitHub😬 https://github.com/Kopfgeldjaeger/Medium_blogs_code/tree/master/2_talos_grid_search Liashchynskyi, P., & Liashchynskyi, P. (2019). Grid Search, Random Search, Genetic Algorithm: A Big Comparison for NAS. arXiv preprint arXiv:1912.06059 Van Rijn, J. N., & Hutter, F. (2018, July). Hyperparameter importance across datasets. In Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining (pp. 2367–2376). Hutter, F., Lücke, J., & Schmidt-Thieme, L. (2015). Beyond manual tuning of hyperparameters. KI-Künstliche Intelligenz, 29(4), 329–337.
[ { "code": null, "e": 647, "s": 47, "text": "With the development of Deep Learning frameworks, it’s more convenient and easy for many people to design the architecture for an artificial neural network. The 3 most popular frameworks, Tensorflow, Keras, and Pytorch, are used more frequently. To improve the performance of our neural networks, there are many approaches, e.g. improve the data quality, using data augmentation. However, data quality is the source of data science. To get better data quality is usually extra expensive, time- and human resource-consuming. Therewith, we prefer to handle the hyperparameters/parameters of a model🏄🏼." }, { "code": null, "e": 663, "s": 647, "text": "Let’s start it!" }, { "code": null, "e": 867, "s": 663, "text": "A model parameter is a configuration variable that is internal to the model. It’s dependent on the model’s training data. The parameter of a model can be estimated by fitting the given data to the model." }, { "code": null, "e": 1040, "s": 867, "text": "A model hyperparameter is a configuration that is external to the model. The hyperparameters are to help us find model parameters, which are not dependent on training data." }, { "code": null, "e": 1408, "s": 1040, "text": "On the contrary, we find the model’s parameter by setting a series of hyperparameters properly, which optimize the training process and make the best use of data. It means that we can manually give hyperparameters values and they can’t be updated during the training. But parameters are something instinct of the model, which updates continuously during the training." }, { "code": null, "e": 1632, "s": 1408, "text": "An inappropriate analogy, if we regard a student as a model, his knowledge, characters, skills are more like the model’s parameter. The way we train him to get these abilities and features can be treated as hyperparameters." }, { "code": null, "e": 1844, "s": 1632, "text": "Since Hyperparameters are the key to the model’s parameters, we should pay a lot of attention to them. How to select the model’s hyperparameters? To deal with the question requires enough knowledge and patience." }, { "code": null, "e": 1901, "s": 1844, "text": "There are typically 5 different optimization techniques:" }, { "code": null, "e": 3386, "s": 1901, "text": "Manual Search: we choose some model hyperparameters based on our judgment/experience. We then train the model, evaluate its accuracy and start the process again. This loop is repeated until a satisfactory accuracy is scored.Grid search: a grid of hyperparameters and train/test our model on each of the possible combinations over a given subset of the hyperparameters space of the training algorithm. It’s the traditional method of hyperparameters optimization.Random Search: it overrides the complete selection of all combinations by their random selection. Therewith, it can reduce the number of search iterations by selecting some random combination of these hyperparameters.Bayesian Optimization: is a sequential design strategy for global optimization of black-box functions. It reduces the number of search iterations by choosing the input values bearing in mind the past outcomes.Evolutionary Algorithm: create a population of N Machine Learning models with some predefined Hyperparameters. It generates some offsprings having similar Hyperparameters to the ones of the best models so that to get again a population of N models. Just the best models will survive at the end of the process by sequentially selecting, combining, and varying parameters using mechanisms that resemble biological evolution. It simulates the process of natural selection which means those species who can adapt to changes in their environment can survive and reproduce and go to the next generation." }, { "code": null, "e": 3611, "s": 3386, "text": "Manual Search: we choose some model hyperparameters based on our judgment/experience. We then train the model, evaluate its accuracy and start the process again. This loop is repeated until a satisfactory accuracy is scored." }, { "code": null, "e": 3849, "s": 3611, "text": "Grid search: a grid of hyperparameters and train/test our model on each of the possible combinations over a given subset of the hyperparameters space of the training algorithm. It’s the traditional method of hyperparameters optimization." }, { "code": null, "e": 4067, "s": 3849, "text": "Random Search: it overrides the complete selection of all combinations by their random selection. Therewith, it can reduce the number of search iterations by selecting some random combination of these hyperparameters." }, { "code": null, "e": 4277, "s": 4067, "text": "Bayesian Optimization: is a sequential design strategy for global optimization of black-box functions. It reduces the number of search iterations by choosing the input values bearing in mind the past outcomes." }, { "code": null, "e": 4875, "s": 4277, "text": "Evolutionary Algorithm: create a population of N Machine Learning models with some predefined Hyperparameters. It generates some offsprings having similar Hyperparameters to the ones of the best models so that to get again a population of N models. Just the best models will survive at the end of the process by sequentially selecting, combining, and varying parameters using mechanisms that resemble biological evolution. It simulates the process of natural selection which means those species who can adapt to changes in their environment can survive and reproduce and go to the next generation." }, { "code": null, "e": 5215, "s": 4875, "text": "In our work, we used often grid search. Grid search suffers from high dimensional spaces, but often can easily be parallelized, since the hyperparameter values that the algorithm works with are usually independent of each other. Besides, we write the code on the platform Colab, which allows us to write and execute Python in your browser:" }, { "code": null, "e": 5243, "s": 5215, "text": "Zero configuration required" }, { "code": null, "e": 5263, "s": 5243, "text": "Free access to GPUs" }, { "code": null, "e": 5276, "s": 5263, "text": "Easy sharing" }, { "code": null, "e": 5699, "s": 5276, "text": "If you want to quickly build and test a neural network with minimal lines of code, then Keras is what you need. Keras is an open-source neural network library written in Python that is an API designed for human beings, not machines. Since Tensorflow 2 comes up with a tight integration of Keras and an intuitive high-level API tf. keras, there are 2 ways to use Keras, either directly import Keras or from tf import Keras." }, { "code": null, "e": 5884, "s": 5699, "text": "Talos was released on May 11, 2018 and has since been upgraded seven times. When running the code with Talos in the scan-command, all possible combinations are tested in an experiment." }, { "code": null, "e": 6104, "s": 5884, "text": "Important: Talos radically changes the ordinary Keras workflow by fully automating hyperparameter tuning and model evaluation. Talos exposes Keras functionality entirely and there is no new syntax or templates to learn." }, { "code": null, "e": 6151, "s": 6104, "text": "we can install talos with one line of command:" }, { "code": null, "e": 6169, "s": 6151, "text": "pip install talos" }, { "code": null, "e": 6460, "s": 6169, "text": "To make our result visible and intuitive, we take a simple case to classify whether images contain either a dog or a cat with CNN, the ancient problem in Computer Vision😆. I downloaded the image dataset from Kaggle. The dataset is in the ZIP file format after you download it from the link." }, { "code": null, "e": 6625, "s": 6460, "text": "from google.colab import drivedrive.mount('/content/gdrive/')!mkdir -p dataset!unzip /content/gdrive/My\\ Drive/Colab\\ Notebooks/blogs_medium/cat_dog.zip -d dataset/" }, { "code": null, "e": 6700, "s": 6625, "text": "We can use a few lines of code to unzip the file directly in Google Colab." }, { "code": null, "e": 6792, "s": 6700, "text": "Here we use LeNet-5, which is the 22-year-old neural network, usually as a teaching sample." }, { "code": null, "e": 6924, "s": 6792, "text": "Now we start our code for building LeNet-5 with Keras. To get reproducible results in Keras, setting the random seeds is necessary." }, { "code": null, "e": 7074, "s": 6924, "text": "import osimport tensorflow as tfimport numpy as npimport random as python_randomnp.random.seed(42)python_random.seed(42)tf.random.set_random_seed(42)" }, { "code": null, "e": 7457, "s": 7074, "text": "Then we can focus on the image data. We need to read them with keras.preprocessing.image into train and validation array, which flow in CNN later for training and validation. There must be a uniform size for all pictures, e.g. (100,100,3). Although images of dogs or cats in the dataset are different with size, some big and some small, we can make them with equal-size by resizing." }, { "code": null, "e": 8601, "s": 7457, "text": "import kerasimport globimport osfrom keras.preprocessing.image import ImageDataGenerator,load_img,img_to_array, array_to_imgfrom keras.layers import Dense, Conv2D, MaxPool2D, Flatten,Dropoutfrom keras import optimizersfrom keras.models import Sequentialimport numpy as npimage_size=(100,100)train_cats = glob.glob('dataset/training_set/training_set/cats/*.jpg')train_dogs = glob.glob('dataset/training_set/training_set/dogs/*.jpg')train_files = [fn for fn in train_cats]+[fn for fn in train_dogs]print(len(train_files))train_imgs = [img_to_array(load_img(img, target_size=image_size)) for img in train_files]train_imgs = np.array(train_imgs)print(train_imgs.shape)train_labels= [0 for i in range(len(train_cats))]+[1 for i in range(len(train_dogs))]val_cats = glob.glob('dataset/test_set/test_set/cats/*.jpg')val_dogs = glob.glob('dataset/test_set/test_set/dogs/*.jpg')val_files = [fn for fn in val_cats]+[fn for fn in val_dogs]val_imgs = [img_to_array(load_img(img, target_size=image_size)) for img in val_files]val_imgs = np.array(val_imgs)print(val_imgs.shape)val_labels= [0 for i in range(len(val_cats))]+[1 for i in range(len(val_dogs))]" }, { "code": null, "e": 8758, "s": 8601, "text": "with the above code, all “dogs” and “cats” are in Array, either train set or validation set. Additionally, we label dogs with digit 1 and cats with digit 0." }, { "code": null, "e": 8837, "s": 8758, "text": "Next, we encode categorical integer features 0 and 1 using a one-hot-encoding." }, { "code": null, "e": 9594, "s": 8837, "text": "num_classes = 2epochs = 10input_shape = (100,100,3)# encode text category labelsfrom sklearn.preprocessing import OneHotEncoder, LabelEncodertrain_labels_array = np.array(train_labels)le = LabelEncoder()train_integer_encoded = le.fit_transform(train_labels_array)ohe = OneHotEncoder(sparse=False)train_integer_encoded = train_integer_encoded.reshape(len(train_integer_encoded), 1)train_labels_ohe = ohe.fit_transform(train_integer_encoded)validation_labels_array = np.array(val_labels)validation_integer_encoded = le.fit_transform(validation_labels_array)ohe = OneHotEncoder(sparse=False)validation_integer_encoded = validation_integer_encoded.reshape(len(validation_integer_encoded), 1)validation_labels_ohe = ohe.fit_transform(validation_integer_encoded)" }, { "code": null, "e": 9665, "s": 9594, "text": "The data must be normalized so that the model can be converged faster." }, { "code": null, "e": 9819, "s": 9665, "text": "train_imgs_scaled = train_imgs.astype('float32')validation_imgs_scaled = val_imgs.astype('float32')train_imgs_scaled /= 255validation_imgs_scaled /= 255" }, { "code": null, "e": 9848, "s": 9819, "text": "Then build a model structure" }, { "code": null, "e": 10808, "s": 9848, "text": "from keras import layersfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropoutfrom keras.models import Modelfrom keras import optimizersdef lenet_5(in_shape=(100,100,3), n_classes=2):in_layer = layers.Input(in_shape)conv1 = layers.Conv2D(filters=20, kernel_size=5,padding='same', activation='relu')(in_layer)pool1 = layers.MaxPool2D()(conv1)conv2 = layers.Conv2D(filters=50, kernel_size=5,padding='same', activation='relu')(pool1)pool2 = layers.MaxPool2D()(conv2)flatten = layers.Flatten()(pool2)dense1 = layers.Dense(500, activation='relu',kernel_initializer='glorot_uniform')(flatten)preds = layers.Dense(2, activation='softmax',kernel_initializer='glorot_uniform')(dense1)opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)model = Model(in_layer, preds)model.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])return modelif __name__ == '__main__':model = lenet_5()print(model.summary())" }, { "code": null, "e": 10876, "s": 10808, "text": "Here we trained the model for 10 epochs and defined batch_size 200." }, { "code": null, "e": 11247, "s": 10876, "text": "from keras.callbacks import ModelCheckpointcheckpoint = ModelCheckpoint(\"lenet.h5\",monitor='val_acc',verbose=1,save_best_only=True, save_weights_only= False, mode ='auto',period=1)history = model.fit(x=train_imgs_scaled, y=train_labels_ohe, validation_data=(validation_imgs_scaled, validation_labels_ohe), batch_size=200, epochs=10, callbacks=[checkpoint], shuffle=True)" }, { "code": null, "e": 11316, "s": 11247, "text": "After a long time waiting, we can get a training/validation diagram." }, { "code": null, "e": 11462, "s": 11316, "text": "The above diagram shows that the model improves not much after 5 epochs. But it hasn’t overfitted. Therefore we can still use the obtained model." }, { "code": null, "e": 11617, "s": 11462, "text": "We want to make more efforts to train a better LeNet-5 model for our dog-cat classifier, so we focus on the model’s hyperparameters to improve the model🎑." }, { "code": null, "e": 11801, "s": 11617, "text": "Here we define a new function that has the same structure as LeNet-5, but some hyperparameters in the model are variable. We save these variable hyperparameters in the dictionary “p”." }, { "code": null, "e": 11975, "s": 11801, "text": "p = {'first_hidden_layer': [500],'opt': [Adam, sgd],'dropout': [0,0.5],'weight_regulizer':[None],'lr': [1],'emb_output_dims': [None],'kernel_initializer':[\"glorot_uniform\"]}" }, { "code": null, "e": 12212, "s": 11975, "text": "To reduce the computer calculation and program running time, in the dictionary we have only set ‘opt’ and ‘dropout’ variable, optimizer with 2 options (Adam or sgd) and dropout with 2 possible values. There is a total of 4 combinations." }, { "code": null, "e": 13567, "s": 12212, "text": "from keras.optimizers import Adam,sgdfrom keras.models import load_modelfrom keras.utils import CustomObjectScopefrom keras.initializers import glorot_uniformimport talosfrom talos.model.normalizers import lr_normalizerdef lenet_model(x_train, y_train,x_val, y_val, params):in_layer = layers.Input((100,100,3))conv1 = layers.Conv2D(filters=20, kernel_size=5,padding='same', activation='relu')(in_layer)pool1 = layers.MaxPool2D()(conv1)conv2 = layers.Conv2D(filters=50, kernel_size=5,padding='same', activation='relu')(pool1)pool2 = layers.MaxPool2D()(conv2)flatten = layers.Flatten()(pool2)dense1 = layers.Dense(params['first_hidden_layer'], activation='relu')(flatten)dropout1 = layers.Dropout(params['dropout'])(dense1)preds = layers.Dense(2, activation='softmax')(dropout1)model = Model(in_layer, preds)model.compile(loss=\"categorical_crossentropy\", optimizer=params['opt'](lr=lr_normalizer(params['lr'],params['opt'])), metrics=[\"acc\"])steps_per_epoch = int(np.ceil(train_imgs.shape[0] / 20)) - 1history = model.fit(x=train_imgs_scaled, y=train_labels_ohe, validation_data=(validation_imgs_scaled, validation_labels_ohe), batch_size=200, epochs=10, callbacks=[talos.utils.ExperimentLogCallback('kgt', params)], verbose=1)return history, modelt = talos.Scan(x=train_imgs_scaled, y=train_labels_ohe, model=lenet_model, experiment_name= 'kgt', params=p)" }, { "code": null, "e": 13723, "s": 13567, "text": "With the help of the Scan command (talos.Scan), we start configuring the experiment. It will last a longer time than training the last basic LeNet-5 model." }, { "code": null, "e": 13837, "s": 13723, "text": "The experiment reports are saved in csv. file format. we can read the csv. file to show the results in the table." }, { "code": null, "e": 14218, "s": 13837, "text": "By plotting the validation_accuracy (top) and validation_loss (bottom), we can conclude that the trained models of the zeroth and third experiments are much better than those of the second and fourth experiments. Comparing the experimental parameter information, we found the models with adam have a better performance. The dropout method played a little roll in training LeNet-5." }, { "code": null, "e": 14323, "s": 14218, "text": "All things considered, the model 0 has the best performance, which uses Adam but doesn’t have a dropout." }, { "code": null, "e": 14831, "s": 14323, "text": "In this story, we introduced how to use talos to tune hyperparameters of a with Keras built CNN. In the beginning, there is some basic knowledge for parameters and hyperparameters, and a review of usual methods to optimize hyperparameters. In the rest of the story, we built a LeNet-5 based cat-dog classifier and scanned all hyperparameter combinations of interest. by observing the metric of validation, we can know which hyperparameter has the most influence and which combination gives the best result🏁." }, { "code": null, "e": 14867, "s": 14831, "text": "The code is available in my GitHub😬" }, { "code": null, "e": 14951, "s": 14867, "text": "https://github.com/Kopfgeldjaeger/Medium_blogs_code/tree/master/2_talos_grid_search" }, { "code": null, "e": 15103, "s": 14951, "text": "Liashchynskyi, P., & Liashchynskyi, P. (2019). Grid Search, Random Search, Genetic Algorithm: A Big Comparison for NAS. arXiv preprint arXiv:1912.06059" }, { "code": null, "e": 15307, "s": 15103, "text": "Van Rijn, J. N., & Hutter, F. (2018, July). Hyperparameter importance across datasets. In Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining (pp. 2367–2376)." } ]
SaltStack - Access Control System
An Access Control System provides options for a user for a group to execute a task with permissions. A Salt access control system is used to configure access to non-administrative control interfaces. You can apply this process to all the systems. This control helps the non-administrative users to execute the Salt commands. Salt interfaces are of the following three types − Publisher ACL system External Auth system Peer system Let us understand go through each of these interfaces in detail. A Publisher ACL system allows access to the users other than root to execute Salt commands on minions from the master. The publisher ACL system is configured in the master configuration file via the publisher_acl configuration option. It is defined as follows − publisher_acl: user1: - .* user2: - web*: - test.* - pkg.* Here, user1 is allowed to execute anything. user1 is allowed to execute anything. user2 is allowed to use test and pkg, but only on “web*” minions. user2 is allowed to use test and pkg, but only on “web*” minions. The external auth system is used to provide access to execute salt commands on specific minions through external authorization system like PAM, LDAP, etc. This configuration file is defined in the master file as described below. external_auth: pam: user1: - 'web*': - test.* - network.* user2: - .* Here, user1 is allowed to execute functions in the test and network modules on the minions that match the web* target. user1 is allowed to execute functions in the test and network modules on the minions that match the web* target. user2 is allowed to execute all the functions. user2 is allowed to execute all the functions. Salt server provides an option ‘–a’ to enable external authentication. salt -a pam web\* test.ping Here, the -a pam option is used to enable PAM external authentication. Salt Server will ask for authentication details whenever we execute the command. To restrict Salt Server from asking the authentication details for the first time only, we can use the T option. This -T option caches the authentication details for the next 12 hours (default setting) and use it to authenticate the users. salt -T -a pam web\* test.ping Salt minions can pass commands using the peer interface. The peer interface is configured through the master configuration file either to allow minions to send commands from the master using the peer configuration section or to allow minions to execute runners from the master using the peer_run configuration. Let us understand both these configurations in detail. The simple configuration to be defined in master file is as below − peer: .*: - .* Here, It enables communication for all minions, but it is only recommended for very secure environments. To assign minions to specific ID’s, the configuration needs to be defined as shown below: peer − .*domain.com: - test.* This configuration is to allow minions to execute runners from the master using the peer_run option on the master file. The following example is to allow access to all minions and to all the runners. peer_run: .*: - .* To assign minions to a specific ID, the configuration needs to be defined as given below − peer_run: .*domain.com: - test.* To execute test.ping on all the minions, use the salt-call command along with the publish.publish module. salt-call publish.publish \* test.ping To execute runner, use the salt-call command along with the publish.runner module. salt-call publish.runner manage.up Print Add Notes Bookmark this page
[ { "code": null, "e": 2532, "s": 2207, "text": "An Access Control System provides options for a user for a group to execute a task with permissions. A Salt access control system is used to configure access to non-administrative control interfaces. You can apply this process to all the systems. This control helps the non-administrative users to execute the Salt commands." }, { "code": null, "e": 2583, "s": 2532, "text": "Salt interfaces are of the following three types −" }, { "code": null, "e": 2604, "s": 2583, "text": "Publisher ACL system" }, { "code": null, "e": 2625, "s": 2604, "text": "External Auth system" }, { "code": null, "e": 2637, "s": 2625, "text": "Peer system" }, { "code": null, "e": 2702, "s": 2637, "text": "Let us understand go through each of these interfaces in detail." }, { "code": null, "e": 2964, "s": 2702, "text": "A Publisher ACL system allows access to the users other than root to execute Salt commands on minions from the master. The publisher ACL system is configured in the master configuration file via the publisher_acl configuration option. It is defined as follows −" }, { "code": null, "e": 3061, "s": 2964, "text": "publisher_acl:\n user1:\n - .*\n\n user2:\n - web*:\n - test.*\n - pkg.*\n" }, { "code": null, "e": 3067, "s": 3061, "text": "Here," }, { "code": null, "e": 3105, "s": 3067, "text": "user1 is allowed to execute anything." }, { "code": null, "e": 3143, "s": 3105, "text": "user1 is allowed to execute anything." }, { "code": null, "e": 3209, "s": 3143, "text": "user2 is allowed to use test and pkg, but only on “web*” minions." }, { "code": null, "e": 3275, "s": 3209, "text": "user2 is allowed to use test and pkg, but only on “web*” minions." }, { "code": null, "e": 3504, "s": 3275, "text": "The external auth system is used to provide access to execute salt commands on specific minions through external authorization system like PAM, LDAP, etc. This configuration file is defined in the master file as described below." }, { "code": null, "e": 3632, "s": 3504, "text": "external_auth:\n pam:\n user1:\n - 'web*':\n - test.*\n - network.*\n user2:\n - .*\n" }, { "code": null, "e": 3638, "s": 3632, "text": "Here," }, { "code": null, "e": 3751, "s": 3638, "text": "user1 is allowed to execute functions in the test and network modules on the minions that match the web* target." }, { "code": null, "e": 3864, "s": 3751, "text": "user1 is allowed to execute functions in the test and network modules on the minions that match the web* target." }, { "code": null, "e": 3911, "s": 3864, "text": "user2 is allowed to execute all the functions." }, { "code": null, "e": 3958, "s": 3911, "text": "user2 is allowed to execute all the functions." }, { "code": null, "e": 4029, "s": 3958, "text": "Salt server provides an option ‘–a’ to enable external authentication." }, { "code": null, "e": 4058, "s": 4029, "text": "salt -a pam web\\* test.ping\n" }, { "code": null, "e": 4451, "s": 4058, "text": "Here, the -a pam option is used to enable PAM external authentication. Salt Server will ask for authentication details whenever we execute the command. To restrict Salt Server from asking the authentication details for the first time only, we can use the T option. This -T option caches the authentication details for the next 12 hours (default setting) and use it to authenticate the users." }, { "code": null, "e": 4483, "s": 4451, "text": "salt -T -a pam web\\* test.ping\n" }, { "code": null, "e": 4794, "s": 4483, "text": "Salt minions can pass commands using the peer interface. The peer interface is configured through the master configuration file either to allow minions to send commands from the master using the peer configuration section or to allow minions to execute runners from the master using the peer_run configuration." }, { "code": null, "e": 4849, "s": 4794, "text": "Let us understand both these configurations in detail." }, { "code": null, "e": 4917, "s": 4849, "text": "The simple configuration to be defined in master file is as below −" }, { "code": null, "e": 4942, "s": 4917, "text": "peer:\n .*:\n - .*\n" }, { "code": null, "e": 5047, "s": 4942, "text": "Here, It enables communication for all minions, but it is only recommended for very secure environments." }, { "code": null, "e": 5144, "s": 5047, "text": "To assign minions to specific ID’s, the configuration needs to be defined as shown below: peer −" }, { "code": null, "e": 5171, "s": 5144, "text": ".*domain.com:\n - test.*\n" }, { "code": null, "e": 5371, "s": 5171, "text": "This configuration is to allow minions to execute runners from the master using the peer_run option on the master file. The following example is to allow access to all minions and to all the runners." }, { "code": null, "e": 5400, "s": 5371, "text": "peer_run:\n .*:\n - .*\n" }, { "code": null, "e": 5491, "s": 5400, "text": "To assign minions to a specific ID, the configuration needs to be defined as given below −" }, { "code": null, "e": 5534, "s": 5491, "text": "peer_run:\n .*domain.com:\n - test.*\n" }, { "code": null, "e": 5640, "s": 5534, "text": "To execute test.ping on all the minions, use the salt-call command along with the publish.publish module." }, { "code": null, "e": 5680, "s": 5640, "text": "salt-call publish.publish \\* test.ping\n" }, { "code": null, "e": 5763, "s": 5680, "text": "To execute runner, use the salt-call command along with the publish.runner module." }, { "code": null, "e": 5799, "s": 5763, "text": "salt-call publish.runner manage.up\n" }, { "code": null, "e": 5806, "s": 5799, "text": " Print" }, { "code": null, "e": 5817, "s": 5806, "text": " Add Notes" } ]
Nearest prime less than given number n C++
We are given a number n, we need to find the nearest prime number that is less than n. We can find the number easily if we start checking from the n - 1. Let's see some examples. Input 10 Output 7 Initialise the number n. Write a loop that iterates from n - 1 to 1Return the first prime number that you found Return the first prime number that you found Return -1 if you didn't find any prime that's less than given n Following is the implementation of the above algorithm in C++ #include <bits/stdc++.h> using namespace std; bool isPrime(int n) { if (n == 2) { return true; } for (int i = 2; i <= ceil(sqrt(n)); i++) { if (n % i == 0) { return false; } } return true; } int getNearestPrimeNumber(int n) { for (int i = n - 1; i > 1; i--) { if (isPrime(i)) { return i; } } return -1; } int main() { int n = 20; cout << getNearestPrimeNumber(n) << endl; return 0; } If you run the above code, then you will get the following result. 19
[ { "code": null, "e": 1241, "s": 1062, "text": "We are given a number n, we need to find the nearest prime number that is less than n. We can find the number easily if we start checking from the n - 1. Let's see some examples." }, { "code": null, "e": 1247, "s": 1241, "text": "Input" }, { "code": null, "e": 1250, "s": 1247, "text": "10" }, { "code": null, "e": 1257, "s": 1250, "text": "Output" }, { "code": null, "e": 1259, "s": 1257, "text": "7" }, { "code": null, "e": 1284, "s": 1259, "text": "Initialise the number n." }, { "code": null, "e": 1371, "s": 1284, "text": "Write a loop that iterates from n - 1 to 1Return the first prime number that you found" }, { "code": null, "e": 1416, "s": 1371, "text": "Return the first prime number that you found" }, { "code": null, "e": 1480, "s": 1416, "text": "Return -1 if you didn't find any prime that's less than given n" }, { "code": null, "e": 1542, "s": 1480, "text": "Following is the implementation of the above algorithm in C++" }, { "code": null, "e": 2007, "s": 1542, "text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isPrime(int n) {\n if (n == 2) {\n return true;\n }\n for (int i = 2; i <= ceil(sqrt(n)); i++) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n}\nint getNearestPrimeNumber(int n) {\n for (int i = n - 1; i > 1; i--) {\n if (isPrime(i)) {\n return i;\n }\n }\n return -1;\n}\nint main() {\n int n = 20;\n cout << getNearestPrimeNumber(n) << endl;\n return 0;\n}" }, { "code": null, "e": 2074, "s": 2007, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 2077, "s": 2074, "text": "19" } ]
How to query JSON datatype in MySQL?
Use JSON data type from MySQL to work with JSON. Let us first create a table − mysql> create table DemoTable -> ( -> StudentName json -> ); Query OK, 0 rows affected (0.74 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('["John", "Chris", "Robert","David","Sam"]'); Query OK, 1 row affected (0.33 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +---------------------------------------------+ | StudentName | +---------------------------------------------+ | ["John", "Chris", "Robert", "David", "Sam"] | +---------------------------------------------+ 1 row in set (0.00 sec) Here is how you can query JSON data type − mysql> SELECT *from DemoTable WHERE JSON_CONTAINS(StudentName, '["Chris"]'); This will produce the following output − +---------------------------------------------+ | StudentName | +---------------------------------------------+ | ["John", "Chris", "Robert", "David", "Sam"] | +---------------------------------------------+ 1 row in set (0.04 sec)
[ { "code": null, "e": 1141, "s": 1062, "text": "Use JSON data type from MySQL to work with JSON. Let us first create a table −" }, { "code": null, "e": 1239, "s": 1141, "text": "mysql> create table DemoTable\n-> (\n-> StudentName json\n-> );\nQuery OK, 0 rows affected (0.74 sec)" }, { "code": null, "e": 1295, "s": 1239, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1413, "s": 1295, "text": "mysql> insert into DemoTable values('[\"John\", \"Chris\", \"Robert\",\"David\",\"Sam\"]');\nQuery OK, 1 row affected (0.33 sec)" }, { "code": null, "e": 1473, "s": 1413, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1504, "s": 1473, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1545, "s": 1504, "text": "This will produce the following output −" }, { "code": null, "e": 1809, "s": 1545, "text": "+---------------------------------------------+\n| StudentName |\n+---------------------------------------------+\n| [\"John\", \"Chris\", \"Robert\", \"David\", \"Sam\"] |\n+---------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1852, "s": 1809, "text": "Here is how you can query JSON data type −" }, { "code": null, "e": 1929, "s": 1852, "text": "mysql> SELECT *from DemoTable WHERE JSON_CONTAINS(StudentName, '[\"Chris\"]');" }, { "code": null, "e": 1970, "s": 1929, "text": "This will produce the following output −" }, { "code": null, "e": 2234, "s": 1970, "text": "+---------------------------------------------+\n| StudentName |\n+---------------------------------------------+\n| [\"John\", \"Chris\", \"Robert\", \"David\", \"Sam\"] |\n+---------------------------------------------+\n1 row in set (0.04 sec)" } ]
How to add users and groups to the local groups on Windows System using PowerShell?
To add users to the local groups using PowerShell, we need to use the Add-LocalGroupMember command (Module − Microsoft.PowerShell.LocalAccounts). Add-LocalGroupMember -Group "Administrators" -Member "NewLocalUser","labdomain\Alpha","Labdomain\ITSecurity" The above command adds 2 users (NewLocalUser (Local) and Alpha (Domain)) and one Domain Security Group ITSecurity to the Local Administrators group. You can also use the other local group name instead of Administrators. To add the new users in the local group on the remote system(s) use the Invoke-Command method. For example, Invoke-Command -ComputerName Test1-Win2k12, Test1-Win2k16{ Add-LocalGroupMember -Group "Administrators" -Member "NewLocalUser","labdomain\Alpha","Labdomain\ITSecurity" } Please note − To run the above command, the remote server must use the PS version 5.1 or advance version. You can also use the command prompt if you don’t have the PS version 5.1 or higher to add users to the group using the below command syntax. net localgroup groupname username /add For example, net localgroup Administrators "labdomain\alpha" /add In the above example, we are adding LabDomain user Alpha to the local Administrators group. You can replace the Administrators with the other group name. For the local user/group, we just need to provide the username or group name without specifying the domain. For example, net localgroup Administrators "NewLocalUser" /add To add the above commands remotely, Invoke-Command -ComputerName Test1-Win2k12, Test1-Win2k16 -ScriptBlock{ Net Localgroup Administrators "LabDomain\Alpha" /add }
[ { "code": null, "e": 1208, "s": 1062, "text": "To add users to the local groups using PowerShell, we need to use the Add-LocalGroupMember command (Module − Microsoft.PowerShell.LocalAccounts)." }, { "code": null, "e": 1317, "s": 1208, "text": "Add-LocalGroupMember -Group \"Administrators\" -Member\n\"NewLocalUser\",\"labdomain\\Alpha\",\"Labdomain\\ITSecurity\"" }, { "code": null, "e": 1466, "s": 1317, "text": "The above command adds 2 users (NewLocalUser (Local) and Alpha (Domain)) and one Domain Security Group ITSecurity to the Local Administrators group." }, { "code": null, "e": 1537, "s": 1466, "text": "You can also use the other local group name instead of Administrators." }, { "code": null, "e": 1645, "s": 1537, "text": "To add the new users in the local group on the remote system(s) use the Invoke-Command method. For example," }, { "code": null, "e": 1821, "s": 1645, "text": "Invoke-Command -ComputerName Test1-Win2k12, Test1-Win2k16{\n Add-LocalGroupMember -Group \"Administrators\" -Member\n \"NewLocalUser\",\"labdomain\\Alpha\",\"Labdomain\\ITSecurity\"\n}" }, { "code": null, "e": 1927, "s": 1821, "text": "Please note − To run the above command, the remote server must use the PS version 5.1 or advance version." }, { "code": null, "e": 2068, "s": 1927, "text": "You can also use the command prompt if you don’t have the PS version 5.1 or higher to add users to the group using the below command syntax." }, { "code": null, "e": 2107, "s": 2068, "text": "net localgroup groupname username /add" }, { "code": null, "e": 2120, "s": 2107, "text": "For example," }, { "code": null, "e": 2173, "s": 2120, "text": "net localgroup Administrators \"labdomain\\alpha\" /add" }, { "code": null, "e": 2448, "s": 2173, "text": "In the above example, we are adding LabDomain user Alpha to the local Administrators group. You can replace the Administrators with the other group name. For the local user/group, we just need to provide the username or group name without specifying the domain. For example," }, { "code": null, "e": 2498, "s": 2448, "text": "net localgroup Administrators \"NewLocalUser\" /add" }, { "code": null, "e": 2534, "s": 2498, "text": "To add the above commands remotely," }, { "code": null, "e": 2664, "s": 2534, "text": "Invoke-Command -ComputerName Test1-Win2k12, Test1-Win2k16 -ScriptBlock{\n Net Localgroup Administrators \"LabDomain\\Alpha\" /add\n}" } ]
Collaborative Filtering in Pytorch | by Neel Iyer | Towards Data Science
Collaborative filtering is a tool that companies are increasingly using. Netflix uses it to recommend shows for you to watch. Facebook uses it to recommend who you should be friends with. Spotify uses it to recommend playlists and songs. It’s incredibly useful in recommending products to customers. In this post, I construct a collaborative filtering neural network with embeddings to understand how users would feel towards certain movies. From this, we can recommend movies for them to watch. The dataset is taken from here. This code is loosely based off the fastai notebook. First, let get rid of the annoyingly complex user ids. We can make do with plain old integers. They’re much easier to handle. import pandas as pdratings = pd.read_csv('ratings.csv')movies = pd.read_csv('movies.csv') Then we’ll do the same thing for movie ids as well. u_uniq = ratings.userId.unique()user2idx = {o:i for i,o in enumerate(u_uniq)}ratings.userId = ratings.userId.apply(lambda x: user2idx[x]) We’ll need to get the number of users and the number of movies. n_users=int(ratings.userId.nunique())n_movies=int(ratings.movieId.nunique()) First, let’s create some random weights. We need to call. This allows us to avoid calling the base class explicitly. This makes the code more maintainable. These weights will be uniformly distributed between 0 and 0.05. The _ operator at the end of uniform_ denotes an inplace operation. Next, we add our Embedding matrices and latent factors. We’re creating an embedding matrix for our user ids and our movie ids. An embedding is basically an array lookup. When we multiply our one-hot encoded user ids by our weights most calculations cancel to 0 (0 * number = 0). All we're left with is a particular row in the weight matrix. That's basically just an array lookup. So we don’t need the matrix multiply and we don’t need the one-hot encoded array. Instead, we can just do an array lookup. This reduces memory usage and speeds up the neural network. It also reveals the intrinsic properties of the categorical variables. This idea was applied in a recent Kaggle competition and achieved 3rd place. The size of these embedding matrices will be determined by n_factors. These factors determine the number of latent factors in our dataset. Latent factors are immensely useful in our network. They reduce the need for feature engineering. For example, if User_id 554 likes Tom cruise and Tom cruise appears in a movie. User 554 will probably like the movie. Tom cruise appearing in a movie would be a latent feature. We didn't specify it before training. It just showed up. And we're glad that it did. Finally, we’ll need to add our forward function. As the name of this class would suggest we’re doing a dot product of embedding matrices. users,movies = cats[:,0],cats[:,1] gives us a minibatch of users and movies. We only look at categorical variables for embeddings. conts refers to continous variables. This minibatch size will be determined by the batchsize that you set. According to this paper, a large batch size can actually compromise the quality of the model. But according to this paper, a large batch size increases the quality of the model. There is no consensus at the moment. Many people are reporting contradictory results. So feel free to experiment with a batch size of your choosing. From that minibatch, we want to do an array lookup in our embedding matrix. self.u(users),self.m(movies) allows us to do that array lookup. This lookup is less computationally intensive that a matrix multiply of a one-hot encoded matrix and a weight matrix. (u*m).sum(1).view(-1, 1) is a cross product of the embeddings for users and movies and returns a single number. This is the predicted rating for that movie. Next, we need to create a ColumnarModelData object Then I’ll set up an optimiser. I’ll use stochastic gradient descent for this. optim.SGD implements stochastic gradient descent. Stochastistic gradient descent is computationally less intensive than gradient descent. This is because we introduce randomness when selecting the data point to calculate the derivative. We could also use optim.Adam. That implements rmsprop and momentum. In turn that results in an adaptive learning rate. But this paper shows that the solutions derived from SGD generalize far better than the solutions obtained from Adam. Plus it doesn't take that long to train anyway, so SGD isn't a bad option. Then we fit for a 3 epochs. fit(model, data, 3, opt, F.mse_loss) MSE loss is simply mean square error loss. This is calculated automatically. Fastai creates a neural net automatically behind the scenes. You can call a collab_learner which automatically creates a neural network for collaborative filtering. Fastai also has options for introducing Bias and dropout through this collab learner. Bias is very useful. We need to find user bias and movie bias. User bias would account for people who give high ratings for every movie. Movie bias would account for people who tend to give high ratings for a certain type of movie. Fastai adds in Bias automatically. Using fastai we can create a collab learner easily: Bias is very useful. We need to find user bias and movie bias. User bias would account for people who give high ratings for every movie. Movie bias would account for people who tend to give high ratings for a certain type of movie. Fastai adds in Bias automatically. Interestingly, fastai notes that you should be increase the y_range slightly. A sigmoid function is used to ensure that the final output is between the numbers specified in y_range. The issue is that a sigmoid function asymtotes. So we'll need to increase our y_range slightly. Fastai recommends increasing by 0.5. I’m using the suggested learning rate here with a small amount of weight decay. This is the combination that I found to work really well. We can train some more We finally get a MSE of 0.784105. But it's a very bumpy ride. Our loss jumps up and down considerably. That said 0.784105 is actually a better score than the LibRec system for collaborative filtering. They were getting 0.91**2 = 0.83 MSE. It’s also actually slightly better than the model that fastai created in their collaborative filtering lesson. They were getting 0.814652 MSE. We can adjust the size of the embedding by sending in a dictionary called emb_szs. This could be a useful parameter to adjust.Content-based recommendation. Collaborative filtering is just one method of building a recommendation system. Other methods could be more useful. A Content-based system is something I’m keeping in mind. That could look at metadata such as cast, crew, genre and director to make recommendations. I think some kind of hybrid solution would be optimal. This would combination a content-based recommendation system and a collaborative filtering system.Collaborative filtering is largely undermined by the cold-start problem. To overcome this we could potentially look at the users metadata. For example, we could look at things like: gender, age, city, time they accessed the site, etc. Just all the things they entered on the sign up form. Building a model on that data could be tricky, but if it works well it could be useful. We can adjust the size of the embedding by sending in a dictionary called emb_szs. This could be a useful parameter to adjust. Content-based recommendation. Collaborative filtering is just one method of building a recommendation system. Other methods could be more useful. A Content-based system is something I’m keeping in mind. That could look at metadata such as cast, crew, genre and director to make recommendations. I think some kind of hybrid solution would be optimal. This would combination a content-based recommendation system and a collaborative filtering system. Collaborative filtering is largely undermined by the cold-start problem. To overcome this we could potentially look at the users metadata. For example, we could look at things like: gender, age, city, time they accessed the site, etc. Just all the things they entered on the sign up form. Building a model on that data could be tricky, but if it works well it could be useful. Originally published at https://spiyer99.github.io on July 12, 2020.
[ { "code": null, "e": 472, "s": 172, "text": "Collaborative filtering is a tool that companies are increasingly using. Netflix uses it to recommend shows for you to watch. Facebook uses it to recommend who you should be friends with. Spotify uses it to recommend playlists and songs. It’s incredibly useful in recommending products to customers." }, { "code": null, "e": 668, "s": 472, "text": "In this post, I construct a collaborative filtering neural network with embeddings to understand how users would feel towards certain movies. From this, we can recommend movies for them to watch." }, { "code": null, "e": 752, "s": 668, "text": "The dataset is taken from here. This code is loosely based off the fastai notebook." }, { "code": null, "e": 878, "s": 752, "text": "First, let get rid of the annoyingly complex user ids. We can make do with plain old integers. They’re much easier to handle." }, { "code": null, "e": 968, "s": 878, "text": "import pandas as pdratings = pd.read_csv('ratings.csv')movies = pd.read_csv('movies.csv')" }, { "code": null, "e": 1020, "s": 968, "text": "Then we’ll do the same thing for movie ids as well." }, { "code": null, "e": 1158, "s": 1020, "text": "u_uniq = ratings.userId.unique()user2idx = {o:i for i,o in enumerate(u_uniq)}ratings.userId = ratings.userId.apply(lambda x: user2idx[x])" }, { "code": null, "e": 1222, "s": 1158, "text": "We’ll need to get the number of users and the number of movies." }, { "code": null, "e": 1299, "s": 1222, "text": "n_users=int(ratings.userId.nunique())n_movies=int(ratings.movieId.nunique())" }, { "code": null, "e": 1455, "s": 1299, "text": "First, let’s create some random weights. We need to call. This allows us to avoid calling the base class explicitly. This makes the code more maintainable." }, { "code": null, "e": 1587, "s": 1455, "text": "These weights will be uniformly distributed between 0 and 0.05. The _ operator at the end of uniform_ denotes an inplace operation." }, { "code": null, "e": 1643, "s": 1587, "text": "Next, we add our Embedding matrices and latent factors." }, { "code": null, "e": 1967, "s": 1643, "text": "We’re creating an embedding matrix for our user ids and our movie ids. An embedding is basically an array lookup. When we multiply our one-hot encoded user ids by our weights most calculations cancel to 0 (0 * number = 0). All we're left with is a particular row in the weight matrix. That's basically just an array lookup." }, { "code": null, "e": 2298, "s": 1967, "text": "So we don’t need the matrix multiply and we don’t need the one-hot encoded array. Instead, we can just do an array lookup. This reduces memory usage and speeds up the neural network. It also reveals the intrinsic properties of the categorical variables. This idea was applied in a recent Kaggle competition and achieved 3rd place." }, { "code": null, "e": 2437, "s": 2298, "text": "The size of these embedding matrices will be determined by n_factors. These factors determine the number of latent factors in our dataset." }, { "code": null, "e": 2798, "s": 2437, "text": "Latent factors are immensely useful in our network. They reduce the need for feature engineering. For example, if User_id 554 likes Tom cruise and Tom cruise appears in a movie. User 554 will probably like the movie. Tom cruise appearing in a movie would be a latent feature. We didn't specify it before training. It just showed up. And we're glad that it did." }, { "code": null, "e": 2847, "s": 2798, "text": "Finally, we’ll need to add our forward function." }, { "code": null, "e": 2936, "s": 2847, "text": "As the name of this class would suggest we’re doing a dot product of embedding matrices." }, { "code": null, "e": 3104, "s": 2936, "text": "users,movies = cats[:,0],cats[:,1] gives us a minibatch of users and movies. We only look at categorical variables for embeddings. conts refers to continous variables." }, { "code": null, "e": 3501, "s": 3104, "text": "This minibatch size will be determined by the batchsize that you set. According to this paper, a large batch size can actually compromise the quality of the model. But according to this paper, a large batch size increases the quality of the model. There is no consensus at the moment. Many people are reporting contradictory results. So feel free to experiment with a batch size of your choosing." }, { "code": null, "e": 3577, "s": 3501, "text": "From that minibatch, we want to do an array lookup in our embedding matrix." }, { "code": null, "e": 3759, "s": 3577, "text": "self.u(users),self.m(movies) allows us to do that array lookup. This lookup is less computationally intensive that a matrix multiply of a one-hot encoded matrix and a weight matrix." }, { "code": null, "e": 3916, "s": 3759, "text": "(u*m).sum(1).view(-1, 1) is a cross product of the embeddings for users and movies and returns a single number. This is the predicted rating for that movie." }, { "code": null, "e": 3967, "s": 3916, "text": "Next, we need to create a ColumnarModelData object" }, { "code": null, "e": 4282, "s": 3967, "text": "Then I’ll set up an optimiser. I’ll use stochastic gradient descent for this. optim.SGD implements stochastic gradient descent. Stochastistic gradient descent is computationally less intensive than gradient descent. This is because we introduce randomness when selecting the data point to calculate the derivative." }, { "code": null, "e": 4594, "s": 4282, "text": "We could also use optim.Adam. That implements rmsprop and momentum. In turn that results in an adaptive learning rate. But this paper shows that the solutions derived from SGD generalize far better than the solutions obtained from Adam. Plus it doesn't take that long to train anyway, so SGD isn't a bad option." }, { "code": null, "e": 4622, "s": 4594, "text": "Then we fit for a 3 epochs." }, { "code": null, "e": 4659, "s": 4622, "text": "fit(model, data, 3, opt, F.mse_loss)" }, { "code": null, "e": 4736, "s": 4659, "text": "MSE loss is simply mean square error loss. This is calculated automatically." }, { "code": null, "e": 4987, "s": 4736, "text": "Fastai creates a neural net automatically behind the scenes. You can call a collab_learner which automatically creates a neural network for collaborative filtering. Fastai also has options for introducing Bias and dropout through this collab learner." }, { "code": null, "e": 5254, "s": 4987, "text": "Bias is very useful. We need to find user bias and movie bias. User bias would account for people who give high ratings for every movie. Movie bias would account for people who tend to give high ratings for a certain type of movie. Fastai adds in Bias automatically." }, { "code": null, "e": 5306, "s": 5254, "text": "Using fastai we can create a collab learner easily:" }, { "code": null, "e": 5573, "s": 5306, "text": "Bias is very useful. We need to find user bias and movie bias. User bias would account for people who give high ratings for every movie. Movie bias would account for people who tend to give high ratings for a certain type of movie. Fastai adds in Bias automatically." }, { "code": null, "e": 5888, "s": 5573, "text": "Interestingly, fastai notes that you should be increase the y_range slightly. A sigmoid function is used to ensure that the final output is between the numbers specified in y_range. The issue is that a sigmoid function asymtotes. So we'll need to increase our y_range slightly. Fastai recommends increasing by 0.5." }, { "code": null, "e": 6026, "s": 5888, "text": "I’m using the suggested learning rate here with a small amount of weight decay. This is the combination that I found to work really well." }, { "code": null, "e": 6049, "s": 6026, "text": "We can train some more" }, { "code": null, "e": 6288, "s": 6049, "text": "We finally get a MSE of 0.784105. But it's a very bumpy ride. Our loss jumps up and down considerably. That said 0.784105 is actually a better score than the LibRec system for collaborative filtering. They were getting 0.91**2 = 0.83 MSE." }, { "code": null, "e": 6431, "s": 6288, "text": "It’s also actually slightly better than the model that fastai created in their collaborative filtering lesson. They were getting 0.814652 MSE." }, { "code": null, "e": 7382, "s": 6431, "text": "We can adjust the size of the embedding by sending in a dictionary called emb_szs. This could be a useful parameter to adjust.Content-based recommendation. Collaborative filtering is just one method of building a recommendation system. Other methods could be more useful. A Content-based system is something I’m keeping in mind. That could look at metadata such as cast, crew, genre and director to make recommendations. I think some kind of hybrid solution would be optimal. This would combination a content-based recommendation system and a collaborative filtering system.Collaborative filtering is largely undermined by the cold-start problem. To overcome this we could potentially look at the users metadata. For example, we could look at things like: gender, age, city, time they accessed the site, etc. Just all the things they entered on the sign up form. Building a model on that data could be tricky, but if it works well it could be useful." }, { "code": null, "e": 7509, "s": 7382, "text": "We can adjust the size of the embedding by sending in a dictionary called emb_szs. This could be a useful parameter to adjust." }, { "code": null, "e": 7958, "s": 7509, "text": "Content-based recommendation. Collaborative filtering is just one method of building a recommendation system. Other methods could be more useful. A Content-based system is something I’m keeping in mind. That could look at metadata such as cast, crew, genre and director to make recommendations. I think some kind of hybrid solution would be optimal. This would combination a content-based recommendation system and a collaborative filtering system." }, { "code": null, "e": 8335, "s": 7958, "text": "Collaborative filtering is largely undermined by the cold-start problem. To overcome this we could potentially look at the users metadata. For example, we could look at things like: gender, age, city, time they accessed the site, etc. Just all the things they entered on the sign up form. Building a model on that data could be tricky, but if it works well it could be useful." } ]
What is CGI in Python ? - GeeksforGeeks
10 Feb, 2022 CGI stands for Common Gateway Interface in Python which is a set of standards that explains how information or data is exchanged between the web server and a routine script. This interface is used by web servers to route information requests supplied by a browser or we can say that CGI is customary for external gateway programs to interface with information servers such as HTTP servers. A CGI script is invoked by an HTTP server, usually to course user input which is submitted through an HTML <FORM> or an <ISINDEX> element. Whenever we click on a hyperlink to browse a particular web page or URL, our browser interacts with the HTTP web server and asks for the same URL (or filename). Web Server then parses the URL and looks for the same filename. If that file is found, then that file is sent back to the browser, otherwise, an error message is sent indicating that we are demanding the wrong file. Web browser takes the response from a web server and displays it, then whether it is the received file from the webserver or an error message. But, conversely, it is possible to set up the HTTP server so that whenever a specific file is requested, then that file is not sent back, but instead, it is executed as a program, and whatever that program output is, that is sent back to our browser for display. This same function is called the Common Gateway Interface (or CGI) and the programs which are executed are called CGI scripts. In python, these CGI programs are Python Script. Example:Let us take a sample URL which passes two values to first_cgi.py program using GET method:/cgi-bin/first_cgi.py?your_name=Piyush&company_name=GeeksforGeeks Below is the first_cgi.py script to handle the input given by the above sample URL. Here we will use cgi module which will makes it very easy to access the passed information Python3 #!/usr/bin/python # Import CGI and CGIT moduleimport cgi, cgitb # to create instance of FieldStorage # class which we can use to work # with the submitted form dataform = cgi.FieldStorage() your_name = form.getvalue('your_name') # to get the data from fieldscomapny_name = form.getvalue('company_name') print ("Content-type:text/html\n")print ("<html>")print ("<head>")print ("<title>First CGI Program</title>")print ("</head>")print ("<body>")print ("<h2>Hello, %s is working in %s</h2>" % (your_name, company_name)) print ("</body>")print ("</html>") Output: Hello, Piyush is working in GeeksforGeeks reenadevi98412200 Python-CGI python-utility 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 How to Install PIP on Windows ? 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 Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 23946, "s": 23918, "text": "\n10 Feb, 2022" }, { "code": null, "e": 24475, "s": 23946, "text": "CGI stands for Common Gateway Interface in Python which is a set of standards that explains how information or data is exchanged between the web server and a routine script. This interface is used by web servers to route information requests supplied by a browser or we can say that CGI is customary for external gateway programs to interface with information servers such as HTTP servers. A CGI script is invoked by an HTTP server, usually to course user input which is submitted through an HTML <FORM> or an <ISINDEX> element." }, { "code": null, "e": 25434, "s": 24475, "text": "Whenever we click on a hyperlink to browse a particular web page or URL, our browser interacts with the HTTP web server and asks for the same URL (or filename). Web Server then parses the URL and looks for the same filename. If that file is found, then that file is sent back to the browser, otherwise, an error message is sent indicating that we are demanding the wrong file. Web browser takes the response from a web server and displays it, then whether it is the received file from the webserver or an error message. But, conversely, it is possible to set up the HTTP server so that whenever a specific file is requested, then that file is not sent back, but instead, it is executed as a program, and whatever that program output is, that is sent back to our browser for display. This same function is called the Common Gateway Interface (or CGI) and the programs which are executed are called CGI scripts. In python, these CGI programs are Python Script." }, { "code": null, "e": 25598, "s": 25434, "text": "Example:Let us take a sample URL which passes two values to first_cgi.py program using GET method:/cgi-bin/first_cgi.py?your_name=Piyush&company_name=GeeksforGeeks" }, { "code": null, "e": 25775, "s": 25598, "text": "Below is the first_cgi.py script to handle the input given by the above sample URL. Here we will use cgi module which will makes it very easy to access the passed information " }, { "code": null, "e": 25783, "s": 25775, "text": "Python3" }, { "code": "#!/usr/bin/python # Import CGI and CGIT moduleimport cgi, cgitb # to create instance of FieldStorage # class which we can use to work # with the submitted form dataform = cgi.FieldStorage() your_name = form.getvalue('your_name') # to get the data from fieldscomapny_name = form.getvalue('company_name') print (\"Content-type:text/html\\n\")print (\"<html>\")print (\"<head>\")print (\"<title>First CGI Program</title>\")print (\"</head>\")print (\"<body>\")print (\"<h2>Hello, %s is working in %s</h2>\" % (your_name, company_name)) print (\"</body>\")print (\"</html>\")", "e": 26374, "s": 25783, "text": null }, { "code": null, "e": 26382, "s": 26374, "text": "Output:" }, { "code": null, "e": 26427, "s": 26382, "text": " Hello, Piyush is working in GeeksforGeeks \n" }, { "code": null, "e": 26445, "s": 26427, "text": "reenadevi98412200" }, { "code": null, "e": 26456, "s": 26445, "text": "Python-CGI" }, { "code": null, "e": 26471, "s": 26456, "text": "python-utility" }, { "code": null, "e": 26478, "s": 26471, "text": "Python" }, { "code": null, "e": 26576, "s": 26478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26585, "s": 26576, "text": "Comments" }, { "code": null, "e": 26598, "s": 26585, "text": "Old Comments" }, { "code": null, "e": 26616, "s": 26598, "text": "Python Dictionary" }, { "code": null, "e": 26651, "s": 26616, "text": "Read a file line by line in Python" }, { "code": null, "e": 26683, "s": 26651, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26725, "s": 26683, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26768, "s": 26725, "text": "Python program to convert a list to string" }, { "code": null, "e": 26794, "s": 26768, "text": "Python String | replace()" }, { "code": null, "e": 26838, "s": 26794, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26863, "s": 26838, "text": "sum() function in Python" }, { "code": null, "e": 26900, "s": 26863, "text": "Create a Pandas DataFrame from Lists" } ]
Iterating over ArrayLists in Java - GeeksforGeeks
31 Oct, 2021 ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. With the introduction and upgradations in java versions, newer methods are being available as if we do see from Java8 perceptive lambda expressions and streams concepts were not available before it as it been introduced in java version8. Methods: Using for loopsUsing whileUsing for-each loopUsing IteratorUsing Lambda expressions (after Java8 only)Using Enumeration interface Using for loops Using while Using for-each loop Using Iterator Using Lambda expressions (after Java8 only) Using Enumeration interface Let us discuss these methods of which straight away we can perceive starting three methods are simply the naive approaches and further onwards methods carry some optimization with them. Do remember here while traversing elements are lesser we generally tend to iterate via naive approach only else if the size of elements to be inserted is big then we do use optimal approaches. Let us wrap each of the above approaches quickly. Method 1: Using for loop Java // Java program to iterate over an ArrayList// Using for loop // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating and initializing the ArrayList // Declaring object of integer type List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // Iterating using for loop for (int i = 0; i < numbers.size(); i++) // Printing and display the elements in ArrayList System.out.print(numbers.get(i) + " "); }} 1 2 3 4 5 6 7 8 Method 2: Using while loop Java // Java Program to Illustrate ArrayList// Using While Loop // Importing required classesimport java.util.ArrayList ; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating and initializing the ArrayList // Declaring object of integer type ArrayList<Integer> al = new ArrayList<Integer>(); // Adding elements to ArrayList // using add() method al.add(3); al.add(1); al.add(7); al.add(20); al.add(5); // Step 1: Setting and initializing a variable // as per syntax of while loop // Initially declaring and setting int val = 0; // Step 2: Condition // Till our counter variable is lesser than size of // ArrayList while (al.size() > val) { // Printing the element which holds above // condition true System.out.println(al.get(val)); // Step 3: Terminating condition by incrementing // our counter in each iteration val++ ; } }} 3 1 7 20 5 Method 3: Using for each loop Java // Java Program to Iterate over Arraylist// using for Each loop // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing ArrayList List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // For Each Loop for iterating ArrayList for (Integer i : numbers) // Printing the elements of ArrayList System.out.print(i + " "); }} 1 2 3 4 5 6 7 8 Method 4: Using Iterator Java // Java program to iterate over an ArrayList// Using Iterator // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing ArrayList List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // Iterating ArrayList using Iterator Iterator it = numbers.iterator(); // Holds true till there is single element // remaining in the list while (it.hasNext()) // Print the elements of ArrayList System.out.print(it.next() + " "); }} 1 2 3 4 5 6 7 8 Method 5: Using Lambda expressions Java // Java program to iterate over an arraylist// using Iterator in Java8 with Lambda Expression // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing ArrayList // Custom input elements List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // Printing numbers using lambda expressions // been introduced later in java8 numbers.forEach(number->System.out.println(number)); }} 1 2 3 4 5 6 7 8 Method 6: Using Enumeration interface Java // Java Program to Iterate over ArrayList elements// Using Enumeration // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.Enumeration; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList ArrayList<Integer> al = new ArrayList<Integer>(); // Adding elements to ArrayList al.add(34); al.add(12); al.add(34); al.add(23); al.add(54); // Getting an enumeration object Enumeration<Integer> e = Collections.enumeration(al); // Till elements are there while (e.hasMoreElements()) // Print elements using nextElement() method System.out.println(e.nextElement()); }} 34 12 34 23 54 Now it is a further additive to the article as we are done with discussing all methods that can be used to iterate over elements. Till now we have traversed over input elements only and have not seen the traversal what if we play with elements, so do we are considering Example Java // Java program to demonstrate Working of// Iterator.remove() on Arraylist // Importing utility classesimport java.util.List;import java.util.ArrayList;import java.util.Iterator; // Main classpublic class GFG{ // Main driver method public static void main(String[] args) { // Creating a List with referenceto ArrayList List<Integer> al = new ArrayList<Integer>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Remove elements smaller than 10 using // Iterator.remove() Iterator itr = al.iterator(); while (itr.hasNext()) { int x = (Integer)itr.next(); if (x < 10) itr.remove(); } System.out.println("Modified ArrayList : " + al); }} Modified ArrayList : [10, 20, 30] Removing Items during Traversal: It is not recommended to use ArrayList.remove() when iterating over elements. This may lead to ConcurrentModificationException (Refer to this for a sample program with this exception). When iterating over elements, it is recommended to use Iterator.remove() method. This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SandeepChaudhary solankimayank arorakashish0911 sagartomar9927 anikakapoor Java-ArrayList Java-List-Programs Java 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 Overriding in Java Queue Interface In Java Functional Interfaces in Java How to add an element to an Array in Java? Stream In Java
[ { "code": null, "e": 23672, "s": 23644, "text": "\n31 Oct, 2021" }, { "code": null, "e": 23967, "s": 23672, "text": "ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package." }, { "code": null, "e": 24205, "s": 23967, "text": "With the introduction and upgradations in java versions, newer methods are being available as if we do see from Java8 perceptive lambda expressions and streams concepts were not available before it as it been introduced in java version8." }, { "code": null, "e": 24214, "s": 24205, "text": "Methods:" }, { "code": null, "e": 24344, "s": 24214, "text": "Using for loopsUsing whileUsing for-each loopUsing IteratorUsing Lambda expressions (after Java8 only)Using Enumeration interface" }, { "code": null, "e": 24360, "s": 24344, "text": "Using for loops" }, { "code": null, "e": 24372, "s": 24360, "text": "Using while" }, { "code": null, "e": 24392, "s": 24372, "text": "Using for-each loop" }, { "code": null, "e": 24407, "s": 24392, "text": "Using Iterator" }, { "code": null, "e": 24451, "s": 24407, "text": "Using Lambda expressions (after Java8 only)" }, { "code": null, "e": 24479, "s": 24451, "text": "Using Enumeration interface" }, { "code": null, "e": 24908, "s": 24479, "text": "Let us discuss these methods of which straight away we can perceive starting three methods are simply the naive approaches and further onwards methods carry some optimization with them. Do remember here while traversing elements are lesser we generally tend to iterate via naive approach only else if the size of elements to be inserted is big then we do use optimal approaches. Let us wrap each of the above approaches quickly." }, { "code": null, "e": 24934, "s": 24908, "text": "Method 1: Using for loop " }, { "code": null, "e": 24939, "s": 24934, "text": "Java" }, { "code": "// Java program to iterate over an ArrayList// Using for loop // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating and initializing the ArrayList // Declaring object of integer type List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // Iterating using for loop for (int i = 0; i < numbers.size(); i++) // Printing and display the elements in ArrayList System.out.print(numbers.get(i) + \" \"); }}", "e": 25576, "s": 24939, "text": null }, { "code": null, "e": 25593, "s": 25576, "text": "1 2 3 4 5 6 7 8 " }, { "code": null, "e": 25621, "s": 25593, "text": "Method 2: Using while loop " }, { "code": null, "e": 25626, "s": 25621, "text": "Java" }, { "code": "// Java Program to Illustrate ArrayList// Using While Loop // Importing required classesimport java.util.ArrayList ; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating and initializing the ArrayList // Declaring object of integer type ArrayList<Integer> al = new ArrayList<Integer>(); // Adding elements to ArrayList // using add() method al.add(3); al.add(1); al.add(7); al.add(20); al.add(5); // Step 1: Setting and initializing a variable // as per syntax of while loop // Initially declaring and setting int val = 0; // Step 2: Condition // Till our counter variable is lesser than size of // ArrayList while (al.size() > val) { // Printing the element which holds above // condition true System.out.println(al.get(val)); // Step 3: Terminating condition by incrementing // our counter in each iteration val++ ; } }}", "e": 26721, "s": 25626, "text": null }, { "code": null, "e": 26732, "s": 26721, "text": "3\n1\n7\n20\n5" }, { "code": null, "e": 26763, "s": 26732, "text": "Method 3: Using for each loop " }, { "code": null, "e": 26768, "s": 26763, "text": "Java" }, { "code": "// Java Program to Iterate over Arraylist// using for Each loop // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing ArrayList List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // For Each Loop for iterating ArrayList for (Integer i : numbers) // Printing the elements of ArrayList System.out.print(i + \" \"); }}", "e": 27286, "s": 26768, "text": null }, { "code": null, "e": 27303, "s": 27286, "text": "1 2 3 4 5 6 7 8 " }, { "code": null, "e": 27329, "s": 27303, "text": "Method 4: Using Iterator " }, { "code": null, "e": 27334, "s": 27329, "text": "Java" }, { "code": "// Java program to iterate over an ArrayList// Using Iterator // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing ArrayList List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // Iterating ArrayList using Iterator Iterator it = numbers.iterator(); // Holds true till there is single element // remaining in the list while (it.hasNext()) // Print the elements of ArrayList System.out.print(it.next() + \" \"); }}", "e": 27971, "s": 27334, "text": null }, { "code": null, "e": 27988, "s": 27971, "text": "1 2 3 4 5 6 7 8 " }, { "code": null, "e": 28023, "s": 27988, "text": "Method 5: Using Lambda expressions" }, { "code": null, "e": 28028, "s": 28023, "text": "Java" }, { "code": "// Java program to iterate over an arraylist// using Iterator in Java8 with Lambda Expression // Importing all utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing ArrayList // Custom input elements List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // Printing numbers using lambda expressions // been introduced later in java8 numbers.forEach(number->System.out.println(number)); }}", "e": 28622, "s": 28028, "text": null }, { "code": null, "e": 28638, "s": 28622, "text": "1\n2\n3\n4\n5\n6\n7\n8" }, { "code": null, "e": 28676, "s": 28638, "text": "Method 6: Using Enumeration interface" }, { "code": null, "e": 28681, "s": 28676, "text": "Java" }, { "code": "// Java Program to Iterate over ArrayList elements// Using Enumeration // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.Enumeration; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList ArrayList<Integer> al = new ArrayList<Integer>(); // Adding elements to ArrayList al.add(34); al.add(12); al.add(34); al.add(23); al.add(54); // Getting an enumeration object Enumeration<Integer> e = Collections.enumeration(al); // Till elements are there while (e.hasMoreElements()) // Print elements using nextElement() method System.out.println(e.nextElement()); }}", "e": 29484, "s": 28681, "text": null }, { "code": null, "e": 29499, "s": 29484, "text": "34\n12\n34\n23\n54" }, { "code": null, "e": 29770, "s": 29499, "text": "Now it is a further additive to the article as we are done with discussing all methods that can be used to iterate over elements. Till now we have traversed over input elements only and have not seen the traversal what if we play with elements, so do we are considering " }, { "code": null, "e": 29779, "s": 29770, "text": "Example " }, { "code": null, "e": 29784, "s": 29779, "text": "Java" }, { "code": "// Java program to demonstrate Working of// Iterator.remove() on Arraylist // Importing utility classesimport java.util.List;import java.util.ArrayList;import java.util.Iterator; // Main classpublic class GFG{ // Main driver method public static void main(String[] args) { // Creating a List with referenceto ArrayList List<Integer> al = new ArrayList<Integer>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Remove elements smaller than 10 using // Iterator.remove() Iterator itr = al.iterator(); while (itr.hasNext()) { int x = (Integer)itr.next(); if (x < 10) itr.remove(); } System.out.println(\"Modified ArrayList : \" + al); }}", "e": 30623, "s": 29784, "text": null }, { "code": null, "e": 30657, "s": 30623, "text": "Modified ArrayList : [10, 20, 30]" }, { "code": null, "e": 30957, "s": 30657, "text": "Removing Items during Traversal: It is not recommended to use ArrayList.remove() when iterating over elements. This may lead to ConcurrentModificationException (Refer to this for a sample program with this exception). When iterating over elements, it is recommended to use Iterator.remove() method. " }, { "code": null, "e": 31378, "s": 30957, "text": "This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31395, "s": 31378, "text": "SandeepChaudhary" }, { "code": null, "e": 31409, "s": 31395, "text": "solankimayank" }, { "code": null, "e": 31426, "s": 31409, "text": "arorakashish0911" }, { "code": null, "e": 31441, "s": 31426, "text": "sagartomar9927" }, { "code": null, "e": 31453, "s": 31441, "text": "anikakapoor" }, { "code": null, "e": 31468, "s": 31453, "text": "Java-ArrayList" }, { "code": null, "e": 31487, "s": 31468, "text": "Java-List-Programs" }, { "code": null, "e": 31492, "s": 31487, "text": "Java" }, { "code": null, "e": 31497, "s": 31492, "text": "Java" }, { "code": null, "e": 31595, "s": 31497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31604, "s": 31595, "text": "Comments" }, { "code": null, "e": 31617, "s": 31604, "text": "Old Comments" }, { "code": null, "e": 31636, "s": 31617, "text": "Interfaces in Java" }, { "code": null, "e": 31660, "s": 31636, "text": "Singleton Class in Java" }, { "code": null, "e": 31679, "s": 31660, "text": "LinkedList in Java" }, { "code": null, "e": 31699, "s": 31679, "text": "Collections in Java" }, { "code": null, "e": 31711, "s": 31699, "text": "Set in Java" }, { "code": null, "e": 31730, "s": 31711, "text": "Overriding in Java" }, { "code": null, "e": 31754, "s": 31730, "text": "Queue Interface In Java" }, { "code": null, "e": 31784, "s": 31754, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31827, "s": 31784, "text": "How to add an element to an Array in Java?" } ]
JavaScript Date Set Methods
Set Date methods let you set date values (years, months, days, hours, minutes, seconds, milliseconds) for a Date Object. Set Date methods are used for setting a part of a date: The setFullYear() method sets the year of a date object. In this example to 2020: The setFullYear() method can optionally set month and day: The setMonth() method sets the month of a date object (0-11): The setDate() method sets the day of a date object (1-31): The setDate() method can also be used to add days to a date: If adding days shifts the month or year, the changes are handled automatically by the Date object. The setHours() method sets the hours of a date object (0-23): The setMinutes() method sets the minutes of a date object (0-59): The setSeconds() method sets the seconds of a date object (0-59): Dates can easily be compared. The following example compares today's date with January 14, 2100: JavaScript counts months from 0 to 11. January is 0. December is 11. For a complete Date reference, go to our: Complete JavaScript Date Reference. The reference contains descriptions and examples of all Date properties and methods. Use the correct Date method to set the year of a date object to 2020. const d = new Date(); d.; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 122, "s": 0, "text": "Set Date methods let you set date values (years, \nmonths, days, hours, minutes, seconds, milliseconds) for a Date Object." }, { "code": null, "e": 178, "s": 122, "text": "Set Date methods are used for setting a part of a date:" }, { "code": null, "e": 260, "s": 178, "text": "The setFullYear() method sets the year of a date object. In this example to 2020:" }, { "code": null, "e": 319, "s": 260, "text": "The setFullYear() method can optionally set month and day:" }, { "code": null, "e": 381, "s": 319, "text": "The setMonth() method sets the month of a date object (0-11):" }, { "code": null, "e": 440, "s": 381, "text": "The setDate() method sets the day of a date object (1-31):" }, { "code": null, "e": 501, "s": 440, "text": "The setDate() method can also be used to add days to a date:" }, { "code": null, "e": 600, "s": 501, "text": "If adding days shifts the month or year, the changes are handled automatically by the Date object." }, { "code": null, "e": 662, "s": 600, "text": "The setHours() method sets the hours of a date object (0-23):" }, { "code": null, "e": 728, "s": 662, "text": "The setMinutes() method sets the minutes of a date object (0-59):" }, { "code": null, "e": 794, "s": 728, "text": "The setSeconds() method sets the seconds of a date object (0-59):" }, { "code": null, "e": 824, "s": 794, "text": "Dates can easily be compared." }, { "code": null, "e": 891, "s": 824, "text": "The following example compares today's date with January 14, 2100:" }, { "code": null, "e": 960, "s": 891, "text": "JavaScript counts months from 0 to 11. January is 0. December is 11." }, { "code": null, "e": 1002, "s": 960, "text": "For a complete Date reference, go to our:" }, { "code": null, "e": 1038, "s": 1002, "text": "Complete JavaScript Date Reference." }, { "code": null, "e": 1124, "s": 1038, "text": "The reference contains descriptions and examples of all Date properties and \nmethods." }, { "code": null, "e": 1194, "s": 1124, "text": "Use the correct Date method to set the year of a date object to 2020." }, { "code": null, "e": 1221, "s": 1194, "text": "const d = new Date();\nd.;\n" }, { "code": null, "e": 1240, "s": 1221, "text": "Start the Exercise" }, { "code": null, "e": 1273, "s": 1240, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1315, "s": 1273, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1422, "s": 1315, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1441, "s": 1422, "text": "[email protected]" } ]
How to put an input element on the same line as its label? - GeeksforGeeks
30 Jul, 2021 There are several approaches to make an input element the same as its label. Few approaches are discussed here. Basic CSS to label, span, and input to get clear outputs. Using float and overflow attributes: Make a label and style it with float attribute. Now set the label float(position) left or right according to your requirement. This will align your label accordingly. Overflow property for input is used here to clip the overflow part and show the rest. Example:<!DOCTYPE html><html lang="en"> <head> <style> h1 { color: green; } label { float: left; } span { display: block; overflow: hidden; padding: 0px 4px 0px 6px; } input { width: 70%; } </style></head> <body> <h1>GeeksforGeeks</h1> <label for="test">Enroll with us:</label> <span> <input name="test" id="test" type="text" placeholder="Enter your input"/> </span></body> </html> <!DOCTYPE html><html lang="en"> <head> <style> h1 { color: green; } label { float: left; } span { display: block; overflow: hidden; padding: 0px 4px 0px 6px; } input { width: 70%; } </style></head> <body> <h1>GeeksforGeeks</h1> <label for="test">Enroll with us:</label> <span> <input name="test" id="test" type="text" placeholder="Enter your input"/> </span></body> </html> Output: Using table cell attribute in display property: Make a label inside a div and give the display property. To make the input element and span as equally placed use table-cell attribute in those tags. This attribute makes the element behaves a td element. Whatever item is to be made nearby, the table-cell attribute does it. Example:<!DOCTYPE html><html lang="en"> <head> <style> h1 { color: green; } .container { display: table; width: 100% } label { display: table-cell; width: 1px; white-space: nowrap; } span { display: table-cell; padding: 0 4px 0 6px; } input { width: 70%; } </style></head> <body> <h1>GeeksforGeeks</h1> <div class="container"> <label for="test">Enroll with us:</label> <span><input name="test" id="test" type="text" placeholder="Enter your input" /> </span> </div></body> </html> <!DOCTYPE html><html lang="en"> <head> <style> h1 { color: green; } .container { display: table; width: 100% } label { display: table-cell; width: 1px; white-space: nowrap; } span { display: table-cell; padding: 0 4px 0 6px; } input { width: 70%; } </style></head> <body> <h1>GeeksforGeeks</h1> <div class="container"> <label for="test">Enroll with us:</label> <span><input name="test" id="test" type="text" placeholder="Enter your input" /> </span> </div></body> </html> Output: HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc Picked CSS 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 How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? How to set the default value for an HTML <select> element ? Types of CSS (Cascading Style Sheet) Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 24431, "s": 24403, "text": "\n30 Jul, 2021" }, { "code": null, "e": 24601, "s": 24431, "text": "There are several approaches to make an input element the same as its label. Few approaches are discussed here. Basic CSS to label, span, and input to get clear outputs." }, { "code": null, "e": 24891, "s": 24601, "text": "Using float and overflow attributes: Make a label and style it with float attribute. Now set the label float(position) left or right according to your requirement. This will align your label accordingly. Overflow property for input is used here to clip the overflow part and show the rest." }, { "code": null, "e": 25470, "s": 24891, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <style> h1 { color: green; } label { float: left; } span { display: block; overflow: hidden; padding: 0px 4px 0px 6px; } input { width: 70%; } </style></head> <body> <h1>GeeksforGeeks</h1> <label for=\"test\">Enroll with us:</label> <span> <input name=\"test\" id=\"test\" type=\"text\" placeholder=\"Enter your input\"/> </span></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> h1 { color: green; } label { float: left; } span { display: block; overflow: hidden; padding: 0px 4px 0px 6px; } input { width: 70%; } </style></head> <body> <h1>GeeksforGeeks</h1> <label for=\"test\">Enroll with us:</label> <span> <input name=\"test\" id=\"test\" type=\"text\" placeholder=\"Enter your input\"/> </span></body> </html>", "e": 26041, "s": 25470, "text": null }, { "code": null, "e": 26049, "s": 26041, "text": "Output:" }, { "code": null, "e": 26372, "s": 26049, "text": "Using table cell attribute in display property: Make a label inside a div and give the display property. To make the input element and span as equally placed use table-cell attribute in those tags. This attribute makes the element behaves a td element. Whatever item is to be made nearby, the table-cell attribute does it." }, { "code": null, "e": 27146, "s": 26372, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <style> h1 { color: green; } .container { display: table; width: 100% } label { display: table-cell; width: 1px; white-space: nowrap; } span { display: table-cell; padding: 0 4px 0 6px; } input { width: 70%; } </style></head> <body> <h1>GeeksforGeeks</h1> <div class=\"container\"> <label for=\"test\">Enroll with us:</label> <span><input name=\"test\" id=\"test\" type=\"text\" placeholder=\"Enter your input\" /> </span> </div></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> h1 { color: green; } .container { display: table; width: 100% } label { display: table-cell; width: 1px; white-space: nowrap; } span { display: table-cell; padding: 0 4px 0 6px; } input { width: 70%; } </style></head> <body> <h1>GeeksforGeeks</h1> <div class=\"container\"> <label for=\"test\">Enroll with us:</label> <span><input name=\"test\" id=\"test\" type=\"text\" placeholder=\"Enter your input\" /> </span> </div></body> </html>", "e": 27912, "s": 27146, "text": null }, { "code": null, "e": 27920, "s": 27912, "text": "Output:" }, { "code": null, "e": 28114, "s": 27920, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 28300, "s": 28114, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 28437, "s": 28300, "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": 28446, "s": 28437, "text": "CSS-Misc" }, { "code": null, "e": 28456, "s": 28446, "text": "HTML-Misc" }, { "code": null, "e": 28463, "s": 28456, "text": "Picked" }, { "code": null, "e": 28467, "s": 28463, "text": "CSS" }, { "code": null, "e": 28472, "s": 28467, "text": "HTML" }, { "code": null, "e": 28489, "s": 28472, "text": "Web Technologies" }, { "code": null, "e": 28516, "s": 28489, "text": "Web technologies Questions" }, { "code": null, "e": 28521, "s": 28516, "text": "HTML" }, { "code": null, "e": 28619, "s": 28521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28628, "s": 28619, "text": "Comments" }, { "code": null, "e": 28641, "s": 28628, "text": "Old Comments" }, { "code": null, "e": 28699, "s": 28641, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28736, "s": 28699, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28777, "s": 28736, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28814, "s": 28777, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28878, "s": 28814, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28938, "s": 28878, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28975, "s": 28938, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 29028, "s": 28975, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29078, "s": 29028, "text": "How to Insert Form Data into Database using PHP ?" } ]
How to convert a value of one type to another type in SQL server - GeeksforGeeks
07 Dec, 2020 Convert means to change the form or value of something. The CONVERT() function in SQL server is used to convert a value of one type to another type. Syntax : SELECT CONVERT ( target_type ( length ), expression ) Parameters used : target_type –It is the target data type to which the to expression will be converted, e.g: INT, BIT, SQL_VARIANT, etc. length –It provides the length of the target_type. Length is not mandatory. Default length is set to 30. expression –expression is anything that will be converted. Example-1 :To convert a decimal to an integer :In below example, the CONVERT() function is used to convert the decimal number 7.85 to an integer. SELECT CONVERT(INT, 7.85) AS Result; Output : Example-2 :To convert a decimal to another decimal :In below example, the CONVERT() function is used to convert the decimal number 8.99 to another decimal number with zero scales. SELECT CAST(8.99 AS DEC(2, 0)) AS Result; Output : Example-3 :To convert a string to a datetime value :In below example, the CONVERT() function is used to convert the string ‘2020-05-14’ to a datetime value. SELECT CONVERT(DATETIME, '2020-05-14') AS Result; Output : Example-4 :To convert a datetime value to a string :In below example, the CONVERT() function is used to convert the current date and time to a string with a definite style. SELECT CONVERT(VARCHAR, GETDATE(), 13) AS Result; Output : DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter Composite Key in SQL SQL using Python SQL | DROP, TRUNCATE SQL indexes SQL | Date functions What is Temporary Table in SQL? Window functions in SQL How to Concat Two Columns Into One With the Existing Column Name in MySQL?
[ { "code": null, "e": 23877, "s": 23849, "text": "\n07 Dec, 2020" }, { "code": null, "e": 24026, "s": 23877, "text": "Convert means to change the form or value of something. The CONVERT() function in SQL server is used to convert a value of one type to another type." }, { "code": null, "e": 24035, "s": 24026, "text": "Syntax :" }, { "code": null, "e": 24092, "s": 24035, "text": "SELECT CONVERT \n( target_type ( length ), expression ) \n" }, { "code": null, "e": 24110, "s": 24092, "text": "Parameters used :" }, { "code": null, "e": 24229, "s": 24110, "text": "target_type –It is the target data type to which the to expression will be converted, e.g: INT, BIT, SQL_VARIANT, etc." }, { "code": null, "e": 24334, "s": 24229, "text": "length –It provides the length of the target_type. Length is not mandatory. Default length is set to 30." }, { "code": null, "e": 24393, "s": 24334, "text": "expression –expression is anything that will be converted." }, { "code": null, "e": 24539, "s": 24393, "text": "Example-1 :To convert a decimal to an integer :In below example, the CONVERT() function is used to convert the decimal number 7.85 to an integer." }, { "code": null, "e": 24577, "s": 24539, "text": "SELECT CONVERT(INT, 7.85) AS Result;\n" }, { "code": null, "e": 24586, "s": 24577, "text": "Output :" }, { "code": null, "e": 24766, "s": 24586, "text": "Example-2 :To convert a decimal to another decimal :In below example, the CONVERT() function is used to convert the decimal number 8.99 to another decimal number with zero scales." }, { "code": null, "e": 24809, "s": 24766, "text": "SELECT CAST(8.99 AS DEC(2, 0)) \nAS Result;" }, { "code": null, "e": 24818, "s": 24809, "text": "Output :" }, { "code": null, "e": 24975, "s": 24818, "text": "Example-3 :To convert a string to a datetime value :In below example, the CONVERT() function is used to convert the string ‘2020-05-14’ to a datetime value." }, { "code": null, "e": 25026, "s": 24975, "text": "SELECT CONVERT(DATETIME, '2020-05-14') \nAS Result;" }, { "code": null, "e": 25035, "s": 25026, "text": "Output :" }, { "code": null, "e": 25208, "s": 25035, "text": "Example-4 :To convert a datetime value to a string :In below example, the CONVERT() function is used to convert the current date and time to a string with a definite style." }, { "code": null, "e": 25260, "s": 25208, "text": "SELECT CONVERT(VARCHAR, GETDATE(), 13) \nAS Result;" }, { "code": null, "e": 25269, "s": 25260, "text": "Output :" }, { "code": null, "e": 25278, "s": 25269, "text": "DBMS-SQL" }, { "code": null, "e": 25289, "s": 25278, "text": "SQL-Server" }, { "code": null, "e": 25293, "s": 25289, "text": "SQL" }, { "code": null, "e": 25297, "s": 25293, "text": "SQL" }, { "code": null, "e": 25395, "s": 25297, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25404, "s": 25395, "text": "Comments" }, { "code": null, "e": 25417, "s": 25404, "text": "Old Comments" }, { "code": null, "e": 25483, "s": 25417, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25561, "s": 25483, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 25582, "s": 25561, "text": "Composite Key in SQL" }, { "code": null, "e": 25599, "s": 25582, "text": "SQL using Python" }, { "code": null, "e": 25620, "s": 25599, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 25632, "s": 25620, "text": "SQL indexes" }, { "code": null, "e": 25653, "s": 25632, "text": "SQL | Date functions" }, { "code": null, "e": 25685, "s": 25653, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25709, "s": 25685, "text": "Window functions in SQL" } ]
How to use Scrapy Items? - GeeksforGeeks
19 Sep, 2021 In this article, we will scrape Quotes data using scrapy items, from the webpage https://quotes.toscrape.com/tag/reading/. The main objective of scraping, is to prepare structured data, from unstructured resources. Scrapy Items are wrappers around, the dictionary data structures. Code can be written, such that, the extracted data is returned, as Item objects, in the format of “key-value” pairs. Using Scrapy Items is beneficial when – As the scraped data volume increases, they become irregular to handle. As your data gets complex, it is vulnerable to typos, and, at times may return faulty data. Formatting of data scraped, is easier, as Item objects, can be further passed to Item Pipelines. Cleansing the data, is easy, if we scrape the data, as Items. Validating data, handling missing data, is easier with Scrapy Items. Via the Item adapter library, Scrapy supports various Item Types. One can choose, the Item type, they want. Following, are the Item Types supported: Dictionaries – Items can be written in form of dictionary objects. They are convenient to use. Item objects – They provide dictionary like API, wherein we need to declare, fields for the Item, needed. It consists of key-value pair, of Field objects used, while declaring the Item class. In this tutorial, we are using Item objects. Dataclass objects – They are used, when you need to store, the scraped values, in JSON or CSV files. Here we need to define, the datatype of each field, needed. attr.s – The attr.s allows, defining item classes, with field names, so that scraped data, can be imported, to different file formats. They work similar to Dataclass objects only that the attr package needs to be installed. The Scrapy library, requires a Python version, of 3.6 and above. Install the Scrapy library, by executing the following command, at the terminal – pip install Scrapy This command will install the Scrapy library, in the project environment. Now, we can create a Scrapy project, to write the Spider code. Scrapy has, an efficient command-line tool, also called the ‘Scrapy tool’. Commands accept a different set of arguments and options based on their purpose. To write the Spider code, we begin by creating, a Scrapy project, by executing the following command, at the terminal – scrapy startproject <project_name> Output: Scrapy ‘startproject’ command to create Spider project This should create a folder, in your current directory. It contains a ‘scrapy.cfg’, which is a configuration file, of the project. The folder structure is as shown below: The folder structure of ‘gfg_spiderreadingitems’ The scrapy.cfg, is a project configuration file. The folder, that contains this file, is the root directory. The folder structure, of folder, created is as follows: File ‘items.py’ inside the ‘gfg_spiderreadingitems’ folder The folder, contains items.py,middlerwares.py and other settings files, along with the ‘spiders’ folder. The crawling code will be written, in a spider python file. We will alter, ‘items.py’ file, to mention, our data items, to be extracted. Keep the contents of ‘items.py’, as they are currently. The code for web scraping is written in the spider code file. To create the spider file, we will make use, of the ‘genspider’ command. Please note, that this command, is executed, at the same level, where scrapy.cfg file is present. We are scraping, reading quotes present, on https://quotes.toscrape.com/tag/reading/ webpage. Hence, we will run the command as – scrapy genspider spider_name url_to_be_scraped Use ‘genspider’ command to create Spider file The above command will create a spider file, “gfg_spiitemsread.py” in the ‘spiders’ folder. The spider name will also be,’gfg_spiitemsread’. The default code, for the same, is as follows: Python3 # Import the required librariesimport scrapy # Spider Class Created class GfgSpiitemsreadSpider(scrapy.Spider): # Name of the spider name = 'gfg_spiitemsread' # The domain to be scraped allowed_domains = ['quotes.toscrape.com/tag/reading/'] # The URLs from domain to scrape start_urls = ['http://quotes.toscrape.com/tag/reading//'] # Spider default callback function def parse(self, response): pass We will scrape Quotes Title, Author and Tags from the webpage https://quotes.toscrape.com/tag/reading/. Scrapy provides us, with Selectors, to “select” parts of the webpage, desired. Selectors are CSS or XPath expressions, written to extract data, from the HTML documents. In this tutorial, we will make use of XPath expressions, to select the details we need. Let us understand, the steps for writing the selector syntax, in the spider code. The default callback method, present in the spider class, responsible for, processing the response received, is the parse() method. We will write, selectors with XPath expressions, responsible for data extraction, here. Select the element to be extracted, on the webpage, say Right-Click, and choose the Inspect option. This will allow us, to view its CSS attributes. When we right-click on the first Quote and choose Inspect, we can see it has the CSS ‘class’ attribute “quote”. Similarly, all the quotes on the webpage, have CSS ‘class’ attribute as “quote”. It can be as seen below: Right Click first quote, and, check its CSS “class” attribute Based on this, the XPath expression, for the same, can be written as – quotes = response.xpath(‘//*[@class=”quote”]’). This syntax will fetch all elements, having “quote”, as the CSS ‘class’ attribute. We will fetch the Quote Title, Author and Tags, of all the Quotes. Hence, we will write XPath expressions for extracting them, in a loop. For Quote Title, CSS ‘class’ attribute, is “text”. Hence, the XPath expression, for the same, would be – quote.xpath(‘.//*[@class=”text”]/text()’).extract_first(). The text() method, will extract the text, of the Quote title. The extract_first() method, will give the first matching value, with the CSS attribute “text”. The dot operator ‘.’ in the start, indicates extracting data, from a single quote. Similarly, CSS attributes, “class” and “itemprop”, for author element, is “author”. We can use, any of these, in the XPath expression. The syntax would be – quote.xpath(‘.//*[@itemprop=”author”]/text()’).extract(). This will extract, the Author name, where the CSS ‘itemprop’ attribute is ‘author’. The CSS attributes, “class” and “itemprop”, for tags element, is “keywords”. We can use, any of these, in the XPath expression. Since there are many tags, for any quote, looping through them, will be complex. Hence, we will extract the CSS attribute “content”, from every quote. The XPath expression for the same is – quote.xpath(‘.//*[@itemprop=”keywords”]/@content’).extract(). This will extract, all tags values, from “content” attribute, for quotes. We use ‘yield’ syntax to get the data. We can collect, and, transfer data to CSV, JSON and other file formats, with the ‘yield’ syntax. If we observe the code till here, it will crawl, and, extract data for the webpage. The code is as follows: Python3 # Import the required libraryimport scrapy # The Spider classclass GfgSpiitemsreadSpider(scrapy.Spider): # Name of the spider name = 'gfg_spiitemsread' # The domain allowed to scrape allowed_domains = ['quotes.toscrape.com/tag/reading'] # The URL to be scraped start_urls = ['http://quotes.toscrape.com/tag/reading/'] # Default callback function def parse(self, response): # Fetch all quotes tags quotes = response.xpath('//*[@class="quote"]') # Loop through the Quote selector elements # to get details of each for quote in quotes: # XPath expression to fetch text of the Quote title title = quote.xpath('.//*[@class="text"]/text()').extract_first() # XPath expression to fetch author of the Quote authors = quote.xpath('.//*[@itemprop="author"]/text()').extract() # XPath expression to fetch Tags of the Quote tags = quote.xpath('.//*[@itemprop="keywords"]/@content').extract() # Yield all elements yield {"Quote Text ": title, "Authors ": authors, "Tags ": tags} The crawl command is used to run the spider. Mention the spider name, in the crawl command. If we run, the above code, using the crawl command, then the output at the terminal would be: scrapy crawl filename Output: Quotes scraped as shown by the ‘yield’ statement Here, the yield statement, returns the data, in Python dictionary objects. Understanding Python Dictionary and Scrapy Item The data yielded above, are Python dictionary objects. Advantages of using them are – They are convenient, and, easy to handle key-value pair structures, when the data size is less. Use them, when no further processing, or, formatting on scraped data, is required. Use a dictionary, when the data you want to scrape, is complete and simple. For using Item objects we will make changes in the following files – The items.py file present Current spider class generated, gfg_spiitemsread.py file. Now, we will learn, the process of writing our Scrapy Item, for Quotes. To do so, we will follow, the steps as mentioned below – Open the items.py file. It is present, on the same level, as the ‘spiders’ folder. Mention the fields, we need to extract, in the file, as shown below: Python3 # Define here the models for your scraped# items# Import the required libraryimport scrapy # Define the fields for Scrapy item here# in classclass GfgSpiderreadingitemsItem(scrapy.Item): # Item key for Title of Quote quotetitle = scrapy.Field() # Item key for Author of Quote author = scrapy.Field() # Item key for Tags of Quote tags = scrapy.Field() As seen, in the file above, we have defined one scrapy Item called ‘GfgSpiderreadingitemsItem’. This class, is our blueprint, for all elements, we will scrape. It is going to persist, three fields namely, quote title, author name, and tags. We can now add, only the fields, we mention in the class. The Field() class, is an alias, to built-in dictionary class. It allows a way to define all field metadata, in one location. It does not provide, any extra attributes. Now modify the spider file, to store the values, in the item file’s class’s object, instead of yielding them directly. Please note, you need to import the Item class module, as seen in the code below. Python3 # Import the required libraryimport scrapy # Import the Item class with fields# mentioned in the items.py filefrom ..items import GfgSpiderreadingitemsItem class GfgSpiitemsreadSpider(scrapy.Spider): name = 'gfg_spiitemsread' allowed_domains = ['quotes.toscrape.com/tag/reading'] start_urls = ['http://quotes.toscrape.com/tag/reading/'] def parse(self, response): # Write XPath expression to loop through # all quotes quotes = response.xpath('//*[@class="quote"]') # Loop through all quotes for quote in quotes: # Create an object of Item class item = GfgSpiderreadingitemsItem() # XPath expression to fetch text of the # Quote title Store the title in the class # attribute in key-value pair item['quotetitle'] = quote.xpath( './/*[@class="text"]/text()').extract_first() # XPath expression to fetch author of the Quote # Store the author in the class attribute in # key-value pair item['author'] = quote.xpath( './/*[@itemprop="author"]/text()').extract() # XPath expression to fetch tags of the Quote title # Store the tags in the class attribute in key-value # pair item['tags'] = quote.xpath( './/*[@itemprop="keywords"]/@content').extract() # Yield the item object yield item As seen above, the keys mentioned, in the Item class, can now be used, to collect the data scraped, by XPath expressions. Make sure you mention, the exact key names, at both places. For example, use “item[‘author’]”, when ‘author’ is the key defined, in the items.py file. The items, yielded at the terminal, are as shown below : Data extracted from webpage using Scrapy Items rajeev0719singh simmytarika5 Picked Python-Scrapy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n19 Sep, 2021" }, { "code": null, "e": 24340, "s": 23901, "text": "In this article, we will scrape Quotes data using scrapy items, from the webpage https://quotes.toscrape.com/tag/reading/. The main objective of scraping, is to prepare structured data, from unstructured resources. Scrapy Items are wrappers around, the dictionary data structures. Code can be written, such that, the extracted data is returned, as Item objects, in the format of “key-value” pairs. Using Scrapy Items is beneficial when –" }, { "code": null, "e": 24411, "s": 24340, "text": "As the scraped data volume increases, they become irregular to handle." }, { "code": null, "e": 24503, "s": 24411, "text": "As your data gets complex, it is vulnerable to typos, and, at times may return faulty data." }, { "code": null, "e": 24600, "s": 24503, "text": "Formatting of data scraped, is easier, as Item objects, can be further passed to Item Pipelines." }, { "code": null, "e": 24662, "s": 24600, "text": "Cleansing the data, is easy, if we scrape the data, as Items." }, { "code": null, "e": 24731, "s": 24662, "text": "Validating data, handling missing data, is easier with Scrapy Items." }, { "code": null, "e": 24880, "s": 24731, "text": "Via the Item adapter library, Scrapy supports various Item Types. One can choose, the Item type, they want. Following, are the Item Types supported:" }, { "code": null, "e": 24975, "s": 24880, "text": "Dictionaries – Items can be written in form of dictionary objects. They are convenient to use." }, { "code": null, "e": 25212, "s": 24975, "text": "Item objects – They provide dictionary like API, wherein we need to declare, fields for the Item, needed. It consists of key-value pair, of Field objects used, while declaring the Item class. In this tutorial, we are using Item objects." }, { "code": null, "e": 25373, "s": 25212, "text": "Dataclass objects – They are used, when you need to store, the scraped values, in JSON or CSV files. Here we need to define, the datatype of each field, needed." }, { "code": null, "e": 25597, "s": 25373, "text": "attr.s – The attr.s allows, defining item classes, with field names, so that scraped data, can be imported, to different file formats. They work similar to Dataclass objects only that the attr package needs to be installed." }, { "code": null, "e": 25744, "s": 25597, "text": "The Scrapy library, requires a Python version, of 3.6 and above. Install the Scrapy library, by executing the following command, at the terminal –" }, { "code": null, "e": 25763, "s": 25744, "text": "pip install Scrapy" }, { "code": null, "e": 25900, "s": 25763, "text": "This command will install the Scrapy library, in the project environment. Now, we can create a Scrapy project, to write the Spider code." }, { "code": null, "e": 26176, "s": 25900, "text": "Scrapy has, an efficient command-line tool, also called the ‘Scrapy tool’. Commands accept a different set of arguments and options based on their purpose. To write the Spider code, we begin by creating, a Scrapy project, by executing the following command, at the terminal –" }, { "code": null, "e": 26211, "s": 26176, "text": "scrapy startproject <project_name>" }, { "code": null, "e": 26219, "s": 26211, "text": "Output:" }, { "code": null, "e": 26274, "s": 26219, "text": "Scrapy ‘startproject’ command to create Spider project" }, { "code": null, "e": 26445, "s": 26274, "text": "This should create a folder, in your current directory. It contains a ‘scrapy.cfg’, which is a configuration file, of the project. The folder structure is as shown below:" }, { "code": null, "e": 26494, "s": 26445, "text": "The folder structure of ‘gfg_spiderreadingitems’" }, { "code": null, "e": 26659, "s": 26494, "text": "The scrapy.cfg, is a project configuration file. The folder, that contains this file, is the root directory. The folder structure, of folder, created is as follows:" }, { "code": null, "e": 26718, "s": 26659, "text": "File ‘items.py’ inside the ‘gfg_spiderreadingitems’ folder" }, { "code": null, "e": 27016, "s": 26718, "text": "The folder, contains items.py,middlerwares.py and other settings files, along with the ‘spiders’ folder. The crawling code will be written, in a spider python file. We will alter, ‘items.py’ file, to mention, our data items, to be extracted. Keep the contents of ‘items.py’, as they are currently." }, { "code": null, "e": 27250, "s": 27016, "text": "The code for web scraping is written in the spider code file. To create the spider file, we will make use, of the ‘genspider’ command. Please note, that this command, is executed, at the same level, where scrapy.cfg file is present. " }, { "code": null, "e": 27380, "s": 27250, "text": "We are scraping, reading quotes present, on https://quotes.toscrape.com/tag/reading/ webpage. Hence, we will run the command as –" }, { "code": null, "e": 27427, "s": 27380, "text": "scrapy genspider spider_name url_to_be_scraped" }, { "code": null, "e": 27473, "s": 27427, "text": "Use ‘genspider’ command to create Spider file" }, { "code": null, "e": 27661, "s": 27473, "text": "The above command will create a spider file, “gfg_spiitemsread.py” in the ‘spiders’ folder. The spider name will also be,’gfg_spiitemsread’. The default code, for the same, is as follows:" }, { "code": null, "e": 27669, "s": 27661, "text": "Python3" }, { "code": "# Import the required librariesimport scrapy # Spider Class Created class GfgSpiitemsreadSpider(scrapy.Spider): # Name of the spider name = 'gfg_spiitemsread' # The domain to be scraped allowed_domains = ['quotes.toscrape.com/tag/reading/'] # The URLs from domain to scrape start_urls = ['http://quotes.toscrape.com/tag/reading//'] # Spider default callback function def parse(self, response): pass", "e": 28101, "s": 27669, "text": null }, { "code": null, "e": 28546, "s": 28101, "text": "We will scrape Quotes Title, Author and Tags from the webpage https://quotes.toscrape.com/tag/reading/. Scrapy provides us, with Selectors, to “select” parts of the webpage, desired. Selectors are CSS or XPath expressions, written to extract data, from the HTML documents. In this tutorial, we will make use of XPath expressions, to select the details we need. Let us understand, the steps for writing the selector syntax, in the spider code. " }, { "code": null, "e": 28766, "s": 28546, "text": "The default callback method, present in the spider class, responsible for, processing the response received, is the parse() method. We will write, selectors with XPath expressions, responsible for data extraction, here." }, { "code": null, "e": 28914, "s": 28766, "text": "Select the element to be extracted, on the webpage, say Right-Click, and choose the Inspect option. This will allow us, to view its CSS attributes." }, { "code": null, "e": 29132, "s": 28914, "text": "When we right-click on the first Quote and choose Inspect, we can see it has the CSS ‘class’ attribute “quote”. Similarly, all the quotes on the webpage, have CSS ‘class’ attribute as “quote”. It can be as seen below:" }, { "code": null, "e": 29194, "s": 29132, "text": "Right Click first quote, and, check its CSS “class” attribute" }, { "code": null, "e": 29266, "s": 29194, "text": "Based on this, the XPath expression, for the same, can be written as – " }, { "code": null, "e": 29397, "s": 29266, "text": "quotes = response.xpath(‘//*[@class=”quote”]’). This syntax will fetch all elements, having “quote”, as the CSS ‘class’ attribute." }, { "code": null, "e": 29939, "s": 29397, "text": "We will fetch the Quote Title, Author and Tags, of all the Quotes. Hence, we will write XPath expressions for extracting them, in a loop. For Quote Title, CSS ‘class’ attribute, is “text”. Hence, the XPath expression, for the same, would be – quote.xpath(‘.//*[@class=”text”]/text()’).extract_first(). The text() method, will extract the text, of the Quote title. The extract_first() method, will give the first matching value, with the CSS attribute “text”. The dot operator ‘.’ in the start, indicates extracting data, from a single quote." }, { "code": null, "e": 30239, "s": 29939, "text": "Similarly, CSS attributes, “class” and “itemprop”, for author element, is “author”. We can use, any of these, in the XPath expression. The syntax would be – quote.xpath(‘.//*[@itemprop=”author”]/text()’).extract(). This will extract, the Author name, where the CSS ‘itemprop’ attribute is ‘author’." }, { "code": null, "e": 30694, "s": 30239, "text": "The CSS attributes, “class” and “itemprop”, for tags element, is “keywords”. We can use, any of these, in the XPath expression. Since there are many tags, for any quote, looping through them, will be complex. Hence, we will extract the CSS attribute “content”, from every quote. The XPath expression for the same is – quote.xpath(‘.//*[@itemprop=”keywords”]/@content’).extract(). This will extract, all tags values, from “content” attribute, for quotes." }, { "code": null, "e": 30830, "s": 30694, "text": "We use ‘yield’ syntax to get the data. We can collect, and, transfer data to CSV, JSON and other file formats, with the ‘yield’ syntax." }, { "code": null, "e": 30914, "s": 30830, "text": "If we observe the code till here, it will crawl, and, extract data for the webpage." }, { "code": null, "e": 30938, "s": 30914, "text": "The code is as follows:" }, { "code": null, "e": 30946, "s": 30938, "text": "Python3" }, { "code": "# Import the required libraryimport scrapy # The Spider classclass GfgSpiitemsreadSpider(scrapy.Spider): # Name of the spider name = 'gfg_spiitemsread' # The domain allowed to scrape allowed_domains = ['quotes.toscrape.com/tag/reading'] # The URL to be scraped start_urls = ['http://quotes.toscrape.com/tag/reading/'] # Default callback function def parse(self, response): # Fetch all quotes tags quotes = response.xpath('//*[@class=\"quote\"]') # Loop through the Quote selector elements # to get details of each for quote in quotes: # XPath expression to fetch text of the Quote title title = quote.xpath('.//*[@class=\"text\"]/text()').extract_first() # XPath expression to fetch author of the Quote authors = quote.xpath('.//*[@itemprop=\"author\"]/text()').extract() # XPath expression to fetch Tags of the Quote tags = quote.xpath('.//*[@itemprop=\"keywords\"]/@content').extract() # Yield all elements yield {\"Quote Text \": title, \"Authors \": authors, \"Tags \": tags}", "e": 32144, "s": 30946, "text": null }, { "code": null, "e": 32330, "s": 32144, "text": "The crawl command is used to run the spider. Mention the spider name, in the crawl command. If we run, the above code, using the crawl command, then the output at the terminal would be:" }, { "code": null, "e": 32352, "s": 32330, "text": "scrapy crawl filename" }, { "code": null, "e": 32360, "s": 32352, "text": "Output:" }, { "code": null, "e": 32409, "s": 32360, "text": "Quotes scraped as shown by the ‘yield’ statement" }, { "code": null, "e": 32485, "s": 32409, "text": "Here, the yield statement, returns the data, in Python dictionary objects. " }, { "code": null, "e": 32533, "s": 32485, "text": "Understanding Python Dictionary and Scrapy Item" }, { "code": null, "e": 32620, "s": 32533, "text": "The data yielded above, are Python dictionary objects. Advantages of using them are –" }, { "code": null, "e": 32716, "s": 32620, "text": "They are convenient, and, easy to handle key-value pair structures, when the data size is less." }, { "code": null, "e": 32799, "s": 32716, "text": "Use them, when no further processing, or, formatting on scraped data, is required." }, { "code": null, "e": 32875, "s": 32799, "text": "Use a dictionary, when the data you want to scrape, is complete and simple." }, { "code": null, "e": 32944, "s": 32875, "text": "For using Item objects we will make changes in the following files –" }, { "code": null, "e": 32970, "s": 32944, "text": "The items.py file present" }, { "code": null, "e": 33028, "s": 32970, "text": "Current spider class generated, gfg_spiitemsread.py file." }, { "code": null, "e": 33157, "s": 33028, "text": "Now, we will learn, the process of writing our Scrapy Item, for Quotes. To do so, we will follow, the steps as mentioned below –" }, { "code": null, "e": 33310, "s": 33157, "text": "Open the items.py file. It is present, on the same level, as the ‘spiders’ folder. Mention the fields, we need to extract, in the file, as shown below:" }, { "code": null, "e": 33318, "s": 33310, "text": "Python3" }, { "code": "# Define here the models for your scraped# items# Import the required libraryimport scrapy # Define the fields for Scrapy item here# in classclass GfgSpiderreadingitemsItem(scrapy.Item): # Item key for Title of Quote quotetitle = scrapy.Field() # Item key for Author of Quote author = scrapy.Field() # Item key for Tags of Quote tags = scrapy.Field()", "e": 33702, "s": 33318, "text": null }, { "code": null, "e": 34001, "s": 33702, "text": "As seen, in the file above, we have defined one scrapy Item called ‘GfgSpiderreadingitemsItem’. This class, is our blueprint, for all elements, we will scrape. It is going to persist, three fields namely, quote title, author name, and tags. We can now add, only the fields, we mention in the class." }, { "code": null, "e": 34169, "s": 34001, "text": "The Field() class, is an alias, to built-in dictionary class. It allows a way to define all field metadata, in one location. It does not provide, any extra attributes." }, { "code": null, "e": 34371, "s": 34169, "text": "Now modify the spider file, to store the values, in the item file’s class’s object, instead of yielding them directly. Please note, you need to import the Item class module, as seen in the code below." }, { "code": null, "e": 34379, "s": 34371, "text": "Python3" }, { "code": "# Import the required libraryimport scrapy # Import the Item class with fields# mentioned in the items.py filefrom ..items import GfgSpiderreadingitemsItem class GfgSpiitemsreadSpider(scrapy.Spider): name = 'gfg_spiitemsread' allowed_domains = ['quotes.toscrape.com/tag/reading'] start_urls = ['http://quotes.toscrape.com/tag/reading/'] def parse(self, response): # Write XPath expression to loop through # all quotes quotes = response.xpath('//*[@class=\"quote\"]') # Loop through all quotes for quote in quotes: # Create an object of Item class item = GfgSpiderreadingitemsItem() # XPath expression to fetch text of the # Quote title Store the title in the class # attribute in key-value pair item['quotetitle'] = quote.xpath( './/*[@class=\"text\"]/text()').extract_first() # XPath expression to fetch author of the Quote # Store the author in the class attribute in # key-value pair item['author'] = quote.xpath( './/*[@itemprop=\"author\"]/text()').extract() # XPath expression to fetch tags of the Quote title # Store the tags in the class attribute in key-value # pair item['tags'] = quote.xpath( './/*[@itemprop=\"keywords\"]/@content').extract() # Yield the item object yield item", "e": 35912, "s": 34379, "text": null }, { "code": null, "e": 36188, "s": 35915, "text": "As seen above, the keys mentioned, in the Item class, can now be used, to collect the data scraped, by XPath expressions. Make sure you mention, the exact key names, at both places. For example, use “item[‘author’]”, when ‘author’ is the key defined, in the items.py file." }, { "code": null, "e": 36247, "s": 36190, "text": "The items, yielded at the terminal, are as shown below :" }, { "code": null, "e": 36296, "s": 36249, "text": "Data extracted from webpage using Scrapy Items" }, { "code": null, "e": 36314, "s": 36298, "text": "rajeev0719singh" }, { "code": null, "e": 36327, "s": 36314, "text": "simmytarika5" }, { "code": null, "e": 36334, "s": 36327, "text": "Picked" }, { "code": null, "e": 36348, "s": 36334, "text": "Python-Scrapy" }, { "code": null, "e": 36355, "s": 36348, "text": "Python" }, { "code": null, "e": 36453, "s": 36355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36462, "s": 36453, "text": "Comments" }, { "code": null, "e": 36475, "s": 36462, "text": "Old Comments" }, { "code": null, "e": 36496, "s": 36475, "text": "Python OOPs Concepts" }, { "code": null, "e": 36528, "s": 36496, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 36551, "s": 36528, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 36573, "s": 36551, "text": "Defaultdict in Python" }, { "code": null, "e": 36600, "s": 36573, "text": "Python Classes and Objects" }, { "code": null, "e": 36616, "s": 36600, "text": "Deque in Python" }, { "code": null, "e": 36658, "s": 36616, "text": "Check if element exists in list in Python" }, { "code": null, "e": 36714, "s": 36658, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 36759, "s": 36714, "text": "Python - Ways to remove duplicates from list" } ]
Git Ignore and .gitignore
When sharing your code with others, there are often files or parts of your project, you do not want to share. Examples log files temporary files hidden files personal files etc. Git can specify which files or parts of your project should be ignored by Git using a .gitignore file. Git will not track files and folders specified in .gitignore. However, the .gitignore file itself IS tracked by Git. To create a .gitignore file, go to the root of your local Git, and create it: touch .gitignore Now open the file using a text editor. We are just going to add two simple rules: Ignore any files with the .log extension Ignore everything in any directory named temp Now all .log files and anything in temp folders will be ignored by Git. Note: In this case, we use a single .gitignore which applies to the entire repository. It is also possible to have additional .gitignore files in subdirectories. These only apply to files or folders within that directory. Here are the general rules for matching patterns in .gitignore files: It is also possible to ignore files or folders but not show it in the distubuted .gitignore file. These kinds of ignores are specified in the .git/info/exclude file. It works the same way as .gitignore but are not shown to anyone else. In .gitignore add a line to ignore all .temp files: Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 110, "s": 0, "text": "When sharing your code with others, there are often files or parts of your project, you do not want to share." }, { "code": null, "e": 119, "s": 110, "text": "Examples" }, { "code": null, "e": 129, "s": 119, "text": "log files" }, { "code": null, "e": 145, "s": 129, "text": "temporary files" }, { "code": null, "e": 158, "s": 145, "text": "hidden files" }, { "code": null, "e": 173, "s": 158, "text": "personal files" }, { "code": null, "e": 178, "s": 173, "text": "etc." }, { "code": null, "e": 282, "s": 178, "text": "Git can specify which files or parts of your project should be \nignored by Git using a .gitignore file." }, { "code": null, "e": 400, "s": 282, "text": "Git will not track files and folders specified in .gitignore. However, the .gitignore \nfile itself IS tracked by Git." }, { "code": null, "e": 478, "s": 400, "text": "To create a .gitignore file, go to the root of your local Git, and create it:" }, { "code": null, "e": 495, "s": 478, "text": "touch .gitignore" }, { "code": null, "e": 534, "s": 495, "text": "Now open the file using a text editor." }, { "code": null, "e": 577, "s": 534, "text": "We are just going to add two simple rules:" }, { "code": null, "e": 618, "s": 577, "text": "Ignore any files with the .log extension" }, { "code": null, "e": 664, "s": 618, "text": "Ignore everything in any directory named temp" }, { "code": null, "e": 737, "s": 664, "text": "Now all .log files and anything in \ntemp folders will be ignored by Git." }, { "code": null, "e": 824, "s": 737, "text": "Note: In this case, we use a single .gitignore which applies to the entire repository." }, { "code": null, "e": 960, "s": 824, "text": " It is also possible to have additional .gitignore files in subdirectories. These only apply to files or folders within that directory." }, { "code": null, "e": 1032, "s": 960, "text": "Here are the general rules for matching patterns in .gitignore \nfiles: " }, { "code": null, "e": 1131, "s": 1032, "text": "It is also possible to ignore files or folders but not show it in the \ndistubuted .gitignore file." }, { "code": null, "e": 1270, "s": 1131, "text": "These kinds of ignores are specified in the \n.git/info/exclude file. It works the same way as\n.gitignore but are not shown to anyone else." }, { "code": null, "e": 1322, "s": 1270, "text": "In .gitignore add a line to ignore all .temp files:" }, { "code": null, "e": 1344, "s": 1324, "text": "\nStart the Exercise" }, { "code": null, "e": 1377, "s": 1344, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1419, "s": 1377, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1526, "s": 1419, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1545, "s": 1526, "text": "[email protected]" } ]
How to change the size of text on a label in Tkinter?
The label widget in Tkinter is used to display text and images in a Tkinter application. In order to change the properties of the label widget such as its font-property, color, background color, foreground color, etc., you can use the configure() method. If you want to change the size of the text in a Label widget, then you can configure the font=('font-family font-size style') property in the widget constructor. # Import the required libraries from tkinter import * import tkinter.font as tkFont # Create an instance of tkinter frame or window win=Tk() # Set the size of the tkinter window win.geometry("700x350") def font_style(): label.config(font=('Helvetica bold', 26)) # Create a Label label = Label(win, text="Click the Button to Change the Font Style.", font=('Times', 24)) label.pack() b1 = Button(win, text="Change the Label Size", command=font_style) b1.pack() win.mainloop() When you run the above code, it will display a window with a label widget and a button to change the font style of the label. Now, click the "Change the Label Size" button and it will modify the font style of the label.
[ { "code": null, "e": 1317, "s": 1062, "text": "The label widget in Tkinter is used to display text and images in a Tkinter application. In order to change the properties of the label widget such as its font-property, color, background color, foreground color, etc., you can use the configure() method." }, { "code": null, "e": 1479, "s": 1317, "text": "If you want to change the size of the text in a Label widget, then you can configure the font=('font-family font-size style') property in the widget constructor." }, { "code": null, "e": 1962, "s": 1479, "text": "# Import the required libraries\nfrom tkinter import *\nimport tkinter.font as tkFont\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\ndef font_style():\n label.config(font=('Helvetica bold', 26))\n\n# Create a Label\nlabel = Label(win, text=\"Click the Button to Change the Font Style.\", font=('Times', 24))\nlabel.pack()\n\nb1 = Button(win, text=\"Change the Label Size\", command=font_style)\nb1.pack()\n\nwin.mainloop()" }, { "code": null, "e": 2088, "s": 1962, "text": "When you run the above code, it will display a window with a label widget and a button to change the font style of the label." }, { "code": null, "e": 2182, "s": 2088, "text": "Now, click the \"Change the Label Size\" button and it will modify the font style of the label." } ]
Sorting data frames in pandas. How to sort data frames quickly and... | by Magdalena Konkiewicz | Towards Data Science
Many beginner data scientists try to sort their data frames by writing complicated functions. This is not the most efficient or easiest way to do it. Do not reinvent the wheel and use sort_values() function provided by pandas package. Let’s have a look at the real-life example and how to use sort_values() function in your code. Load data set We will use a python dictionary to create some fake client data and we will load this data to pandas data frame. We will keep it simple so we will have just four columns: name, country, age and latest date active. The data set is simple enough but we will give us a good overview of how we can sort a data frame in several different ways. import pandas as pdimport numpy as npclient_dictionary = {'name': ['Michael', 'Ana', 'Sean'], 'country': ['UK', 'UK', 'USA'], 'age': [10, 51, 13], 'latest date active': ['07-05-2019', '23-12-2019', '03-04-2016']}df = pd.DataFrame(client_dictionary)df.head() Just above, we have our client data frame. It has only three clients but it will be enough to showcase all different sorting possibilities. Sort by alphabetical order Let’ start with sorting a data frame by names in alphabetical order. We will use panads sort_values() function and specify by which column name we want to sort by using a parameter called ‘by’ : df.sort_values(by='name') We can see that a data frame is now sorted according to name column in alphabetical order. We can reverse the ordering by using ascending=False as our function parameter: df.sort_values(by='name', ascending=False) Sort by number Let’s try to do the same but now sort by age. The code looks exactly the same except we change the column name that we will use for sorting: df.sort_values(by='age') Sort by dates Again the same line of code will work for dates! The only thing we need to ensure is that our date is recognized as a date type and not as a string. We will use astype() method to do that and then apply the sorting function: df['latest date active'] = df['latest date active'].astype('datetime64[ns]')df.sort_values(by='latest date active') Sort by multiple columns Sort values function can work with multiple columns. It will first sort the data frame according to the first element in the column list. If there are values that are not sortable using the first column it will proceed to the next column in the list. Let’s look at the example when we first sort by country and then sort by name: df.sort_values(by=['country','name']) So here we can see that our entries are sorted by country. All UK entries are above USA entries and then they are even further sorted according to its name column. Using inplace parameter Last but not least if you want your current data frame to save the result of the sorting you remember to use inplace parameter and set it to True: df.sort_values(by=['country','name'], inplace=True) Conclusion You can efficiently sort your data frames using single lines of code. The magic is done using sort_values function from pandas package. If you get to know how to use parameters as outlined in this overview you will be able to sort any data frame according to your needs. I hope you will find it useful and happy sorting! Originally published at aboutdatablog.com: Sorting data frames in pandas, on October 16, 2019. PS: I am writing articles that explain basic Data Science concepts in a simple and comprehensible manner on Medium and aboutdatablog.com. You can subscribe to my email list to get notified every time I write a new article. And if you are not a Medium member yet you can join here. Below there are some other posts you may enjoy:
[ { "code": null, "e": 502, "s": 172, "text": "Many beginner data scientists try to sort their data frames by writing complicated functions. This is not the most efficient or easiest way to do it. Do not reinvent the wheel and use sort_values() function provided by pandas package. Let’s have a look at the real-life example and how to use sort_values() function in your code." }, { "code": null, "e": 516, "s": 502, "text": "Load data set" }, { "code": null, "e": 855, "s": 516, "text": "We will use a python dictionary to create some fake client data and we will load this data to pandas data frame. We will keep it simple so we will have just four columns: name, country, age and latest date active. The data set is simple enough but we will give us a good overview of how we can sort a data frame in several different ways." }, { "code": null, "e": 1175, "s": 855, "text": "import pandas as pdimport numpy as npclient_dictionary = {'name': ['Michael', 'Ana', 'Sean'], 'country': ['UK', 'UK', 'USA'], 'age': [10, 51, 13], 'latest date active': ['07-05-2019', '23-12-2019', '03-04-2016']}df = pd.DataFrame(client_dictionary)df.head()" }, { "code": null, "e": 1315, "s": 1175, "text": "Just above, we have our client data frame. It has only three clients but it will be enough to showcase all different sorting possibilities." }, { "code": null, "e": 1342, "s": 1315, "text": "Sort by alphabetical order" }, { "code": null, "e": 1537, "s": 1342, "text": "Let’ start with sorting a data frame by names in alphabetical order. We will use panads sort_values() function and specify by which column name we want to sort by using a parameter called ‘by’ :" }, { "code": null, "e": 1563, "s": 1537, "text": "df.sort_values(by='name')" }, { "code": null, "e": 1654, "s": 1563, "text": "We can see that a data frame is now sorted according to name column in alphabetical order." }, { "code": null, "e": 1734, "s": 1654, "text": "We can reverse the ordering by using ascending=False as our function parameter:" }, { "code": null, "e": 1777, "s": 1734, "text": "df.sort_values(by='name', ascending=False)" }, { "code": null, "e": 1792, "s": 1777, "text": "Sort by number" }, { "code": null, "e": 1933, "s": 1792, "text": "Let’s try to do the same but now sort by age. The code looks exactly the same except we change the column name that we will use for sorting:" }, { "code": null, "e": 1958, "s": 1933, "text": "df.sort_values(by='age')" }, { "code": null, "e": 1972, "s": 1958, "text": "Sort by dates" }, { "code": null, "e": 2197, "s": 1972, "text": "Again the same line of code will work for dates! The only thing we need to ensure is that our date is recognized as a date type and not as a string. We will use astype() method to do that and then apply the sorting function:" }, { "code": null, "e": 2313, "s": 2197, "text": "df['latest date active'] = df['latest date active'].astype('datetime64[ns]')df.sort_values(by='latest date active')" }, { "code": null, "e": 2338, "s": 2313, "text": "Sort by multiple columns" }, { "code": null, "e": 2668, "s": 2338, "text": "Sort values function can work with multiple columns. It will first sort the data frame according to the first element in the column list. If there are values that are not sortable using the first column it will proceed to the next column in the list. Let’s look at the example when we first sort by country and then sort by name:" }, { "code": null, "e": 2706, "s": 2668, "text": "df.sort_values(by=['country','name'])" }, { "code": null, "e": 2870, "s": 2706, "text": "So here we can see that our entries are sorted by country. All UK entries are above USA entries and then they are even further sorted according to its name column." }, { "code": null, "e": 2894, "s": 2870, "text": "Using inplace parameter" }, { "code": null, "e": 3041, "s": 2894, "text": "Last but not least if you want your current data frame to save the result of the sorting you remember to use inplace parameter and set it to True:" }, { "code": null, "e": 3093, "s": 3041, "text": "df.sort_values(by=['country','name'], inplace=True)" }, { "code": null, "e": 3104, "s": 3093, "text": "Conclusion" }, { "code": null, "e": 3425, "s": 3104, "text": "You can efficiently sort your data frames using single lines of code. The magic is done using sort_values function from pandas package. If you get to know how to use parameters as outlined in this overview you will be able to sort any data frame according to your needs. I hope you will find it useful and happy sorting!" }, { "code": null, "e": 3520, "s": 3425, "text": "Originally published at aboutdatablog.com: Sorting data frames in pandas, on October 16, 2019." }, { "code": null, "e": 3801, "s": 3520, "text": "PS: I am writing articles that explain basic Data Science concepts in a simple and comprehensible manner on Medium and aboutdatablog.com. You can subscribe to my email list to get notified every time I write a new article. And if you are not a Medium member yet you can join here." } ]
Python - Advanced Linked list
We have already seen Linked List in earlier chapter in which it is possible only to travel forward. In this chapter we see another type of linked list in which it is possible to travel both forward and backward. Such a linked list is called Doubly Linked List. Following is the features of doubly linked list. Doubly Linked List contains a link element called first and last. Doubly Linked List contains a link element called first and last. Each link carries a data field(s) and two link fields called next and prev. Each link carries a data field(s) and two link fields called next and prev. Each link is linked with its next link using its next link. Each link is linked with its next link using its next link. Each link is linked with its previous link using its previous link. Each link is linked with its previous link using its previous link. The last link carries a link as null to mark the end of the list. The last link carries a link as null to mark the end of the list. We create a Doubly Linked list by using the Node class. Now we use the same approach as used in the Singly Linked List but the head and next pointers will be used for proper assignation to create two links in each of the nodes in addition to the data present in the node. class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class doubly_linked_list: def __init__(self): self.head = None # Adding data elements def push(self, NewVal): NewNode = Node(NewVal) NewNode.next = self.head if self.head is not None: self.head.prev = NewNode self.head = NewNode # Print the Doubly Linked list def listprint(self, node): while (node is not None): print(node.data), last = node node = node.next dllist = doubly_linked_list() dllist.push(12) dllist.push(8) dllist.push(62) dllist.listprint(dllist.head) When the above code is executed, it produces the following result − 62 8 12 Here, we are going to see how to insert a node to the Doubly Link List using the following program. The program uses a method named insert which inserts the new node at the third position from the head of the doubly linked list. # Create the Node class class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Create the doubly linked list class doubly_linked_list: def __init__(self): self.head = None # Define the push method to add elements def push(self, NewVal): NewNode = Node(NewVal) NewNode.next = self.head if self.head is not None: self.head.prev = NewNode self.head = NewNode # Define the insert method to insert the element def insert(self, prev_node, NewVal): if prev_node is None: return NewNode = Node(NewVal) NewNode.next = prev_node.next prev_node.next = NewNode NewNode.prev = prev_node if NewNode.next is not None: NewNode.next.prev = NewNode # Define the method to print the linked list def listprint(self, node): while (node is not None): print(node.data), last = node node = node.next dllist = doubly_linked_list() dllist.push(12) dllist.push(8) dllist.push(62) dllist.insert(dllist.head.next, 13) dllist.listprint(dllist.head) When the above code is executed, it produces the following result − 62 8 13 12 Appending to a doubly linked list will add the element at the end. # Create the node class class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Create the doubly linked list class class doubly_linked_list: def __init__(self): self.head = None # Define the push method to add elements at the begining def push(self, NewVal): NewNode = Node(NewVal) NewNode.next = self.head if self.head is not None: self.head.prev = NewNode self.head = NewNode # Define the append method to add elements at the end def append(self, NewVal): NewNode = Node(NewVal) NewNode.next = None if self.head is None: NewNode.prev = None self.head = NewNode return last = self.head while (last.next is not None): last = last.next last.next = NewNode NewNode.prev = last return # Define the method to print def listprint(self, node): while (node is not None): print(node.data), last = node node = node.next dllist = doubly_linked_list() dllist.push(12) dllist.append(9) dllist.push(8) dllist.push(62) dllist.append(45) dllist.listprint(dllist.head) When the above code is executed, it produces the following result − 62 8 12 9 45 Please note the position of the elements 9 and 45 for the append operation. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2638, "s": 2327, "text": "We have already seen Linked List in earlier chapter in which it is possible only to travel forward. In this chapter we see another type of linked list in which it is possible to travel both forward and backward. Such a linked list is called Doubly Linked List. Following is the features of doubly linked list." }, { "code": null, "e": 2704, "s": 2638, "text": "Doubly Linked List contains a link element called first and last." }, { "code": null, "e": 2770, "s": 2704, "text": "Doubly Linked List contains a link element called first and last." }, { "code": null, "e": 2846, "s": 2770, "text": "Each link carries a data field(s) and two link fields called next and prev." }, { "code": null, "e": 2922, "s": 2846, "text": "Each link carries a data field(s) and two link fields called next and prev." }, { "code": null, "e": 2982, "s": 2922, "text": "Each link is linked with its next link using its next link." }, { "code": null, "e": 3042, "s": 2982, "text": "Each link is linked with its next link using its next link." }, { "code": null, "e": 3110, "s": 3042, "text": "Each link is linked with its previous link using its previous link." }, { "code": null, "e": 3178, "s": 3110, "text": "Each link is linked with its previous link using its previous link." }, { "code": null, "e": 3244, "s": 3178, "text": "The last link carries a link as null to mark the end of the list." }, { "code": null, "e": 3310, "s": 3244, "text": "The last link carries a link as null to mark the end of the list." }, { "code": null, "e": 3582, "s": 3310, "text": "We create a Doubly Linked list by using the Node class. Now we use the same approach as used in the Singly Linked List but the head and next pointers will be used for proper assignation to create two links in each of the nodes in addition to the data present in the node." }, { "code": null, "e": 4248, "s": 3582, "text": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n\nclass doubly_linked_list:\n def __init__(self):\n self.head = None\n\n# Adding data elements\t\t\n def push(self, NewVal):\n NewNode = Node(NewVal)\n NewNode.next = self.head\n if self.head is not None:\n self.head.prev = NewNode\n self.head = NewNode\n\n# Print the Doubly Linked list\t\t\n def listprint(self, node):\n while (node is not None):\n print(node.data),\n last = node\n node = node.next\n\ndllist = doubly_linked_list()\ndllist.push(12)\ndllist.push(8)\ndllist.push(62)\ndllist.listprint(dllist.head)" }, { "code": null, "e": 4316, "s": 4248, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 4325, "s": 4316, "text": "62 8 12\n" }, { "code": null, "e": 4554, "s": 4325, "text": "Here, we are going to see how to insert a node to the Doubly Link List using the following program. The program uses a method named insert which inserts the new node at the third position from the head of the doubly linked list." }, { "code": null, "e": 5678, "s": 4554, "text": "# Create the Node class\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n\n# Create the doubly linked list\nclass doubly_linked_list:\n def __init__(self):\n self.head = None\n\n# Define the push method to add elements\t\t\n def push(self, NewVal):\n NewNode = Node(NewVal)\n NewNode.next = self.head\n if self.head is not None:\n self.head.prev = NewNode\n self.head = NewNode\n\n# Define the insert method to insert the element\t\t\n def insert(self, prev_node, NewVal):\n if prev_node is None:\n return\n NewNode = Node(NewVal)\n NewNode.next = prev_node.next\n prev_node.next = NewNode\n NewNode.prev = prev_node\n if NewNode.next is not None:\n NewNode.next.prev = NewNode\n\n# Define the method to print the linked list \n def listprint(self, node):\n while (node is not None):\n print(node.data),\n last = node\n node = node.next\n\ndllist = doubly_linked_list()\ndllist.push(12)\ndllist.push(8)\ndllist.push(62)\ndllist.insert(dllist.head.next, 13)\ndllist.listprint(dllist.head)" }, { "code": null, "e": 5746, "s": 5678, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 5761, "s": 5746, "text": "62 8 13 12\n" }, { "code": null, "e": 5828, "s": 5761, "text": "Appending to a doubly linked list will add the element at the end." }, { "code": null, "e": 7010, "s": 5828, "text": "# Create the node class\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n# Create the doubly linked list class\nclass doubly_linked_list:\n def __init__(self):\n self.head = None\n\n# Define the push method to add elements at the begining\n def push(self, NewVal):\n NewNode = Node(NewVal)\n NewNode.next = self.head\n if self.head is not None:\n self.head.prev = NewNode\n self.head = NewNode\n\n# Define the append method to add elements at the end\n def append(self, NewVal):\n NewNode = Node(NewVal)\n NewNode.next = None\n if self.head is None:\n NewNode.prev = None\n self.head = NewNode\n return\n last = self.head\n while (last.next is not None):\n last = last.next\n last.next = NewNode\n NewNode.prev = last\n return\n\n# Define the method to print\n def listprint(self, node):\n while (node is not None):\n print(node.data),\n last = node\n node = node.next\n\ndllist = doubly_linked_list()\ndllist.push(12)\ndllist.append(9)\ndllist.push(8)\ndllist.push(62)\ndllist.append(45)\ndllist.listprint(dllist.head)" }, { "code": null, "e": 7078, "s": 7010, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 7092, "s": 7078, "text": "62 8 12 9 45\n" }, { "code": null, "e": 7168, "s": 7092, "text": "Please note the position of the elements 9 and 45 for the append operation." }, { "code": null, "e": 7205, "s": 7168, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7221, "s": 7205, "text": " Malhar Lathkar" }, { "code": null, "e": 7254, "s": 7221, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 7273, "s": 7254, "text": " Arnab Chakraborty" }, { "code": null, "e": 7308, "s": 7273, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 7330, "s": 7308, "text": " In28Minutes Official" }, { "code": null, "e": 7364, "s": 7330, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 7392, "s": 7364, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7427, "s": 7392, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 7441, "s": 7427, "text": " Lets Kode It" }, { "code": null, "e": 7474, "s": 7441, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 7491, "s": 7474, "text": " Abhilash Nelson" }, { "code": null, "e": 7498, "s": 7491, "text": " Print" }, { "code": null, "e": 7509, "s": 7498, "text": " Add Notes" } ]
Why is it faster to process sorted array than an unsorted array ? - GeeksforGeeks
11 Jul, 2017 Here is a C++ code that illustrates that sorting the data miraculously makes the code faster than the unsorted version. Let’s try out a sample C++ program to understand the problem statement better. // CPP program to demonstrate processing// time of sorted and unsorted array#include <iostream>#include <algorithm>#include <ctime>using namespace std; const int N = 100001; int main(){ int arr[N]; // Assign random values to array for (int i=0; i<N; i++) arr[i] = rand()%N; // for loop for unsorted array int count = 0; double start = clock(); for (int i=0; i<N; i++) if (arr[i] < N/2) count++; double end = clock(); cout << "Time for unsorted array :: " << ((end - start)/CLOCKS_PER_SEC) << endl; sort(arr, arr+N); // for loop for sorted array count = 0; start = clock(); for (int i=0; i<N; i++) if (arr[i] < N/2) count++; end = clock(); cout << "Time for sorted array :: " << ((end - start)/CLOCKS_PER_SEC) << endl; return 0;} Output : Execution 1: Time for unsorted array :: 0.00108 Time for sorted array :: 0.00053 Execution 2: Time for unsorted array :: 0.001101 Time for sorted array :: 0.000593 Execution 3: Time for unsorted array :: 0.0011 Time for sorted array :: 0.000418 Observe that time taken for processing a sorted array is less as compared to unsorted array. The reason for this optimisation for sorted array is branch prediction. What is branch prediction ?In computer architecture, branch prediction means determining whether a conditional branch(jump) in the instruction flow of a program is likely to be taken or not.All the pipelined processors do branch prediction in some form, because they must guess the address of the next instruction to fetch before the current instruction has been executed. How branch prediction in applicable on above case ? The if condition checks that arr[i] < 5000, but if you observe in case of sorted array, after passing the number 5000 the condition is always false, and before that it is always true, compiler optimises the code here and skips the if condition which is referred as branch prediction. Case 1 : Sorted array T = if condition true F = if condition false arr[] = {0,1,2,3,4,5,6, .... , 4999,5000,5001, ... , 100000} {T,T,T,T,T,T,T, .... , T, F, F, ... , F } We can observe that it is very easy to predict the branch in sorted array, as the sequence is TTTTTTTTTTTT.........FFFFFFFFFFFFF Case 2 : Unsorted array T = if condition true F = if condition false arr[] = {5,0,5000,10000,17,13, ... , 3,21000,10} {T,T,F, F, T, T, ... , T, F, T} It is very difficult to predict that if statement will be false or true, hence branch prediction don’t play any significant role here. Branch prediction works on the pattern the algorithm is following or basically the history, how it got executed in previous steps. If the guess is correct, then CPU continue executing and if it goes wrong, then CPU need to flush the pipeline and roll back to the branch and restart from beginning. In case compiler is not able to utilise branch prediction as a tool for improving performance, programmer can implement his own hacks to improve performance. References : Branch_prediction StackOverflow Pipelining in computing This article is contributed by Mandeep Singh. 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. Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Building Heap from Array Move all negative numbers to beginning and positive to end with constant extra space
[ { "code": null, "e": 24820, "s": 24792, "text": "\n11 Jul, 2017" }, { "code": null, "e": 25019, "s": 24820, "text": "Here is a C++ code that illustrates that sorting the data miraculously makes the code faster than the unsorted version. Let’s try out a sample C++ program to understand the problem statement better." }, { "code": "// CPP program to demonstrate processing// time of sorted and unsorted array#include <iostream>#include <algorithm>#include <ctime>using namespace std; const int N = 100001; int main(){ int arr[N]; // Assign random values to array for (int i=0; i<N; i++) arr[i] = rand()%N; // for loop for unsorted array int count = 0; double start = clock(); for (int i=0; i<N; i++) if (arr[i] < N/2) count++; double end = clock(); cout << \"Time for unsorted array :: \" << ((end - start)/CLOCKS_PER_SEC) << endl; sort(arr, arr+N); // for loop for sorted array count = 0; start = clock(); for (int i=0; i<N; i++) if (arr[i] < N/2) count++; end = clock(); cout << \"Time for sorted array :: \" << ((end - start)/CLOCKS_PER_SEC) << endl; return 0;}", "e": 25890, "s": 25019, "text": null }, { "code": null, "e": 25899, "s": 25890, "text": "Output :" }, { "code": null, "e": 26147, "s": 25899, "text": "Execution 1:\nTime for unsorted array :: 0.00108\nTime for sorted array :: 0.00053\n\nExecution 2:\nTime for unsorted array :: 0.001101\nTime for sorted array :: 0.000593\n\nExecution 3:\nTime for unsorted array :: 0.0011\nTime for sorted array :: 0.000418\n" }, { "code": null, "e": 26312, "s": 26147, "text": "Observe that time taken for processing a sorted array is less as compared to unsorted array. The reason for this optimisation for sorted array is branch prediction." }, { "code": null, "e": 26685, "s": 26312, "text": "What is branch prediction ?In computer architecture, branch prediction means determining whether a conditional branch(jump) in the instruction flow of a program is likely to be taken or not.All the pipelined processors do branch prediction in some form, because they must guess the address of the next instruction to fetch before the current instruction has been executed." }, { "code": null, "e": 26737, "s": 26685, "text": "How branch prediction in applicable on above case ?" }, { "code": null, "e": 27021, "s": 26737, "text": "The if condition checks that arr[i] < 5000, but if you observe in case of sorted array, after passing the number 5000 the condition is always false, and before that it is always true, compiler optimises the code here and skips the if condition which is referred as branch prediction." }, { "code": null, "e": 27043, "s": 27021, "text": "Case 1 : Sorted array" }, { "code": null, "e": 27219, "s": 27043, "text": "\tT = if condition true\n\tF = if condition false\n\tarr[] = {0,1,2,3,4,5,6, .... , 4999,5000,5001, ... , 100000}\n {T,T,T,T,T,T,T, .... , T, F, F, ... , F }\t\n" }, { "code": null, "e": 27348, "s": 27219, "text": "We can observe that it is very easy to predict the branch in sorted array, as the sequence is TTTTTTTTTTTT.........FFFFFFFFFFFFF" }, { "code": null, "e": 27372, "s": 27348, "text": "Case 2 : Unsorted array" }, { "code": null, "e": 27520, "s": 27372, "text": "\tT = if condition true\n\tF = if condition false\n\tarr[] = {5,0,5000,10000,17,13, ... , 3,21000,10}\n\t {T,T,F, F, T, T, ... , T, F, T}\n" }, { "code": null, "e": 27655, "s": 27520, "text": "It is very difficult to predict that if statement will be false or true, hence branch prediction don’t play any significant role here." }, { "code": null, "e": 27953, "s": 27655, "text": "Branch prediction works on the pattern the algorithm is following or basically the history, how it got executed in previous steps. If the guess is correct, then CPU continue executing and if it goes wrong, then CPU need to flush the pipeline and roll back to the branch and restart from beginning." }, { "code": null, "e": 28111, "s": 27953, "text": "In case compiler is not able to utilise branch prediction as a tool for improving performance, programmer can implement his own hacks to improve performance." }, { "code": null, "e": 28124, "s": 28111, "text": "References :" }, { "code": null, "e": 28142, "s": 28124, "text": "Branch_prediction" }, { "code": null, "e": 28156, "s": 28142, "text": "StackOverflow" }, { "code": null, "e": 28180, "s": 28156, "text": "Pipelining in computing" }, { "code": null, "e": 28481, "s": 28180, "text": "This article is contributed by Mandeep Singh. 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": 28606, "s": 28481, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28613, "s": 28606, "text": "Arrays" }, { "code": null, "e": 28621, "s": 28613, "text": "Sorting" }, { "code": null, "e": 28628, "s": 28621, "text": "Arrays" }, { "code": null, "e": 28636, "s": 28628, "text": "Sorting" }, { "code": null, "e": 28734, "s": 28636, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28759, "s": 28734, "text": "Window Sliding Technique" }, { "code": null, "e": 28779, "s": 28759, "text": "Trapping Rain Water" }, { "code": null, "e": 28817, "s": 28779, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 28842, "s": 28817, "text": "Building Heap from Array" } ]
JavaScript Number - NaN
Unquoted literal constant NaN is a special value representing Not-a-Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number. Note − Use the isNaN() global function to see if a value is an NaN value. The syntax to use NaN is − var val = Number.NaN; Try the following example to learn how to use NaN. <html> <head> <script type = "text/javascript"> <!-- function showValue() { var dayOfMonth = 50; if (dayOfMonth < 1 || dayOfMonth > 31) { dayOfMonth = Number.NaN alert("Day of Month must be between 1 and 31.") } Document.write("Value of dayOfMonth : " + dayOfMonth ); } //--> </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = "showValue();" /> </form> </body> </html> Click the following to see the result: 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": 2706, "s": 2466, "text": "Unquoted literal constant NaN is a special value representing Not-a-Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number." }, { "code": null, "e": 2780, "s": 2706, "text": "Note − Use the isNaN() global function to see if a value is an NaN value." }, { "code": null, "e": 2807, "s": 2780, "text": "The syntax to use NaN is −" }, { "code": null, "e": 2830, "s": 2807, "text": "var val = Number.NaN;\n" }, { "code": null, "e": 2881, "s": 2830, "text": "Try the following example to learn how to use NaN." }, { "code": null, "e": 3562, "s": 2881, "text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function showValue() {\n var dayOfMonth = 50;\n \n if (dayOfMonth < 1 || dayOfMonth > 31) {\n dayOfMonth = Number.NaN\n alert(\"Day of Month must be between 1 and 31.\")\n }\n Document.write(\"Value of dayOfMonth : \" + dayOfMonth );\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following to see the result:</p> \n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"showValue();\" />\n </form> \n </body>\n</html>" }, { "code": null, "e": 3601, "s": 3562, "text": "Click the following to see the result:" }, { "code": null, "e": 3636, "s": 3601, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3650, "s": 3636, "text": " Anadi Sharma" }, { "code": null, "e": 3684, "s": 3650, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3698, "s": 3684, "text": " Lets Kode It" }, { "code": null, "e": 3733, "s": 3698, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3750, "s": 3733, "text": " Frahaan Hussain" }, { "code": null, "e": 3785, "s": 3750, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3802, "s": 3785, "text": " Frahaan Hussain" }, { "code": null, "e": 3835, "s": 3802, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3863, "s": 3835, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3897, "s": 3863, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3925, "s": 3897, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3932, "s": 3925, "text": " Print" }, { "code": null, "e": 3943, "s": 3932, "text": " Add Notes" } ]
3 Ways to Get Notified with Python | by Khuyen Tran | Towards Data Science
As a data scientist or programmer, it might take you a lot of time to process your data and train your model. It is inefficient to constantly check the training on your screen, especially when the training can take hours or days. Are there ways that you can get a notification when your training is done with Python? Yes, you can get notified by: noise email slack Each of these methods just takes you 2 or 3 more lines of codes. Let’s find out how to create your own system to get notified using these methods. If you are doing something close to your computer while waiting for the training to be done, simply making a noise when the training is complete is a good enough solution. I found this code snippet on StackOverflow. The function below creates beep noise with specified duration and frequency You need to install sox to run the code below On Linux, run sudo apt install sox On Mac, run sudo port install sox Simply insert function make_noise() at the bottom of your training code Once the training finishes running, the function make_noise() will be executed and there will be a noise! If you are doing something else, you can stop what you are doing and check on your training results. Making noise is a great way to get notified, but what if you are not close to your computer when the training is complete? Plus you might want to let your teammates know when the training is complete. That is when sending an email comes in handy. There is a Python library called knockknock that allows you to get a notification when your training is complete or when it crashes during the process. All it takes to get a notification is two additional lines of code. To install knock-knock, type pip install knockknock You need a Gmail email address to send an email with knock-knock. Make sure to turn on the less secure apps feature for knockknock to use your Gmail account. It is ideal to create another Gmail account to send a notification in order to secure your main Gmail account. To send an email, simply insert a decorator @email_sender() above your training function You can send an email to one person or a list of people with recipient_emails=[“[email protected]”, “[email protected]”] . If sender_email is not specified, then the first email in recipient_emails will be used as the sender's email. Now when you run your script python yourscript.py You will receive an email when the training is complete. Try this on your existing script and check your email! Slack is a common platform for many teams to discuss their work and share their progress. If you are using Slack, you might wish to send it to a channel in your company, for example, channel #developer, to notify your developer team when the training is finished. Luckily, knock-knock also allows you to send a notification when the training finishes! To send a notification to your Slack, start with enabling and creating an incoming webhook. Then simply specify the webhook URL of your slack room with webhook_url and the channel to notify with channel. In case you want to tag your teammate, adduser_mentions=[“your_slack_id”, “your_teammate_slack_id”] to @slack_sender Now when you run your script, a message should be sent to your slack channel when the code finishes executing! Congratulations! You have just learned how to get notified by making noise, sending a notification to your email, or Slack channel. Now you don’t need to constantly check your computer to find out whether the training has complete anymore! You and your teammates can work on other projects while waiting for the training to finish. Check knock-knock if you want to use Telegram messenger, text message, or other ways to get notifications. The source code for this article can be found here: github.com I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 488, "s": 171, "text": "As a data scientist or programmer, it might take you a lot of time to process your data and train your model. It is inefficient to constantly check the training on your screen, especially when the training can take hours or days. Are there ways that you can get a notification when your training is done with Python?" }, { "code": null, "e": 518, "s": 488, "text": "Yes, you can get notified by:" }, { "code": null, "e": 524, "s": 518, "text": "noise" }, { "code": null, "e": 530, "s": 524, "text": "email" }, { "code": null, "e": 536, "s": 530, "text": "slack" }, { "code": null, "e": 683, "s": 536, "text": "Each of these methods just takes you 2 or 3 more lines of codes. Let’s find out how to create your own system to get notified using these methods." }, { "code": null, "e": 855, "s": 683, "text": "If you are doing something close to your computer while waiting for the training to be done, simply making a noise when the training is complete is a good enough solution." }, { "code": null, "e": 975, "s": 855, "text": "I found this code snippet on StackOverflow. The function below creates beep noise with specified duration and frequency" }, { "code": null, "e": 1021, "s": 975, "text": "You need to install sox to run the code below" }, { "code": null, "e": 1035, "s": 1021, "text": "On Linux, run" }, { "code": null, "e": 1056, "s": 1035, "text": "sudo apt install sox" }, { "code": null, "e": 1068, "s": 1056, "text": "On Mac, run" }, { "code": null, "e": 1090, "s": 1068, "text": "sudo port install sox" }, { "code": null, "e": 1162, "s": 1090, "text": "Simply insert function make_noise() at the bottom of your training code" }, { "code": null, "e": 1369, "s": 1162, "text": "Once the training finishes running, the function make_noise() will be executed and there will be a noise! If you are doing something else, you can stop what you are doing and check on your training results." }, { "code": null, "e": 1616, "s": 1369, "text": "Making noise is a great way to get notified, but what if you are not close to your computer when the training is complete? Plus you might want to let your teammates know when the training is complete. That is when sending an email comes in handy." }, { "code": null, "e": 1836, "s": 1616, "text": "There is a Python library called knockknock that allows you to get a notification when your training is complete or when it crashes during the process. All it takes to get a notification is two additional lines of code." }, { "code": null, "e": 1865, "s": 1836, "text": "To install knock-knock, type" }, { "code": null, "e": 1888, "s": 1865, "text": "pip install knockknock" }, { "code": null, "e": 2157, "s": 1888, "text": "You need a Gmail email address to send an email with knock-knock. Make sure to turn on the less secure apps feature for knockknock to use your Gmail account. It is ideal to create another Gmail account to send a notification in order to secure your main Gmail account." }, { "code": null, "e": 2246, "s": 2157, "text": "To send an email, simply insert a decorator @email_sender() above your training function" }, { "code": null, "e": 2385, "s": 2246, "text": "You can send an email to one person or a list of people with recipient_emails=[“[email protected]”, “[email protected]”] ." }, { "code": null, "e": 2496, "s": 2385, "text": "If sender_email is not specified, then the first email in recipient_emails will be used as the sender's email." }, { "code": null, "e": 2525, "s": 2496, "text": "Now when you run your script" }, { "code": null, "e": 2546, "s": 2525, "text": "python yourscript.py" }, { "code": null, "e": 2603, "s": 2546, "text": "You will receive an email when the training is complete." }, { "code": null, "e": 2658, "s": 2603, "text": "Try this on your existing script and check your email!" }, { "code": null, "e": 3010, "s": 2658, "text": "Slack is a common platform for many teams to discuss their work and share their progress. If you are using Slack, you might wish to send it to a channel in your company, for example, channel #developer, to notify your developer team when the training is finished. Luckily, knock-knock also allows you to send a notification when the training finishes!" }, { "code": null, "e": 3214, "s": 3010, "text": "To send a notification to your Slack, start with enabling and creating an incoming webhook. Then simply specify the webhook URL of your slack room with webhook_url and the channel to notify with channel." }, { "code": null, "e": 3331, "s": 3214, "text": "In case you want to tag your teammate, adduser_mentions=[“your_slack_id”, “your_teammate_slack_id”] to @slack_sender" }, { "code": null, "e": 3442, "s": 3331, "text": "Now when you run your script, a message should be sent to your slack channel when the code finishes executing!" }, { "code": null, "e": 3774, "s": 3442, "text": "Congratulations! You have just learned how to get notified by making noise, sending a notification to your email, or Slack channel. Now you don’t need to constantly check your computer to find out whether the training has complete anymore! You and your teammates can work on other projects while waiting for the training to finish." }, { "code": null, "e": 3881, "s": 3774, "text": "Check knock-knock if you want to use Telegram messenger, text message, or other ways to get notifications." }, { "code": null, "e": 3933, "s": 3881, "text": "The source code for this article can be found here:" }, { "code": null, "e": 3944, "s": 3933, "text": "github.com" }, { "code": null, "e": 4104, "s": 3944, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
Creating Junction Points - GeeksforGeeks
05 Oct, 2020 Junction Points (also commonly referred to as NTFS Junction or Directory Junction) is a type of reparse point which contains a link to a directory that acts as an alias of that directory. Junction points are a Windows exclusive feature, absent in other operating systems. Compatibility with Legacy Windows OS and less privilege requirement makes Junction Points a good alternative for symlinks. In this article, we will take a look at methods used for the creation of junction points on Windows OS. Description of the command : Mklink /J Link Target Description of command as follows. /J : Creates a Directory Junction Link : Specifies the new symbolic link name. Target : Specifies the path (relative or absolute) that the new link refers to. Note –The above text is a stripped-out section out of mklink help page. Creating a Junction Point :Junction points can be created both relatively or absolutely, but they would always refer to the Target path in an absolute manner. Therefore, regardless of whether the link was created using relative paths or using absolute paths, the final target path would be absolute. In the following example we would be creating an Junction Point to the Directory having C:\suga path in our Operating System. To create a junction point at a different path (C:\Users\Public\), the command would look as follows. mklink /J "C:\Users\Public\Junction_PT" "C:\suga" Note –We have provided both source and Target paths as absolute, for the sake of simplicity. Where C:\Users\Public\Junction_PT is the full path to our newly created junction. After the execution of the above command, a Directory Junction would be created at the Link path, which could be confirmed by its entry of type <JUNCTION> in the output of dir command on the newly created junction’s parent directory. Volume in drive C has no label. Volume Serial Number is 2C7D-7820 Directory of C:\Users\Public 09/18/2020 06:22 PM <DIR> . 09/18/2020 06:22 PM <DIR> .. 09/18/2020 09:28 AM <DIR> Documents 06/22/2020 11:25 PM <DIR> Downloads 09/18/2020 06:22 PM <JUNCTION> Junction_PT [C:\suga] 06/22/2020 11:25 PM <DIR> Music 06/22/2020 11:37 PM <DIR> Pictures 06/22/2020 11:25 PM <DIR> Videos 0 File(s) 0 bytes 8 Dir(s) 36, 849, 307, 648 bytes free Note –Bolded the field we are interested in.The junction point (Junction_PT) would have a similar appearance to this. File & Disk Management Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Memory Management in Operating System Difference between Internal and External fragmentation Program for Least Recently Used (LRU) Page Replacement algorithm Mutex lock for Linux Thread Synchronization Logical and Physical Address in Operating System File Allocation Methods States of a Process in Operating Systems Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm Dining Philosopher Problem Using Semaphores Producer Consumer Problem using Semaphores | Set 1
[ { "code": null, "e": 24492, "s": 24464, "text": "\n05 Oct, 2020" }, { "code": null, "e": 24991, "s": 24492, "text": "Junction Points (also commonly referred to as NTFS Junction or Directory Junction) is a type of reparse point which contains a link to a directory that acts as an alias of that directory. Junction points are a Windows exclusive feature, absent in other operating systems. Compatibility with Legacy Windows OS and less privilege requirement makes Junction Points a good alternative for symlinks. In this article, we will take a look at methods used for the creation of junction points on Windows OS." }, { "code": null, "e": 25020, "s": 24991, "text": "Description of the command :" }, { "code": null, "e": 25042, "s": 25020, "text": "Mklink /J Link Target" }, { "code": null, "e": 25077, "s": 25042, "text": "Description of command as follows." }, { "code": null, "e": 25246, "s": 25077, "text": "/J : Creates a Directory Junction\nLink : Specifies the new symbolic link name.\nTarget : Specifies the path (relative or absolute) that the new link refers to.\n" }, { "code": null, "e": 25318, "s": 25246, "text": "Note –The above text is a stripped-out section out of mklink help page." }, { "code": null, "e": 25618, "s": 25318, "text": "Creating a Junction Point :Junction points can be created both relatively or absolutely, but they would always refer to the Target path in an absolute manner. Therefore, regardless of whether the link was created using relative paths or using absolute paths, the final target path would be absolute." }, { "code": null, "e": 25744, "s": 25618, "text": "In the following example we would be creating an Junction Point to the Directory having C:\\suga path in our Operating System." }, { "code": null, "e": 25846, "s": 25744, "text": "To create a junction point at a different path (C:\\Users\\Public\\), the command would look as follows." }, { "code": null, "e": 25897, "s": 25846, "text": "mklink /J \"C:\\Users\\Public\\Junction_PT\" \"C:\\suga\"\n" }, { "code": null, "e": 25990, "s": 25897, "text": "Note –We have provided both source and Target paths as absolute, for the sake of simplicity." }, { "code": null, "e": 26306, "s": 25990, "text": "Where C:\\Users\\Public\\Junction_PT is the full path to our newly created junction. After the execution of the above command, a Directory Junction would be created at the Link path, which could be confirmed by its entry of type <JUNCTION> in the output of dir command on the newly created junction’s parent directory." }, { "code": null, "e": 26883, "s": 26306, "text": "Volume in drive C has no label.\nVolume Serial Number is 2C7D-7820\n\nDirectory of C:\\Users\\Public\n\n09/18/2020 06:22 PM <DIR> .\n09/18/2020 06:22 PM <DIR> ..\n09/18/2020 09:28 AM <DIR> Documents\n06/22/2020 11:25 PM <DIR> Downloads\n09/18/2020 06:22 PM <JUNCTION> Junction_PT [C:\\suga]\n06/22/2020 11:25 PM <DIR> Music\n06/22/2020 11:37 PM <DIR> Pictures\n06/22/2020 11:25 PM <DIR> Videos\n 0 File(s) 0 bytes\n 8 Dir(s) 36, 849, 307, 648 bytes free\n" }, { "code": null, "e": 27001, "s": 26883, "text": "Note –Bolded the field we are interested in.The junction point (Junction_PT) would have a similar appearance to this." }, { "code": null, "e": 27024, "s": 27001, "text": "File & Disk Management" }, { "code": null, "e": 27042, "s": 27024, "text": "Operating Systems" }, { "code": null, "e": 27060, "s": 27042, "text": "Operating Systems" }, { "code": null, "e": 27158, "s": 27060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27196, "s": 27158, "text": "Memory Management in Operating System" }, { "code": null, "e": 27251, "s": 27196, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27316, "s": 27251, "text": "Program for Least Recently Used (LRU) Page Replacement algorithm" }, { "code": null, "e": 27360, "s": 27316, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 27409, "s": 27360, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27433, "s": 27409, "text": "File Allocation Methods" }, { "code": null, "e": 27474, "s": 27433, "text": "States of a Process in Operating Systems" }, { "code": null, "e": 27542, "s": 27474, "text": "Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm" }, { "code": null, "e": 27586, "s": 27542, "text": "Dining Philosopher Problem Using Semaphores" } ]
How to Convert Int to Bytes in Python? - GeeksforGeeks
23 Dec, 2020 An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. Method 1: int.tobytes() An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution. Syntax: int.to_bytes(length, byteorder) Arguments : length – desired length of the array in bytes . byteorder – order of the array to carry out conversion of an int to bytes. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end. Exceptions : OverflowError is returned in case the integer value length is not large enough to be accommodated in the length of the array. The following programs illustrate the usage of this method in Python : Python3 # declaring an integer value integer_val = 5 # converting int to bytes with length # of the array as 2 and byter order as big bytes_val = integer_val.to_bytes(2, 'big') # printing integer in byte representation print(bytes_val) b'\x00\x05' Python3 # declaring an integer value integer_val = 10 # converting int to bytes with length # of the array as 5 and byter order as # little bytes_val = integer_val.to_bytes(5, 'little') # printing integer in byte representation print(bytes_val) b'\n\x00\x00\x00\x00' Method 2: Converting integer to string and string to bytes This approach works is compatible in both Python versions, 2 and 3. This method doesn’t take the length of the array and byteorder as arguments. An integer value represented in decimal format can be converted to string first using the str() function , which takes as argument the integer value to be converted to the corresponding string equivalent. This string equivalent is then converted to a sequence of bytes by choosing the desired representation for each character, that is encoding the string value. This is done by the str.encode() method. Python3 # declaring an integer value int_val = 5 # converting to string str_val = str(int_val) # converting string to bytes byte_val = str_val.encode() print(byte_val) b'5' python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Enumerate() in Python Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python Iterate over a list in Python How to Install PIP on Windows ? Deque in Python Python String | replace() Convert integer to string in Python
[ { "code": null, "e": 23919, "s": 23888, "text": " \n23 Dec, 2020\n" }, { "code": null, "e": 24140, "s": 23919, "text": "An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. " }, { "code": null, "e": 24164, "s": 24140, "text": "Method 1: int.tobytes()" }, { "code": null, "e": 24351, "s": 24164, "text": "An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution." }, { "code": null, "e": 24391, "s": 24351, "text": "Syntax: int.to_bytes(length, byteorder)" }, { "code": null, "e": 24404, "s": 24391, "text": "Arguments : " }, { "code": null, "e": 24452, "s": 24404, "text": "length – desired length of the array in bytes ." }, { "code": null, "e": 24706, "s": 24452, "text": "byteorder – order of the array to carry out conversion of an int to bytes. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end. " }, { "code": null, "e": 24720, "s": 24706, "text": "Exceptions : " }, { "code": null, "e": 24847, "s": 24720, "text": "OverflowError is returned in case the integer value length is not large enough to be accommodated in the length of the array. " }, { "code": null, "e": 24919, "s": 24847, "text": "The following programs illustrate the usage of this method in Python : " }, { "code": null, "e": 24927, "s": 24919, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# declaring an integer value \ninteger_val = 5\n \n# converting int to bytes with length \n# of the array as 2 and byter order as big \nbytes_val = integer_val.to_bytes(2, 'big') \n \n# printing integer in byte representation \nprint(bytes_val) \n\n\n\n\n\n", "e": 25191, "s": 24937, "text": null }, { "code": null, "e": 25203, "s": 25191, "text": "b'\\x00\\x05'" }, { "code": null, "e": 25211, "s": 25203, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# declaring an integer value \ninteger_val = 10\n \n# converting int to bytes with length \n# of the array as 5 and byter order as \n# little \nbytes_val = integer_val.to_bytes(5, 'little') \n \n# printing integer in byte representation \nprint(bytes_val) \n\n\n\n\n\n", "e": 25486, "s": 25221, "text": null }, { "code": null, "e": 25508, "s": 25486, "text": "b'\\n\\x00\\x00\\x00\\x00'" }, { "code": null, "e": 25568, "s": 25508, "text": "Method 2: Converting integer to string and string to bytes " }, { "code": null, "e": 25714, "s": 25568, "text": "This approach works is compatible in both Python versions, 2 and 3. This method doesn’t take the length of the array and byteorder as arguments. " }, { "code": null, "e": 25919, "s": 25714, "text": "An integer value represented in decimal format can be converted to string first using the str() function , which takes as argument the integer value to be converted to the corresponding string equivalent." }, { "code": null, "e": 26118, "s": 25919, "text": "This string equivalent is then converted to a sequence of bytes by choosing the desired representation for each character, that is encoding the string value. This is done by the str.encode() method." }, { "code": null, "e": 26126, "s": 26118, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# declaring an integer value \nint_val = 5\n \n# converting to string \nstr_val = str(int_val) \n \n# converting string to bytes \nbyte_val = str_val.encode() \nprint(byte_val) \n\n\n\n\n\n", "e": 26321, "s": 26136, "text": null }, { "code": null, "e": 26326, "s": 26321, "text": "b'5'" }, { "code": null, "e": 26342, "s": 26326, "text": "\npython-basics\n" }, { "code": null, "e": 26351, "s": 26342, "text": "\nPython\n" }, { "code": null, "e": 26556, "s": 26351, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 26578, "s": 26556, "text": "Enumerate() in Python" }, { "code": null, "e": 26613, "s": 26578, "text": "Read a file line by line in Python" }, { "code": null, "e": 26635, "s": 26613, "text": "Defaultdict in Python" }, { "code": null, "e": 26677, "s": 26635, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26702, "s": 26677, "text": "sum() function in Python" }, { "code": null, "e": 26732, "s": 26702, "text": "Iterate over a list in Python" }, { "code": null, "e": 26764, "s": 26732, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26780, "s": 26764, "text": "Deque in Python" }, { "code": null, "e": 26806, "s": 26780, "text": "Python String | replace()" } ]
POSIX Function strftime() in Perl
You can use the POSIX function strftime() in Perl to format the date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent. Let's check the following example to understand the usage − Live Demo #!/usr/local/bin/perl use POSIX qw(strftime); $datestring = strftime "%a %b %e %H:%M:%S %Y", localtime; printf("date and time - $datestring\n"); # or for GMT formatted appropriately for your locale: $datestring = strftime "%a %b %e %H:%M:%S %Y", gmtime; printf("date and time - $datestring\n"); When the above code is executed, it produces the following result − date and time - Sat Feb 16 07:10:23 2013 date and time - Sat Feb 16 14:10:23 2013
[ { "code": null, "e": 1260, "s": 1062, "text": "You can use the POSIX function strftime() in Perl to format the date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent." }, { "code": null, "e": 1320, "s": 1260, "text": "Let's check the following example to understand the usage −" }, { "code": null, "e": 1331, "s": 1320, "text": " Live Demo" }, { "code": null, "e": 1626, "s": 1331, "text": "#!/usr/local/bin/perl\nuse POSIX qw(strftime);\n$datestring = strftime \"%a %b %e %H:%M:%S %Y\", localtime;\nprintf(\"date and time - $datestring\\n\");\n# or for GMT formatted appropriately for your locale:\n$datestring = strftime \"%a %b %e %H:%M:%S %Y\", gmtime;\nprintf(\"date and time - $datestring\\n\");" }, { "code": null, "e": 1694, "s": 1626, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 1776, "s": 1694, "text": "date and time - Sat Feb 16 07:10:23 2013\ndate and time - Sat Feb 16 14:10:23 2013" } ]
Data Structures | Hash | Question 5 - GeeksforGeeks
20 May, 2019 Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and the hash function x mod 10, which of the following statements are true?i. 9679, 1989, 4199 hash to the same valueii. 1471, 6171 hash to the same valueiii. All elements hash to the same valueiv. Each element hashes to a different value(GATE CS 2004)(A) i only(B) ii only(C) i and ii only(D) iii or ivAnswer: (C)Explanation: Hash function given is mod(10). 9679, 1989 and 4199 all these give same hash value i.e 9 1471 and 6171 give hash value 1 Quiz of this Question UzairGhauri Data Structures Data Structures-Hash Hash Data Structures Data Structures Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j] Advantages and Disadvantages of Linked List C program to implement Adjacency Matrix of a given Graph Introduction to Data Structures | 10 most commonly used Data Structures Difference between Singly linked list and Doubly linked list FIFO vs LIFO approach in Programming Data Structures | Stack | Question 6 Bit manipulation | Swap Endianness of a number Data Structures | Queue | Question 11 Data Structures | Stack | Question 4
[ { "code": null, "e": 24362, "s": 24334, "text": "\n20 May, 2019" }, { "code": null, "e": 24764, "s": 24362, "text": "Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and the hash function x mod 10, which of the following statements are true?i. 9679, 1989, 4199 hash to the same valueii. 1471, 6171 hash to the same valueiii. All elements hash to the same valueiv. Each element hashes to a different value(GATE CS 2004)(A) i only(B) ii only(C) i and ii only(D) iii or ivAnswer: (C)Explanation:" }, { "code": null, "e": 24886, "s": 24764, "text": "Hash function given is mod(10).\n9679, 1989 and 4199 all these give same hash value i.e 9\n1471 and 6171 give hash value 1 " }, { "code": null, "e": 24908, "s": 24886, "text": "Quiz of this Question" }, { "code": null, "e": 24920, "s": 24908, "text": "UzairGhauri" }, { "code": null, "e": 24936, "s": 24920, "text": "Data Structures" }, { "code": null, "e": 24957, "s": 24936, "text": "Data Structures-Hash" }, { "code": null, "e": 24962, "s": 24957, "text": "Hash" }, { "code": null, "e": 24978, "s": 24962, "text": "Data Structures" }, { "code": null, "e": 24994, "s": 24978, "text": "Data Structures" }, { "code": null, "e": 24999, "s": 24994, "text": "Hash" }, { "code": null, "e": 25097, "s": 24999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25106, "s": 25097, "text": "Comments" }, { "code": null, "e": 25119, "s": 25106, "text": "Old Comments" }, { "code": null, "e": 25202, "s": 25119, "text": "Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]" }, { "code": null, "e": 25246, "s": 25202, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 25303, "s": 25246, "text": "C program to implement Adjacency Matrix of a given Graph" }, { "code": null, "e": 25375, "s": 25303, "text": "Introduction to Data Structures | 10 most commonly used Data Structures" }, { "code": null, "e": 25436, "s": 25375, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 25473, "s": 25436, "text": "FIFO vs LIFO approach in Programming" }, { "code": null, "e": 25510, "s": 25473, "text": "Data Structures | Stack | Question 6" }, { "code": null, "e": 25557, "s": 25510, "text": "Bit manipulation | Swap Endianness of a number" }, { "code": null, "e": 25595, "s": 25557, "text": "Data Structures | Queue | Question 11" } ]
How to open a new tab using Selenium WebDriver?
We can open a new tab with Selenium. The Keys.chord and sendKeys methods are used for this. Multiple keys can be passed simultaneously with the Keys.chord method. A group of strings or keys can be passed as parameters to that method. The Keys.CONTROL and Keys.ENTER are passed as parameters to the Keys.chord method here. This is stored as a string value and finally passed as a parameter to the sendKeys method. String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER); driver.findElement(By.xpath("//*[text()='Company']")).sendKeys(nwtb); Code Implementation. 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 OpnLinkNwTab{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); // wait of 4 seconds driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // Keys.Chord string String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER); // open the link in new tab, Keys.Chord string passed to sendKeys driver.findElement( By.xpath("//*[text()='Company']")).sendKeys(nwtb); } }
[ { "code": null, "e": 1296, "s": 1062, "text": "We can open a new tab with Selenium. The Keys.chord and sendKeys methods are used for this. Multiple keys can be passed simultaneously with the Keys.chord method. A group of strings or keys can be passed as parameters to that method." }, { "code": null, "e": 1475, "s": 1296, "text": "The Keys.CONTROL and Keys.ENTER are passed as parameters to the Keys.chord method here. This is stored as a string value and finally passed as a parameter to the sendKeys method." }, { "code": null, "e": 1596, "s": 1475, "text": "String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER);\ndriver.findElement(By.xpath(\"//*[text()='Company']\")).sendKeys(nwtb);" }, { "code": null, "e": 1617, "s": 1596, "text": "Code Implementation." }, { "code": null, "e": 2454, "s": 1617, "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 OpnLinkNwTab{\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 // wait of 4 seconds\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // Keys.Chord string\n String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER);\n // open the link in new tab, Keys.Chord string passed to sendKeys\n driver.findElement(\n By.xpath(\"//*[text()='Company']\")).sendKeys(nwtb);\n }\n}" } ]
Integrating JsonToKotlin Plugin With Android Studio - GeeksforGeeks
18 Feb, 2021 Android Studio is the best IDE for android development. Plenty of plugins are available and they can be installed easily via Android Studio itself. In computing, a plug-in is a software component that adds a particular characteristic to an existing computer program. When a program supports plug-ins, it enables customization. Plugins are a great way to increase productivity and overall programming experience.⁣⁣ Some tasks are boring and not fun to do, by using plugins in the android studio you can get more done in less time. One such plugin that we are going to see in this article is “JsonToKotlin Plugin“. Note: You may refer to the 6 Most Useful Android Studio Plugins to know the most useful android studio plugins. JSON to kotlin Class is a plugin to create Kotlin data class from JSON string, in other words, a plugin that changes JSON string to Kotlin data class. With this, you can generate a Kotlin data class from the JSON string programmatically. Supporting (almost) all kinds of JSON libs’ annotation(Gson, Jackson, Fastjson, MoShi and LoganSquare, kotlinx.serialization(default custom value)). Some of the important features are: Customizing the own annotations Initializing properties with default values Allowing properties to be nullable(?) Determining property nullability automatically Renaming field names to be camelCase style when selecting a target JSON lib annotation. Generating Kotlin class as individual classes Generating Kotlin class as inner classes Formatting any legal JSON string Generating Map Type when JSON key is the primitive type Only create annotation when needed Custom define data class parent class Sort property order by Alphabetical Make keyword property valid Support Loading JSON From Paster/Local File/HTTP URL Support customize your own plugin by Extension Module Normal Class support Dynamic plugin load support Support generating ListClass from JSONArray Complex JSON schema supporting JSON to kotlin Class is an excellent tool for Kotlin developers and it can convert a JSON string to Kotlin data class. The tool could not only understand the primitive types but also auto-create complex types. It’s simply accessible. We provide shortcut keymap ALT + K for Windows and Option + K for Mac, have a try and you are going to fall in love with it! JsonToKotlinClass just makes programming more delightful. Note: You may refer to How to Install and Uninstall Plugins in Android Studio? to Install and Uninstall Plugins in Android Studio. Step 1: Go to the File > Settings > Plugins > Search for jsontokotlin as shown in the below image. Step 2: Press the install button Step 3: Once you got the plugin, please install it by clicking on the “Install” button. Then select the project location and right-click on that folder, select New > Kotlin data class file from JSON (as shown in the image below) Step 4: Then in the place of JSON provision, provide the JSON that you want to convert. In our example, let us give the sample output of JSON that is meant for Exchange Rates as shown in the below image Once it is given and generate, we can able to see 2 files got generated as shown in the below-attached image. Here two data class are generated. “ExchangeRates” is the data class nothing but the name that we specified If we check the JSON output and generated data class “ExchangeRates”, all the column names like base -> String datatype, date -> String datatype, rates -> Rates datatype, time_last_updated -> int datatype is created very easily. Kotlin // JSON to kotlin conversion is // easier with JSONToKotlin plugindata class ExchangeRates( val base: String, val date: String, val rates: Rates, val time_last_updated: Int) And since many “Rates” are there, which are nothing but the exchange rate value of all the available worldwide currencies, it has got created with another data class. Kotlin // In JSON, below are the currencies // available and they are presented heredata class Rates( val AED: Double, val ARS: Double, val AUD: Double, val BGN: Double, val BRL: Double, val BSD: Int, val CAD: Double, val CHF: Double, val CLP: Double, val CNY: Double, val COP: Double, val CZK: Double, val DKK: Double, val DOP: Double, val EGP: Double, val EUR: Double, val FJD: Double, val GBP: Double, val GTQ: Double, val HKD: Double, val HRK: Double, val HUF: Double, val IDR: Double, val ILS: Double, val INR: Double, val ISK: Double, val JPY: Double, val KRW: Double, val KZT: Double, val MVR: Double, val MXN: Double, val MYR: Double, val NOK: Double, val NZD: Double, val PAB: Int, val PEN: Double, val PHP: Double, val PKR: Double, val PLN: Double, val PYG: Double, val RON: Double, val RUB: Double, val SAR: Double, val SEK: Double, val SGD: Double, val THB: Double, val TRY: Double, val TWD: Double, val UAH: Double, val USD: Int, val UYU: Double, val ZAR: Double) One can customize your own annotations Can initialize properties with default values Can allow properties to be nullable Can determine property nullability automatically Can rename property names to be camelCase style when selecting a target JSON lib annotation. Can generate Kotlin class as individual classes Can Generate Kotlin class as inner classes Can format any legal JSON string Can generate Map Type when JSON key is a primitive type. Can only create annotation when needed. Custom define data class parent class Sort property order by Alphabetical Make keyword property valid Support Loading JSON From Paster/Local File/HTTP URL Support customize your own plugin by Extension Module Let us consider one more example JSON File: Check on advanced options: Resultant Kotlin class: Hence any valid formatted JSON can be converted into Kotlin data class very easily by using the amazing “JSONToKotlin” plugin. Very helpful for your development. Advanced properties help to convert JSON to kotlin with the available options and hence it is very useful in the development. android Android-Studio Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin How to View and Locate SQLite Database in Android Studio? Navigation Drawer in Android Retrofit with Kotlin Coroutine in Android How to Update Gradle in Android Studio? Android Listview in Java with Example
[ { "code": null, "e": 24590, "s": 24562, "text": "\n18 Feb, 2021" }, { "code": null, "e": 25203, "s": 24590, "text": "Android Studio is the best IDE for android development. Plenty of plugins are available and they can be installed easily via Android Studio itself. In computing, a plug-in is a software component that adds a particular characteristic to an existing computer program. When a program supports plug-ins, it enables customization. Plugins are a great way to increase productivity and overall programming experience.⁣⁣ Some tasks are boring and not fun to do, by using plugins in the android studio you can get more done in less time. One such plugin that we are going to see in this article is “JsonToKotlin Plugin“." }, { "code": null, "e": 25315, "s": 25203, "text": "Note: You may refer to the 6 Most Useful Android Studio Plugins to know the most useful android studio plugins." }, { "code": null, "e": 25738, "s": 25315, "text": "JSON to kotlin Class is a plugin to create Kotlin data class from JSON string, in other words, a plugin that changes JSON string to Kotlin data class. With this, you can generate a Kotlin data class from the JSON string programmatically. Supporting (almost) all kinds of JSON libs’ annotation(Gson, Jackson, Fastjson, MoShi and LoganSquare, kotlinx.serialization(default custom value)). Some of the important features are:" }, { "code": null, "e": 25770, "s": 25738, "text": "Customizing the own annotations" }, { "code": null, "e": 25814, "s": 25770, "text": "Initializing properties with default values" }, { "code": null, "e": 25852, "s": 25814, "text": "Allowing properties to be nullable(?)" }, { "code": null, "e": 25899, "s": 25852, "text": "Determining property nullability automatically" }, { "code": null, "e": 25987, "s": 25899, "text": "Renaming field names to be camelCase style when selecting a target JSON lib annotation." }, { "code": null, "e": 26033, "s": 25987, "text": "Generating Kotlin class as individual classes" }, { "code": null, "e": 26074, "s": 26033, "text": "Generating Kotlin class as inner classes" }, { "code": null, "e": 26107, "s": 26074, "text": "Formatting any legal JSON string" }, { "code": null, "e": 26163, "s": 26107, "text": "Generating Map Type when JSON key is the primitive type" }, { "code": null, "e": 26198, "s": 26163, "text": "Only create annotation when needed" }, { "code": null, "e": 26236, "s": 26198, "text": "Custom define data class parent class" }, { "code": null, "e": 26272, "s": 26236, "text": "Sort property order by Alphabetical" }, { "code": null, "e": 26300, "s": 26272, "text": "Make keyword property valid" }, { "code": null, "e": 26353, "s": 26300, "text": "Support Loading JSON From Paster/Local File/HTTP URL" }, { "code": null, "e": 26407, "s": 26353, "text": "Support customize your own plugin by Extension Module" }, { "code": null, "e": 26428, "s": 26407, "text": "Normal Class support" }, { "code": null, "e": 26456, "s": 26428, "text": "Dynamic plugin load support" }, { "code": null, "e": 26500, "s": 26456, "text": "Support generating ListClass from JSONArray" }, { "code": null, "e": 26531, "s": 26500, "text": "Complex JSON schema supporting" }, { "code": null, "e": 26948, "s": 26531, "text": "JSON to kotlin Class is an excellent tool for Kotlin developers and it can convert a JSON string to Kotlin data class. The tool could not only understand the primitive types but also auto-create complex types. It’s simply accessible. We provide shortcut keymap ALT + K for Windows and Option + K for Mac, have a try and you are going to fall in love with it! JsonToKotlinClass just makes programming more delightful." }, { "code": null, "e": 27079, "s": 26948, "text": "Note: You may refer to How to Install and Uninstall Plugins in Android Studio? to Install and Uninstall Plugins in Android Studio." }, { "code": null, "e": 27178, "s": 27079, "text": "Step 1: Go to the File > Settings > Plugins > Search for jsontokotlin as shown in the below image." }, { "code": null, "e": 27211, "s": 27178, "text": "Step 2: Press the install button" }, { "code": null, "e": 27440, "s": 27211, "text": "Step 3: Once you got the plugin, please install it by clicking on the “Install” button. Then select the project location and right-click on that folder, select New > Kotlin data class file from JSON (as shown in the image below)" }, { "code": null, "e": 27644, "s": 27440, "text": "Step 4: Then in the place of JSON provision, provide the JSON that you want to convert. In our example, let us give the sample output of JSON that is meant for Exchange Rates as shown in the below image" }, { "code": null, "e": 27789, "s": 27644, "text": "Once it is given and generate, we can able to see 2 files got generated as shown in the below-attached image. Here two data class are generated." }, { "code": null, "e": 27959, "s": 27789, "text": "“ExchangeRates” is the data class nothing but the name that we specified If we check the JSON output and generated data class “ExchangeRates”, all the column names like" }, { "code": null, "e": 27984, "s": 27959, "text": "base -> String datatype," }, { "code": null, "e": 28009, "s": 27984, "text": "date -> String datatype," }, { "code": null, "e": 28034, "s": 28009, "text": "rates -> Rates datatype," }, { "code": null, "e": 28069, "s": 28034, "text": "time_last_updated -> int datatype " }, { "code": null, "e": 28093, "s": 28069, "text": "is created very easily." }, { "code": null, "e": 28100, "s": 28093, "text": "Kotlin" }, { "code": "// JSON to kotlin conversion is // easier with JSONToKotlin plugindata class ExchangeRates( val base: String, val date: String, val rates: Rates, val time_last_updated: Int)", "e": 28286, "s": 28100, "text": null }, { "code": null, "e": 28453, "s": 28286, "text": "And since many “Rates” are there, which are nothing but the exchange rate value of all the available worldwide currencies, it has got created with another data class." }, { "code": null, "e": 28460, "s": 28453, "text": "Kotlin" }, { "code": "// In JSON, below are the currencies // available and they are presented heredata class Rates( val AED: Double, val ARS: Double, val AUD: Double, val BGN: Double, val BRL: Double, val BSD: Int, val CAD: Double, val CHF: Double, val CLP: Double, val CNY: Double, val COP: Double, val CZK: Double, val DKK: Double, val DOP: Double, val EGP: Double, val EUR: Double, val FJD: Double, val GBP: Double, val GTQ: Double, val HKD: Double, val HRK: Double, val HUF: Double, val IDR: Double, val ILS: Double, val INR: Double, val ISK: Double, val JPY: Double, val KRW: Double, val KZT: Double, val MVR: Double, val MXN: Double, val MYR: Double, val NOK: Double, val NZD: Double, val PAB: Int, val PEN: Double, val PHP: Double, val PKR: Double, val PLN: Double, val PYG: Double, val RON: Double, val RUB: Double, val SAR: Double, val SEK: Double, val SGD: Double, val THB: Double, val TRY: Double, val TWD: Double, val UAH: Double, val USD: Int, val UYU: Double, val ZAR: Double)", "e": 29586, "s": 28460, "text": null }, { "code": null, "e": 29625, "s": 29586, "text": "One can customize your own annotations" }, { "code": null, "e": 29671, "s": 29625, "text": "Can initialize properties with default values" }, { "code": null, "e": 29707, "s": 29671, "text": "Can allow properties to be nullable" }, { "code": null, "e": 29756, "s": 29707, "text": "Can determine property nullability automatically" }, { "code": null, "e": 29849, "s": 29756, "text": "Can rename property names to be camelCase style when selecting a target JSON lib annotation." }, { "code": null, "e": 29897, "s": 29849, "text": "Can generate Kotlin class as individual classes" }, { "code": null, "e": 29940, "s": 29897, "text": "Can Generate Kotlin class as inner classes" }, { "code": null, "e": 29973, "s": 29940, "text": "Can format any legal JSON string" }, { "code": null, "e": 30030, "s": 29973, "text": "Can generate Map Type when JSON key is a primitive type." }, { "code": null, "e": 30070, "s": 30030, "text": "Can only create annotation when needed." }, { "code": null, "e": 30108, "s": 30070, "text": "Custom define data class parent class" }, { "code": null, "e": 30144, "s": 30108, "text": "Sort property order by Alphabetical" }, { "code": null, "e": 30172, "s": 30144, "text": "Make keyword property valid" }, { "code": null, "e": 30225, "s": 30172, "text": "Support Loading JSON From Paster/Local File/HTTP URL" }, { "code": null, "e": 30279, "s": 30225, "text": "Support customize your own plugin by Extension Module" }, { "code": null, "e": 30312, "s": 30279, "text": "Let us consider one more example" }, { "code": null, "e": 30323, "s": 30312, "text": "JSON File:" }, { "code": null, "e": 30350, "s": 30323, "text": "Check on advanced options:" }, { "code": null, "e": 30374, "s": 30350, "text": "Resultant Kotlin class:" }, { "code": null, "e": 30662, "s": 30374, "text": "Hence any valid formatted JSON can be converted into Kotlin data class very easily by using the amazing “JSONToKotlin” plugin. Very helpful for your development. Advanced properties help to convert JSON to kotlin with the available options and hence it is very useful in the development." }, { "code": null, "e": 30670, "s": 30662, "text": "android" }, { "code": null, "e": 30685, "s": 30670, "text": "Android-Studio" }, { "code": null, "e": 30693, "s": 30685, "text": "Android" }, { "code": null, "e": 30701, "s": 30693, "text": "Android" }, { "code": null, "e": 30799, "s": 30701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30808, "s": 30799, "text": "Comments" }, { "code": null, "e": 30821, "s": 30808, "text": "Old Comments" }, { "code": null, "e": 30879, "s": 30821, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 30922, "s": 30879, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 30955, "s": 30922, "text": "Services in Android with Example" }, { "code": null, "e": 30997, "s": 30955, "text": "Content Providers in Android with Example" }, { "code": null, "e": 31028, "s": 30997, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 31086, "s": 31028, "text": "How to View and Locate SQLite Database in Android Studio?" }, { "code": null, "e": 31115, "s": 31086, "text": "Navigation Drawer in Android" }, { "code": null, "e": 31157, "s": 31115, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31197, "s": 31157, "text": "How to Update Gradle in Android Studio?" } ]
Tail command in Linux with examples - GeeksforGeeks
19 Feb, 2021 It is the complementary of head command.The tail command, as the name implies, print the last N number of data of the given input. By default it prints the last 10 lines of the specified files. If more than one file name is provided then data from each file is precedes by its file name. Syntax: tail [OPTION]... [FILE]... Let us consider two files having name state.txt and capital.txt contains all the names of the Indian states and capitals respectively. $ cat state.txt Andhra Pradesh Arunachal Pradesh Assam Bihar Chhattisgarh Goa Gujarat Haryana Himachal Pradesh Jammu and Kashmir Jharkhand Karnataka Kerala Madhya Pradesh Maharashtra Manipur Meghalaya Mizoram Nagaland Odisha Punjab Rajasthan Sikkim Tamil Nadu Telangana Tripura Uttar Pradesh Uttarakhand West Bengal Without any option it display only the last 10 lines of the file specified. Example: $ tail state.txt Odisha Punjab Rajasthan Sikkim Tamil Nadu Telangana Tripura Uttar Pradesh Uttarakhand West Bengal Options: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. 1. -n num: Prints the last ‘num’ lines instead of last 10 lines. num is mandatory to be specified in command otherwise it displays an error. This command can also be written as without symbolizing ‘n’ character but ‘-‘ sign is mandatory. $ tail -n 3 state.txt Uttar Pradesh Uttarakhand West Bengal OR $ tail -3 state.txt Uttar Pradesh Uttarakhand West Bengal Tail command also comes with an ‘+’ option which is not present in the head command. With this option tail command prints the data starting from specified line number of the file instead of end. For command: tail +n file_name, data will start printing from line number ‘n’ till the end of the file specified. $ tail +25 state.txt Telangana Tripura Uttar Pradesh Uttarakhand West Bengal 2. -c num: Prints the last ‘num’ bytes from the file specified. Newline count as a single character, so if tail prints out a newline, it will count it as a byte. In this option it is mandatory to write -c followed by positive or negative num depends upon the requirement. By +num, it display all the data after skipping num bytes from starting of the specified file and by -num, it display the last num bytes from the file specified. Note: Without positive or negative sign before num, command will display the last num bytes from the file specified. With negative num $ tail -c -6 state.txt Bengal OR $ tail -c 6 state.txt Bengal With positive num $ tail -c +263 state.txt Nadu Telangana Tripura Uttar Pradesh Uttarakhand 3. -q: It is used if more than 1 file is given. Because of this command, data from each file is not precedes by its file name. Without using -q option $ tail state.txt capital.txt state.txt Odisha Punjab Rajasthan Sikkim Tamil Nadu Telangana Tripura Uttar Pradesh Uttarakhand West Bengal capital.txt Dispur Patna Raipur Panaji Gandhinagar Chandigarh Shimla Srinagar Ranchi With using -q option $ tail -q state.txt capital.txt Odisha Punjab Rajasthan Sikkim Tamil Nadu Telangana Tripura Uttar Pradesh Uttarakhand West BengalDispur Patna Raipur Panaji Gandhinagar Chandigarh Shimla Srinagar Ranchi Bengaluru 4. -f: This option is mainly used by system administration to monitor the growth of the log files written by many Unix program as they are running. This option shows the last ten lines of a file and will update when new lines are added. As new lines are written to the log, the console will update with the new lines. The prompt doesn’t return even after work is over so, we have to use the interrupt key to abort this command. In general, the applications writes error messages to log files. You can use the -f option to check for the error messages as and when they appear in the log file. $ tail -f logfile 5. -v: By using this option, data from the specified file is always preceded by its file name. $ tail -v state.txt ==> state.txt <== Odisha Punjab Rajasthan Sikkim Tamil Nadu Telangana Tripura Uttar Pradesh Uttarakhand West Bengal 6. –version: This option is used to display the version of tail which is currently running on your system. $ tail --version tail (GNU coreutils) 8.26 Packaged by Cygwin (8.26-1) Copyright (C) 2016 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Written by Paul Rubin, David MacKenzie, Ian Lance Taylor, and Jim Meyering. Applications of tail Command 1. How to use tail with pipes(|): The tail command can be piped with many other commands of the unix. In the following example output of the tail command is given as input to the sort command with -r option to sort the last 7 state names coming from file state.txt in the reverse order. $ tail -n 7 state.txt Sikkim Tamil Nadu Telangana Tripura Uttar Pradesh Uttarakhand West Bengal $ tail -n 7 state.txt | sort -r West Bengal Uttarakhand Uttar Pradesh Tripura Telangana Tamil Nadu Sikkim It can also be piped with one or more filters for additional processing. Like in the following example, we are using cat, head and tail command and whose output is stored in the file name list.txt using directive(>). $ cat state.txt | head -n 20 | tail -n 5 > list.txt $ cat list.txt Manipur Meghalaya Mizoram Nagaland Odisha What is happening in this command let’s try to explore it. First cat command gives all the data present in the file state.txt and after that pipe transfers all the output coming from cat command to the head command. Head command gives all the data from start(line number 1) to the line number 20 and pipe transfer all the output coming from head command to tail command. Now, tail command gives last 5 lines of the data and the output goes to the file name list.txt via directive operator. 2. Print line between M and N lines YouTubeGeeksforGeeks506K subscribersLinux Tutorials | tail command | GeeksforGeeksWatch laterShareCopy link22/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=1pD28tFgAb8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Akash Gupta. 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. linux-command Linux-text-processing-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script UDP Server-Client implementation in C Cat command in Linux with examples touch command in Linux with Examples scp command in Linux with Examples echo command in Linux with Examples ps command in Linux with Examples Compiling with g++
[ { "code": null, "e": 25431, "s": 25400, "text": " \n19 Feb, 2021\n" }, { "code": null, "e": 25720, "s": 25431, "text": "It is the complementary of head command.The tail command, as the name implies, print the last N number of data of the given input. By default it prints the last 10 lines of the specified files. If more than one file name is provided then data from each file is precedes by its file name. " }, { "code": null, "e": 25728, "s": 25720, "text": "Syntax:" }, { "code": null, "e": 25756, "s": 25728, "text": "tail [OPTION]... [FILE]...\n" }, { "code": null, "e": 25891, "s": 25756, "text": "Let us consider two files having name state.txt and capital.txt contains all the names of the Indian states and capitals respectively." }, { "code": null, "e": 26208, "s": 25891, "text": "$ cat state.txt\nAndhra Pradesh\nArunachal Pradesh\nAssam\nBihar\nChhattisgarh\nGoa\nGujarat\nHaryana\nHimachal Pradesh\nJammu and Kashmir\nJharkhand\nKarnataka\nKerala\nMadhya Pradesh\nMaharashtra\nManipur\nMeghalaya\nMizoram\nNagaland\nOdisha\nPunjab\nRajasthan\nSikkim\nTamil Nadu\nTelangana\nTripura\nUttar Pradesh\nUttarakhand\nWest Bengal\n" }, { "code": null, "e": 26293, "s": 26208, "text": "Without any option it display only the last 10 lines of the file specified.\nExample:" }, { "code": null, "e": 26409, "s": 26293, "text": "$ tail state.txt\nOdisha\nPunjab\nRajasthan\nSikkim\nTamil Nadu\nTelangana\nTripura\nUttar Pradesh\nUttarakhand\nWest Bengal\n" }, { "code": null, "e": 26418, "s": 26409, "text": "Options:" }, { "code": null, "e": 26427, "s": 26418, "text": "Chapters" }, { "code": null, "e": 26454, "s": 26427, "text": "descriptions off, selected" }, { "code": null, "e": 26504, "s": 26454, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 26527, "s": 26504, "text": "captions off, selected" }, { "code": null, "e": 26535, "s": 26527, "text": "English" }, { "code": null, "e": 26559, "s": 26535, "text": "This is a modal window." }, { "code": null, "e": 26628, "s": 26559, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 26650, "s": 26628, "text": "End of dialog window." }, { "code": null, "e": 26889, "s": 26650, "text": "1. -n num: Prints the last ‘num’ lines instead of last 10 lines. num is mandatory to be specified in command otherwise it displays an error. This command can also be written as without symbolizing ‘n’ character but ‘-‘ sign is mandatory. " }, { "code": null, "e": 27018, "s": 26889, "text": "$ tail -n 3 state.txt\nUttar Pradesh\nUttarakhand\nWest Bengal\n OR\n$ tail -3 state.txt\nUttar Pradesh\nUttarakhand\nWest Bengal\n" }, { "code": null, "e": 27327, "s": 27018, "text": "Tail command also comes with an ‘+’ option which is not present in the head command. With this option tail command prints the data starting from specified line number of the file instead of end. For command: tail +n file_name, data will start printing from line number ‘n’ till the end of the file specified." }, { "code": null, "e": 27405, "s": 27327, "text": "$ tail +25 state.txt\nTelangana\nTripura\nUttar Pradesh\nUttarakhand\nWest Bengal\n" }, { "code": null, "e": 27956, "s": 27405, "text": "2. -c num: Prints the last ‘num’ bytes from the file specified. Newline count as a single character, so if tail prints out a newline, it will count it as a byte. In this option it is mandatory to write -c followed by positive or negative num depends upon the requirement. By +num, it display all the data after skipping num bytes from starting of the specified file and by -num, it display the last num bytes from the file specified.\nNote: Without positive or negative sign before num, command will display the last num bytes from the file specified." }, { "code": null, "e": 28138, "s": 27956, "text": "With negative num\n$ tail -c -6 state.txt\nBengal\n OR\n$ tail -c 6 state.txt\nBengal\n\nWith positive num\n$ tail -c +263 state.txt\nNadu\nTelangana\nTripura\nUttar Pradesh\nUttarakhand\n" }, { "code": null, "e": 28265, "s": 28138, "text": "3. -q: It is used if more than 1 file is given. Because of this command, data from each file is not precedes by its file name." }, { "code": null, "e": 28751, "s": 28265, "text": "Without using -q option\n$ tail state.txt capital.txt\n state.txt\nOdisha\nPunjab\nRajasthan\nSikkim\nTamil Nadu\nTelangana\nTripura\nUttar Pradesh\nUttarakhand\nWest Bengal\n capital.txt\nDispur\nPatna\nRaipur\nPanaji\nGandhinagar\nChandigarh\nShimla\nSrinagar\nRanchi\n\n\nWith using -q option\n$ tail -q state.txt capital.txt\nOdisha\nPunjab\nRajasthan\nSikkim\nTamil Nadu\nTelangana\nTripura\nUttar Pradesh\nUttarakhand\nWest BengalDispur\nPatna\nRaipur\nPanaji\nGandhinagar\nChandigarh\nShimla\nSrinagar\nRanchi\nBengaluru\n" }, { "code": null, "e": 29344, "s": 28751, "text": "4. -f: This option is mainly used by system administration to monitor the growth of the log files written by many Unix program as they are running. This option shows the last ten lines of a file and will update when new lines are added. As new lines are written to the log, the console will update with the new lines. The prompt doesn’t return even after work is over so, we have to use the interrupt key to abort this command. In general, the applications writes error messages to log files. You can use the -f option to check for the error messages as and when they appear in the log file. " }, { "code": null, "e": 29363, "s": 29344, "text": "$ tail -f logfile\n" }, { "code": null, "e": 29458, "s": 29363, "text": "5. -v: By using this option, data from the specified file is always preceded by its file name." }, { "code": null, "e": 29595, "s": 29458, "text": "$ tail -v state.txt\n==> state.txt <==\nOdisha\nPunjab\nRajasthan\nSikkim\nTamil Nadu\nTelangana\nTripura\nUttar Pradesh\nUttarakhand\nWest Bengal\n" }, { "code": null, "e": 29703, "s": 29595, "text": "6. –version: This option is used to display the version of tail which is currently running on your system. " }, { "code": null, "e": 30069, "s": 29703, "text": "$ tail --version\ntail (GNU coreutils) 8.26\nPackaged by Cygwin (8.26-1)\nCopyright (C) 2016 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later .\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\n\nWritten by Paul Rubin, David MacKenzie, Ian Lance Taylor,\nand Jim Meyering.\n\n" }, { "code": null, "e": 30098, "s": 30069, "text": "Applications of tail Command" }, { "code": null, "e": 30385, "s": 30098, "text": "1. How to use tail with pipes(|): The tail command can be piped with many other commands of the unix. In the following example output of the tail command is given as input to the sort command with -r option to sort the last 7 state names coming from file state.txt in the reverse order." }, { "code": null, "e": 30589, "s": 30385, "text": "$ tail -n 7 state.txt\nSikkim\nTamil Nadu\nTelangana\nTripura\nUttar Pradesh\nUttarakhand\nWest Bengal\n\n$ tail -n 7 state.txt | sort -r\nWest Bengal\nUttarakhand\nUttar Pradesh\nTripura\nTelangana\nTamil Nadu\nSikkim\n" }, { "code": null, "e": 30806, "s": 30589, "text": "It can also be piped with one or more filters for additional processing. Like in the following example, we are using cat, head and tail command and whose output is stored in the file name list.txt using directive(>)." }, { "code": null, "e": 30919, "s": 30806, "text": "$ cat state.txt | head -n 20 | tail -n 5 > list.txt\n\n$ cat list.txt\nManipur\nMeghalaya\nMizoram\nNagaland\nOdisha\n\n" }, { "code": null, "e": 32579, "s": 30919, "text": "What is happening in this command let’s try to explore it. First cat command gives all the data present in the file state.txt and after that pipe transfers all the output coming from cat command to the head command. Head command gives all the data from start(line number 1) to the line number 20 and pipe transfer all the output coming from head command to tail command. Now, tail command gives last 5 lines of the data and the output goes to the file name list.txt via directive operator.\n2. Print line between M and N lines\nYouTubeGeeksforGeeks506K subscribersLinux Tutorials | tail command | GeeksforGeeksWatch laterShareCopy link22/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=1pD28tFgAb8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>\nThis article is contributed by Akash Gupta. 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": 32704, "s": 32579, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 32720, "s": 32704, "text": "\nlinux-command\n" }, { "code": null, "e": 32753, "s": 32720, "text": "\nLinux-text-processing-commands\n" }, { "code": null, "e": 32766, "s": 32753, "text": "\nLinux-Unix\n" }, { "code": null, "e": 32971, "s": 32766, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 33006, "s": 32971, "text": "tar command in Linux with examples" }, { "code": null, "e": 33042, "s": 33006, "text": "curl command in Linux with Examples" }, { "code": null, "e": 33080, "s": 33042, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 33118, "s": 33080, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 33153, "s": 33118, "text": "Cat command in Linux with examples" }, { "code": null, "e": 33190, "s": 33153, "text": "touch command in Linux with Examples" }, { "code": null, "e": 33225, "s": 33190, "text": "scp command in Linux with Examples" }, { "code": null, "e": 33261, "s": 33225, "text": "echo command in Linux with Examples" }, { "code": null, "e": 33296, "s": 33261, "text": "ps command in Linux with Examples" } ]
How to Create Bindings and Conditions Between Multiple Plots Using Altair | by Khuyen Tran | Towards Data Science
Have you ever wanted to see one plot change when you interact with another plot like below? That is when Altair comes in handy. The graph above is created with Altair. If you don’t know about Altair, Altair is a statistical visualization library for Python based on Vega and Vega-Lite. In my last article, I showed how Altair allows you to use concise visualization grammar to quickly build statistical graphics. In this article, I will show how you can create bindings and conditions between multiple plots using Altair. To install Altair, type: pip install altair We will use Altair to explore the CSV file downloaded from Students Performance in Exams data posted on Kaggle. Cool! Now we have the data, let’s visualize it using Altair. We will create a graph that uses an interval selection to filter the contents of a bar plot. Start with creating a scatter plot that allows us to select a specific interval by clicking and dragging. Try to click and drag the chart above. You should see only the colors of the points inside the selected region are highlighted! The code to produce the output above: Explanations: brush = alt.selection(type="interval") : Create interval selection object encode : Specify columns shown in x-axis and y-axis color=alt.condition(brush, “gender:N”, alt.value(“lightgray”) : If the points are in the selected interval, color those points by gender , else color those points lightgray . tooltip : Information to show when hovering over a point add_selection(brush) : Apply interval selection to the chart Q specifies Quantitative (numerical data), N specifies Nominal (categorical data) Refer to this article if you want to understand more about Altair’s basic syntax. Now that we created the interval selection, let’s connect it to another bar plot. Try clicking and dragging the scatter plot. You should see the distribution of the bar plot change when selecting different intervals! Code to produce the plot above: Explanations: x="count(parental_level_of_education):Q": Count of each value in parental_level_of_education column. color=alt.Color(“parental_level_of_education:N”) : Apply colors to bars based on parental_level_of_education transform_filter(brush) : Filter data based on the selected interval With Altair’s Bindings feature, you can do many cool things to bring clarity to your plot such as: Sometimes you might wish to zoom in on your histogram to get a more granular view of your histogram. That can be done with Altair. You can play with the chart yourself here: Code to create the plot above: You might also wish to understand the histogram by looking at which points fall in the selected interval of the histogram. That could also be done with Altair: You can play with the chart yourself here: Code to create the plot above: You can also use Altair to apply multiple filters to your data points like below: You can play with the plot here: Code of the plot above: I hope the code above doesn’t scare you! Many lines of the code above show what we already learned in the first section. Some new Altair’s objects that were not mentioned before: alt.selection_single : Allow users to select only one option at a time alt.binding_select : Create a dropdown bar alt.binding_radio : Create a radio button Congratulations! You have just learned how to bind multiple plots using Altair! Being able to link between multiple plots will bring much more clarity to your data analysis. Plus, you can impress your audience with these plots as well! Feel free to play and fork the source code of this article here: github.com I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 300, "s": 172, "text": "Have you ever wanted to see one plot change when you interact with another plot like below? That is when Altair comes in handy." }, { "code": null, "e": 585, "s": 300, "text": "The graph above is created with Altair. If you don’t know about Altair, Altair is a statistical visualization library for Python based on Vega and Vega-Lite. In my last article, I showed how Altair allows you to use concise visualization grammar to quickly build statistical graphics." }, { "code": null, "e": 694, "s": 585, "text": "In this article, I will show how you can create bindings and conditions between multiple plots using Altair." }, { "code": null, "e": 719, "s": 694, "text": "To install Altair, type:" }, { "code": null, "e": 738, "s": 719, "text": "pip install altair" }, { "code": null, "e": 850, "s": 738, "text": "We will use Altair to explore the CSV file downloaded from Students Performance in Exams data posted on Kaggle." }, { "code": null, "e": 911, "s": 850, "text": "Cool! Now we have the data, let’s visualize it using Altair." }, { "code": null, "e": 1110, "s": 911, "text": "We will create a graph that uses an interval selection to filter the contents of a bar plot. Start with creating a scatter plot that allows us to select a specific interval by clicking and dragging." }, { "code": null, "e": 1238, "s": 1110, "text": "Try to click and drag the chart above. You should see only the colors of the points inside the selected region are highlighted!" }, { "code": null, "e": 1276, "s": 1238, "text": "The code to produce the output above:" }, { "code": null, "e": 1290, "s": 1276, "text": "Explanations:" }, { "code": null, "e": 1364, "s": 1290, "text": "brush = alt.selection(type=\"interval\") : Create interval selection object" }, { "code": null, "e": 1416, "s": 1364, "text": "encode : Specify columns shown in x-axis and y-axis" }, { "code": null, "e": 1591, "s": 1416, "text": "color=alt.condition(brush, “gender:N”, alt.value(“lightgray”) : If the points are in the selected interval, color those points by gender , else color those points lightgray ." }, { "code": null, "e": 1648, "s": 1591, "text": "tooltip : Information to show when hovering over a point" }, { "code": null, "e": 1709, "s": 1648, "text": "add_selection(brush) : Apply interval selection to the chart" }, { "code": null, "e": 1791, "s": 1709, "text": "Q specifies Quantitative (numerical data), N specifies Nominal (categorical data)" }, { "code": null, "e": 1873, "s": 1791, "text": "Refer to this article if you want to understand more about Altair’s basic syntax." }, { "code": null, "e": 1955, "s": 1873, "text": "Now that we created the interval selection, let’s connect it to another bar plot." }, { "code": null, "e": 2090, "s": 1955, "text": "Try clicking and dragging the scatter plot. You should see the distribution of the bar plot change when selecting different intervals!" }, { "code": null, "e": 2122, "s": 2090, "text": "Code to produce the plot above:" }, { "code": null, "e": 2136, "s": 2122, "text": "Explanations:" }, { "code": null, "e": 2237, "s": 2136, "text": "x=\"count(parental_level_of_education):Q\": Count of each value in parental_level_of_education column." }, { "code": null, "e": 2346, "s": 2237, "text": "color=alt.Color(“parental_level_of_education:N”) : Apply colors to bars based on parental_level_of_education" }, { "code": null, "e": 2415, "s": 2346, "text": "transform_filter(brush) : Filter data based on the selected interval" }, { "code": null, "e": 2514, "s": 2415, "text": "With Altair’s Bindings feature, you can do many cool things to bring clarity to your plot such as:" }, { "code": null, "e": 2645, "s": 2514, "text": "Sometimes you might wish to zoom in on your histogram to get a more granular view of your histogram. That can be done with Altair." }, { "code": null, "e": 2688, "s": 2645, "text": "You can play with the chart yourself here:" }, { "code": null, "e": 2719, "s": 2688, "text": "Code to create the plot above:" }, { "code": null, "e": 2879, "s": 2719, "text": "You might also wish to understand the histogram by looking at which points fall in the selected interval of the histogram. That could also be done with Altair:" }, { "code": null, "e": 2922, "s": 2879, "text": "You can play with the chart yourself here:" }, { "code": null, "e": 2953, "s": 2922, "text": "Code to create the plot above:" }, { "code": null, "e": 3035, "s": 2953, "text": "You can also use Altair to apply multiple filters to your data points like below:" }, { "code": null, "e": 3068, "s": 3035, "text": "You can play with the plot here:" }, { "code": null, "e": 3092, "s": 3068, "text": "Code of the plot above:" }, { "code": null, "e": 3271, "s": 3092, "text": "I hope the code above doesn’t scare you! Many lines of the code above show what we already learned in the first section. Some new Altair’s objects that were not mentioned before:" }, { "code": null, "e": 3342, "s": 3271, "text": "alt.selection_single : Allow users to select only one option at a time" }, { "code": null, "e": 3385, "s": 3342, "text": "alt.binding_select : Create a dropdown bar" }, { "code": null, "e": 3427, "s": 3385, "text": "alt.binding_radio : Create a radio button" }, { "code": null, "e": 3663, "s": 3427, "text": "Congratulations! You have just learned how to bind multiple plots using Altair! Being able to link between multiple plots will bring much more clarity to your data analysis. Plus, you can impress your audience with these plots as well!" }, { "code": null, "e": 3728, "s": 3663, "text": "Feel free to play and fork the source code of this article here:" }, { "code": null, "e": 3739, "s": 3728, "text": "github.com" }, { "code": null, "e": 3899, "s": 3739, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
Autoencoders in Practice: Dimensionality Reduction and Image Denoising | by Ruben Winastwan | Towards Data Science
Let’s imagine ourselves creating a neural network based machine learning model. When we do so, most of the time we’re going to use it to do a classification task. This means that we train our neural network to predict the target y given the input features x. However, the ability of a neural network to create a lower-dimensional representation of our data in a non-linear fashion opens up a lot of possibilities. Now we can train our neural network to compress our data and then decompress them back to their original dimension. This is the basic concept of an autoencoder. In a nutshell, an autoencoder is a neural network based model to compress the data. Therefore, it has the ability to learn the compressed representation of our input data. In the early development of Deep Learning, autoencoder has been viewed as a solution to solve the problem of unsupervised learning. This is because an autoencoder doesn’t really need a labeled ground-truth for it to learn the data. However, it is important to note that an autoencoder itself is not a pure unsupervised learning technique. Autoencoder is a self-supervised learning technique, where the target that it needs to learn is generated from our input data. Let’s take a look at the code snippet below: model.fit(x=x, y=x) Instead of using the model to predict the ground-truth label, as we usually do with supervised models, we use an autoencoder model to reconstruct our original input data to be as similar as possible. Because of that, the point of training an autoencoder is to minimize the so-called reconstruction loss. The lower the reconstruction loss, the more similar the reconstruction of the input data can be generated by the model. In practice, you need two different functions to create an autoencoder model: an encoder and a decoder. These two functions are normally implemented with neural networks. It can be LSTM if you’re working on NLP use case, or Convolutional Neural Networks (CNN), if you’re working on Computer Vision use case. As you can see above, there are three components of an autoencoder: Encoder — The function to compress the data to their lower-dimensional representation. Bottleneck — This is also called a latent space, where our initial data are now represented in a lower dimension. Decoder — The function to decompress or reconstruct our low dimension data back to their initial dimension. Due to its encoder-decoder architecture, nowadays an autoencoder is mostly used in two of these domains: image denoising and dimensionality reduction for data visualization. In this article, let’s build an autoencoder to tackle these things. Before we start building an autoencoder, we need to load the data first. The data that we’re going to use is the Medical MNIST dataset. If you want to follow along, you can download the dataset here. There are 58954 medical images belonging to 6 classes: AbdomenCT, BreastMRI, CXR, ChestCT, Hand, HeadCT. After downloading the data, unzip the file and place it in the directory of your choice. You should then have a folder with the following structure: MedicalMNIST/ AbdomenCT/ BreastMRI/ CXR/ ChestCT/ Hand/ HeadCT/ The next thing that we should do is to split the file into training and test folder. To do this, we can use a library called split-folders. You can install it by typing the following command: pip install split-folders With this library, we can split our MedicalMNIST folder into training and test folder. We will allocate 80% of the data for training data and 20% for test data. If you run the code above, now you get a new folder called ‘ MedicalMNIST_splitted‘. Inside this folder, you’ll see two folders: ‘training’ folder and ‘val’ folder. Your folder now should have the following structure. MedicalMNIST_splitted/ train/ AbdomenCT/ BreastMRI/ CXR/ ChestCT/ Hand/ HeadCT/ val/ AbdomenCT/ BreastMRI/ CXR/ ChestCT/ Hand/ HeadCT/ Finally, we can generate our training and test data from these folders with image generator from TensorFlow. If you run the code above, you’ll get your training and test data together with their ground-truth labels. Now we are ready to build our autoencoder for dimensionality reduction and image denoising. When we’re working on our machine learning projects, we commonly run into a problem where we have a lot of input variables. This means two things: first, your machine learning model will be likely to suffer from overfitting problem and second, you need to allocate a whole lot amount of time to train the model. Dimensionality reduction is the technique that’ll save you from all of those problems. When dealing with a lot of input variables, it is often necessary to reduce the dimension of the data to capture the most valuable inputs among all of those input variables. Also, you can visualize your data and see how they occupy the latent space by lowering its dimension to two or three dimensions. There are two techniques that are commonly used to reduce the dimension of your data: PCA and t-SNE. However, autoencoders can be used as well for dimensionality reduction. In some cases, autoencoders perform even better than PCA because PCA can only learn linear transformation of the features. However, since autoencoders are built based on neural networks, they have the ability to learn the non-linear transformation of the features. This turns into a better reconstruction ability. Let’s say we have two features, x1 and x2. In the first row, they have a linear relationship and in the second row, they have a non-linear relationship. In the first row, since the two features have a linear relationship, then both PCA and autoencoders can accurately reconstruct the relationship between features in the latent space. Meanwhile, if the two features have a non-linear relationship, as shown in the second row, then autoencoders would be more suited to use since they have the ability to learn non-linear relationship between features. Now it’s time for us to build an autoencoder to reduce the dimension of our Medical MNIST images into two dimensions. After we reduce the dimension, we can visualize how our images occupy the latent space. Since our data are images, then we’re going to build an autoencoder consists of convolutional layers. As you already know, we need to create two functions to build an autoencoder: an encoder and a decoder. The encoder consists of three stacks of convolution layers before we flatten it and use a fully-connected layer. The final fully-connected layer consists of two nodes since we want to compress and project our image data into their 2D representation. Meanwhile, the decoder is basically the total opposite of our encoder since we want to reconstruct the 2D representation of our images back into their initial dimension. Next, we can start to compile and train our autoencoder. You can use binary cross-entropy, mean squared error, or mean absolute error as your loss function. In this example, I’m going to use binary cross-entropy as the loss function. Now since we have compressed our image data into their 2D representation, we can visualize them. To visualize the data, we can use Matplotlib and Seaborn library. And below is the resulting visualization. As you can see above, before we trained the autoencoder, our images are scattered in the latent space randomly, with almost no structure at all. However, we can see the self-supervised nature of an autoencoder after we trained it. Our images are mapped together based on their respective class. The images that belong to the same class are mapped close to each other, although we didn’t give the model the ground-truth label of our images during the training. This is because our autoencoder is trained to reconstruct our input images from their 2D representation. To reconstruct our images as accurately as possible, the autoencoder needs to map similar images together. However, it is important to note that you’re not going to see a strong mapping phenomenon like above in some of image datasets when you compress them into 2D. Your image dataset needs to have a strong underlying characteristic in between each class. If you have complex data like images of cats and dogs with different background, breed, or colors, and you try to compress them into 2D, two things will likely to happen: first, your encoder wouldn’t be able to properly create a representation of your images, resulting in random scatter points in the latent space. Second, your decoder wouldn’t be able to recover your image. Therefore, you need to compress your data in a higher dimension. Now we can also reconstruct our image back from its 2D representation with our autoencoder model. As we can see, our autoencoder is able to reconstruct the test images with a good result. You might be wondering, why the quality of the decompressed images looks worse than our original images? This is because of the ‘lossy’ characteristic of autoencoders, which means that the quality of the decompressed output will always be degraded compared to our input. The term denoising that I use here is the same as noise reduction. So, when we talk about noise reduction, we commonly talk about the technique to remove noise from a signal, either from an audio or an image. Noise in an image is commonly pretty visible with our naked eye and it can be very distracting. The grains in an image, as shown below, is the common form of noise in an image. The addition of digital grains makes it more difficult for our eyes to identify what kind of objects are shown in our image. Probably we need to squint our eyes to see the object clearly. With an autoencoder, we can remove the grains in our image such that we can see clearly the main objects in our image. We will use the same images that we’ve been using so far for this image denoising example. However, as our Medical MNIST dataset doesn’t have any noise, we can generate artificial random noise to the image easily with a few lines of Python code. Now if we take a look at the data, we can see that the grains are now apparent in our images. Now we can start to build our autoencoder model. Same as before, we’re going to build a convolutional autoencoder model. The encoder consists of three stacks of convolutional layers and we don’t need to flatten it this time. The decoder will be a total opposite of our encoder architecture. The architecture is very straightforward as below. Now we can compile and train our autoencoder model. As you can see below, we’re passing our noisy images to the encoder and let the autoencoder learn how to compress our noisy images and decompress them into a clean image. You can use binary cross-entropy, mean squared error, or mean absolute error as the loss function. In this example, I’m going to use binary cross-entropy. Let’s use our trained autoencoder to reconstruct our noisy images from the test set and let’s see if the model can reconstruct them into clean images. If you run the code above, you’ll get the following visualization. As you can see, now our autoencoder can be used to remove the noise in our Medical MNIST images effectively. Hopefully, this article helps you to understand the basic concept of an autoencoder and its common practical applications. It is also important to note that an autoencoder is a data-specific model. This means that an autoencoder will only be able to compress the data similar to what they have been trained on. If you train your autoencoder to compress medical images, your model will do a poor job to compress a handwritten digit image, although they have the same input dimensions. You can find the complete Notebook of this article here.
[ { "code": null, "e": 430, "s": 171, "text": "Let’s imagine ourselves creating a neural network based machine learning model. When we do so, most of the time we’re going to use it to do a classification task. This means that we train our neural network to predict the target y given the input features x." }, { "code": null, "e": 746, "s": 430, "text": "However, the ability of a neural network to create a lower-dimensional representation of our data in a non-linear fashion opens up a lot of possibilities. Now we can train our neural network to compress our data and then decompress them back to their original dimension. This is the basic concept of an autoencoder." }, { "code": null, "e": 918, "s": 746, "text": "In a nutshell, an autoencoder is a neural network based model to compress the data. Therefore, it has the ability to learn the compressed representation of our input data." }, { "code": null, "e": 1150, "s": 918, "text": "In the early development of Deep Learning, autoencoder has been viewed as a solution to solve the problem of unsupervised learning. This is because an autoencoder doesn’t really need a labeled ground-truth for it to learn the data." }, { "code": null, "e": 1429, "s": 1150, "text": "However, it is important to note that an autoencoder itself is not a pure unsupervised learning technique. Autoencoder is a self-supervised learning technique, where the target that it needs to learn is generated from our input data. Let’s take a look at the code snippet below:" }, { "code": null, "e": 1449, "s": 1429, "text": "model.fit(x=x, y=x)" }, { "code": null, "e": 1873, "s": 1449, "text": "Instead of using the model to predict the ground-truth label, as we usually do with supervised models, we use an autoencoder model to reconstruct our original input data to be as similar as possible. Because of that, the point of training an autoencoder is to minimize the so-called reconstruction loss. The lower the reconstruction loss, the more similar the reconstruction of the input data can be generated by the model." }, { "code": null, "e": 2181, "s": 1873, "text": "In practice, you need two different functions to create an autoencoder model: an encoder and a decoder. These two functions are normally implemented with neural networks. It can be LSTM if you’re working on NLP use case, or Convolutional Neural Networks (CNN), if you’re working on Computer Vision use case." }, { "code": null, "e": 2249, "s": 2181, "text": "As you can see above, there are three components of an autoencoder:" }, { "code": null, "e": 2336, "s": 2249, "text": "Encoder — The function to compress the data to their lower-dimensional representation." }, { "code": null, "e": 2450, "s": 2336, "text": "Bottleneck — This is also called a latent space, where our initial data are now represented in a lower dimension." }, { "code": null, "e": 2558, "s": 2450, "text": "Decoder — The function to decompress or reconstruct our low dimension data back to their initial dimension." }, { "code": null, "e": 2800, "s": 2558, "text": "Due to its encoder-decoder architecture, nowadays an autoencoder is mostly used in two of these domains: image denoising and dimensionality reduction for data visualization. In this article, let’s build an autoencoder to tackle these things." }, { "code": null, "e": 3000, "s": 2800, "text": "Before we start building an autoencoder, we need to load the data first. The data that we’re going to use is the Medical MNIST dataset. If you want to follow along, you can download the dataset here." }, { "code": null, "e": 3254, "s": 3000, "text": "There are 58954 medical images belonging to 6 classes: AbdomenCT, BreastMRI, CXR, ChestCT, Hand, HeadCT. After downloading the data, unzip the file and place it in the directory of your choice. You should then have a folder with the following structure:" }, { "code": null, "e": 3336, "s": 3254, "text": "MedicalMNIST/ AbdomenCT/ BreastMRI/ CXR/ ChestCT/ Hand/ HeadCT/" }, { "code": null, "e": 3528, "s": 3336, "text": "The next thing that we should do is to split the file into training and test folder. To do this, we can use a library called split-folders. You can install it by typing the following command:" }, { "code": null, "e": 3554, "s": 3528, "text": "pip install split-folders" }, { "code": null, "e": 3715, "s": 3554, "text": "With this library, we can split our MedicalMNIST folder into training and test folder. We will allocate 80% of the data for training data and 20% for test data." }, { "code": null, "e": 3933, "s": 3715, "text": "If you run the code above, now you get a new folder called ‘ MedicalMNIST_splitted‘. Inside this folder, you’ll see two folders: ‘training’ folder and ‘val’ folder. Your folder now should have the following structure." }, { "code": null, "e": 4120, "s": 3933, "text": "MedicalMNIST_splitted/ train/ AbdomenCT/ BreastMRI/ CXR/ ChestCT/ Hand/ HeadCT/ val/ AbdomenCT/ BreastMRI/ CXR/ ChestCT/ Hand/ HeadCT/" }, { "code": null, "e": 4229, "s": 4120, "text": "Finally, we can generate our training and test data from these folders with image generator from TensorFlow." }, { "code": null, "e": 4336, "s": 4229, "text": "If you run the code above, you’ll get your training and test data together with their ground-truth labels." }, { "code": null, "e": 4428, "s": 4336, "text": "Now we are ready to build our autoencoder for dimensionality reduction and image denoising." }, { "code": null, "e": 4740, "s": 4428, "text": "When we’re working on our machine learning projects, we commonly run into a problem where we have a lot of input variables. This means two things: first, your machine learning model will be likely to suffer from overfitting problem and second, you need to allocate a whole lot amount of time to train the model." }, { "code": null, "e": 5130, "s": 4740, "text": "Dimensionality reduction is the technique that’ll save you from all of those problems. When dealing with a lot of input variables, it is often necessary to reduce the dimension of the data to capture the most valuable inputs among all of those input variables. Also, you can visualize your data and see how they occupy the latent space by lowering its dimension to two or three dimensions." }, { "code": null, "e": 5303, "s": 5130, "text": "There are two techniques that are commonly used to reduce the dimension of your data: PCA and t-SNE. However, autoencoders can be used as well for dimensionality reduction." }, { "code": null, "e": 5617, "s": 5303, "text": "In some cases, autoencoders perform even better than PCA because PCA can only learn linear transformation of the features. However, since autoencoders are built based on neural networks, they have the ability to learn the non-linear transformation of the features. This turns into a better reconstruction ability." }, { "code": null, "e": 5770, "s": 5617, "text": "Let’s say we have two features, x1 and x2. In the first row, they have a linear relationship and in the second row, they have a non-linear relationship." }, { "code": null, "e": 5952, "s": 5770, "text": "In the first row, since the two features have a linear relationship, then both PCA and autoencoders can accurately reconstruct the relationship between features in the latent space." }, { "code": null, "e": 6168, "s": 5952, "text": "Meanwhile, if the two features have a non-linear relationship, as shown in the second row, then autoencoders would be more suited to use since they have the ability to learn non-linear relationship between features." }, { "code": null, "e": 6374, "s": 6168, "text": "Now it’s time for us to build an autoencoder to reduce the dimension of our Medical MNIST images into two dimensions. After we reduce the dimension, we can visualize how our images occupy the latent space." }, { "code": null, "e": 6580, "s": 6374, "text": "Since our data are images, then we’re going to build an autoencoder consists of convolutional layers. As you already know, we need to create two functions to build an autoencoder: an encoder and a decoder." }, { "code": null, "e": 6830, "s": 6580, "text": "The encoder consists of three stacks of convolution layers before we flatten it and use a fully-connected layer. The final fully-connected layer consists of two nodes since we want to compress and project our image data into their 2D representation." }, { "code": null, "e": 7000, "s": 6830, "text": "Meanwhile, the decoder is basically the total opposite of our encoder since we want to reconstruct the 2D representation of our images back into their initial dimension." }, { "code": null, "e": 7234, "s": 7000, "text": "Next, we can start to compile and train our autoencoder. You can use binary cross-entropy, mean squared error, or mean absolute error as your loss function. In this example, I’m going to use binary cross-entropy as the loss function." }, { "code": null, "e": 7397, "s": 7234, "text": "Now since we have compressed our image data into their 2D representation, we can visualize them. To visualize the data, we can use Matplotlib and Seaborn library." }, { "code": null, "e": 7439, "s": 7397, "text": "And below is the resulting visualization." }, { "code": null, "e": 7670, "s": 7439, "text": "As you can see above, before we trained the autoencoder, our images are scattered in the latent space randomly, with almost no structure at all. However, we can see the self-supervised nature of an autoencoder after we trained it." }, { "code": null, "e": 8111, "s": 7670, "text": "Our images are mapped together based on their respective class. The images that belong to the same class are mapped close to each other, although we didn’t give the model the ground-truth label of our images during the training. This is because our autoencoder is trained to reconstruct our input images from their 2D representation. To reconstruct our images as accurately as possible, the autoencoder needs to map similar images together." }, { "code": null, "e": 8361, "s": 8111, "text": "However, it is important to note that you’re not going to see a strong mapping phenomenon like above in some of image datasets when you compress them into 2D. Your image dataset needs to have a strong underlying characteristic in between each class." }, { "code": null, "e": 8803, "s": 8361, "text": "If you have complex data like images of cats and dogs with different background, breed, or colors, and you try to compress them into 2D, two things will likely to happen: first, your encoder wouldn’t be able to properly create a representation of your images, resulting in random scatter points in the latent space. Second, your decoder wouldn’t be able to recover your image. Therefore, you need to compress your data in a higher dimension." }, { "code": null, "e": 8901, "s": 8803, "text": "Now we can also reconstruct our image back from its 2D representation with our autoencoder model." }, { "code": null, "e": 8991, "s": 8901, "text": "As we can see, our autoencoder is able to reconstruct the test images with a good result." }, { "code": null, "e": 9262, "s": 8991, "text": "You might be wondering, why the quality of the decompressed images looks worse than our original images? This is because of the ‘lossy’ characteristic of autoencoders, which means that the quality of the decompressed output will always be degraded compared to our input." }, { "code": null, "e": 9471, "s": 9262, "text": "The term denoising that I use here is the same as noise reduction. So, when we talk about noise reduction, we commonly talk about the technique to remove noise from a signal, either from an audio or an image." }, { "code": null, "e": 9648, "s": 9471, "text": "Noise in an image is commonly pretty visible with our naked eye and it can be very distracting. The grains in an image, as shown below, is the common form of noise in an image." }, { "code": null, "e": 9955, "s": 9648, "text": "The addition of digital grains makes it more difficult for our eyes to identify what kind of objects are shown in our image. Probably we need to squint our eyes to see the object clearly. With an autoencoder, we can remove the grains in our image such that we can see clearly the main objects in our image." }, { "code": null, "e": 10201, "s": 9955, "text": "We will use the same images that we’ve been using so far for this image denoising example. However, as our Medical MNIST dataset doesn’t have any noise, we can generate artificial random noise to the image easily with a few lines of Python code." }, { "code": null, "e": 10295, "s": 10201, "text": "Now if we take a look at the data, we can see that the grains are now apparent in our images." }, { "code": null, "e": 10520, "s": 10295, "text": "Now we can start to build our autoencoder model. Same as before, we’re going to build a convolutional autoencoder model. The encoder consists of three stacks of convolutional layers and we don’t need to flatten it this time." }, { "code": null, "e": 10637, "s": 10520, "text": "The decoder will be a total opposite of our encoder architecture. The architecture is very straightforward as below." }, { "code": null, "e": 11015, "s": 10637, "text": "Now we can compile and train our autoencoder model. As you can see below, we’re passing our noisy images to the encoder and let the autoencoder learn how to compress our noisy images and decompress them into a clean image. You can use binary cross-entropy, mean squared error, or mean absolute error as the loss function. In this example, I’m going to use binary cross-entropy." }, { "code": null, "e": 11166, "s": 11015, "text": "Let’s use our trained autoencoder to reconstruct our noisy images from the test set and let’s see if the model can reconstruct them into clean images." }, { "code": null, "e": 11233, "s": 11166, "text": "If you run the code above, you’ll get the following visualization." }, { "code": null, "e": 11342, "s": 11233, "text": "As you can see, now our autoencoder can be used to remove the noise in our Medical MNIST images effectively." }, { "code": null, "e": 11465, "s": 11342, "text": "Hopefully, this article helps you to understand the basic concept of an autoencoder and its common practical applications." }, { "code": null, "e": 11826, "s": 11465, "text": "It is also important to note that an autoencoder is a data-specific model. This means that an autoencoder will only be able to compress the data similar to what they have been trained on. If you train your autoencoder to compress medical images, your model will do a poor job to compress a handwritten digit image, although they have the same input dimensions." } ]
What Is the Best Input Pipeline to Train Image Classification Models with tf.keras? | by Yan Gobeil | Towards Data Science
When we start learning how to build deep neural networks with Keras, the first method we use to input data is simply loading it into NumPy arrays. At some point, especially when working with images, the data is too large to fit in memory so we need an alternative to arrays. From my experience, the go-to solution to that problem is to use the tool built into Keras called ImageDataGenerator. This creates a Python generator that feeds the data gradually to the neural network without keeping it into memory. Additionally, it includes data augmentation features that make it a very useful tool. This could be the end of the story, but after working on image classification for some time now, I found out about new methods to create image input pipelines that are claimed to be more efficient. The goal of this article is to run a few experiments to figure out the best method out there. The main contestants will be: tf.keras.preprocessing.image.ImageDataGenerator tf.keras.preprocessing.image_dataset_from_directory tf.data.Dataset with image files tf.data.Dataset with TFRecords The code for all the experiments can be found in this Colab notebook. To have a fair comparison of the pipelines, they will be used to perform exactly the same task: fine tune an EfficienNetB3 model to classify images in two different datasets. Before describing the datasets, here is the training pipeline that is used, strongly inspired by this tutorial. This code simply takes a pretrained EfficientNetB3 and adds a classification layer on top of it with the right number of neurons. This model is then trained for 5 epochs with a batch size of 32 with each tested method. The experiments are done on Google Colab, with the hardware available with Colab Pro. The version of TensorFlow used is 2.4.1. The first dataset used to test the pipelines is a subset of the Open Images Dataset [1] consisting only of fruit images. The second one is the Stanford Dogs Dataset [2–3] with images of various dog breeds. Here is a summary of the two datasets: The datasets are pretty different since one has a small number of classes with less images that are larger in size. Code to download and prepare these datasets is presented in the colab. Since the rest of this article spends a good amount of time explaining the different input pipelines and some people may only care about the conclusions, here is a summary of all the experiments: The numbers clearly show that the go-to solution ImageDataGenerator is far from being optimal in terms of speed. The only reason to keep using it could be because of how simple data augmentation is with this method. It is however not that hard to do with the other methods, and could be worth it given the big improvement in speed. In my opinion, image_dataset_from_directory should be the new go-to because it is not more complicated that the old method and is clearly faster. Building our own input pipeline using tf.data.Dataset improves speed a bit but is also a bit more complicated so to use it or not is a personal choice. Concerning TFRecords, it seems that if one is not working with TPUs they are not necessary since working directly with the image files makes no difference in performance. The optimal solution seems to be using TFRecords with a TPU and given the increase in speed it is worth the extra trouble. The drop in accuracy comes simply from the fact that different hyperparameter combinations are efficient with the TPUs but the tests used the same as the GPU. Using the right hyperparameters lead to similar accuracies than with the other methods. Let’s now jump into the details of each method, starting with a review of the reigning champion, which is very simple. The Keras method takes the data stored into a folder, with each subfolder corresponding to an individual class. In this example, it resizes the images and creates batches automatically. The labels are generated from the subfolder names. The ‘sparse’ format is used to have labels of the form 0,1,2,3,... because the sparse metrics are used in the model building. The main advantages of this method are its extreme simplicity and the fact that data augmentation can be done simply by specifying the transformations (rotation, flip, zoom, etc) in the arguments. The next option is also pretty simple and is included in Keras as well. The format of the data is the same as for the first method, the images are again resized and batched, and the labels are generated automatically. There are however no options to do data augmentation on the fly. The main difference in this method is that the output is not a python generator but a tf.data.Dataset object. This allows it to fit nicely with the rest of the pipelining tools discussed below. For example, a prefetch of the data is done here to help make the calculations faster. Any form of data augmentation done with TensorFlow can be done on this kind of dataset. It is a bit less simple but much more customizable. TensorFlow recommends using tf.data when working with the library to achieve optimal performance. This is a set of tools to create a dataset made of tensors, apply transformations to the data and iterate over the dataset to train neural networks. It works with any type of data, like tables, images or text. The data can be imported in multiple ways. The most common ones are NumPy arrays, python generators, CSVs, TFRecords and strings. Much more detail can be found on Tensorflow’s website. Let’s start by showing the code used for this specific case of image classification, and then explain how it works. The first step that is done here is to format the data needed correctly before feeding it to TensorFlow. The format that is used here is a filepath and an integer label for each image. This processing is done in lines 19–22. It is extremely important to not forget to shuffle the list of images because the performance of the model would be greatly affected. Trust me... Note: An alternate method is to directly get the list of files using tf.data.Dataset.list_files . The problem with this is that the labels must be extracted using TensorFlow operations, which is very inefficient. This slows down the pipeline by a lot so it is preferred to get the labels with pure python code. The labels part is simple because the list of labels is converted to a dataset using the method from_tensor_slices , which converts any tensor-like object (numpy array, list, dictionary). The list of filenames is also converted to a dataset using the same method. The next step is to apply the parse_image function to the filenames dataset using the map method, which applies a TensorFlow function to all the elements of a dataset. This particular function loads the image from the file, converts is to RGB format if necessary and resizes it. The num_parallel_calls argument is set to be fixed automatically by Tensorflow to increase speed as much as possible. Once the two parts of the dataset are finished, they are combined using the zip method, which is similar to the python function with the same name. The final step is to make sure the dataset can be iterated over correctly to train a neural network. This is done with the configure_for_performance function, which is applied directly to the whole dataset, so no need to use map . The first part of the function does a shuffle. The goal of this one is to take the next X images, where X is the buffer size, and mix them every time we pass over the dataset, This ensures that the data is shuffled differently at every epoch of the training, but since the buffer size has to be small for performance sake, it does not replace the original shuffling of the full dataset. The data is then separated in batches and then repeated forever. The last step is to prefetch some data, which preloads the data to be used in the future, to help with performance. The output of this whole pipeline is a dataset made of tensors. To help visualizing it, we can iterate over it with the following method: for image, label in ds.take(1): print(image.numpy()) print(label.numpy()) The data is in tensor form so it has to be converted to usual arrays for simplicity. It is important to understand that even if one element is taken from the dataset, there are 32 images loaded because an element in this case corresponds to a batch. This dataset can be used directly to train a neural network, as was done with the other methods. The only new (and very important) thing is the steps_per_epoch argument. Since the dataset was made to repeat indefinitely, TensorFlow needs to know how many steps correspond to one epoch. This is basically the total number of images divided by the batch size, rounded up since the last batch is typically not complete. As mentioned above, doing data augmentation is not hard with tf.data . The only extra step is to apply a new TensorFlow function, like tf.image.flip_left_right , to the resulting dataset. This can be customized at will, as discussed here. With a small enough dataset, the cache method makes the training extra fast because the data is saved in memory after the first epoch. For larger datasets, it may be possible to cache the data to a file, or use something called a snapshot, but I didn’t explore any of those. The final complexity jump in this chain of input pipelines involves saving the images into TensorFlow Record format. This is a file format that plays especially well with TensorFlow and, since it stores the objects in binary format, training a model goes faster, especially for large datasets. This section will describe the specifics for image classification, but the TensorFlow page is clear about how TFRecords work in general. Here is the code used to transform an image dataset into TFRecords. The majority of the make_tfrecords function is very similar to the data preparation step used before. The data consisting of filepaths and integer labels, randomized, is found using simple python code. The only difference is that the full image is loaded to be saved in the TFRecords. The TFRecordWriter method is used to write the files. The only major addition needed to create TFRecords is in the serialize_example function. Each data point has to be transformed into Features, stored in a dictionary (lines 7–10), which are then transformed into an Example (line 12), that is finally written into a String (line 13). This is what the TFRecord files contain. The process seems complicated at first, but is actually pretty much the same for all possible cases. The advantages of this way of working are numerous. All this processing has to be done only once and the data is ready for any training in the future. It is also easier to share, with fewer files of smaller sizes. Transformations like resizing can be done before and saved for later training, which can increase the speed. For larger datasets, the TFRecords can be split into multiple smaller files, called shards, to make the training even faster. Once the tf.data.Dataset section above is understood, reading TFRecords is easy to understand. Indeed the process is almost exactly the same. The data is loaded from TFRecords files instead of from image files, but the subsequent processing is the same. The dataset is first initialized in read_dataset by reading the TFRecords file(s) with the method TFRecordDataset . The _parse_image_funtion is then applied to convert the content of the TFRecords back to images and labels. This is done in lines 2–7, where the dictionary used to create the TFRecords is used to tell TensorFlow what the contents are supposed to correspond to. The rest of the steps is the exact same processing as before. A small detail that is introduced here because it is necessary for the next section appears in the batching step. The extra argument drop_remainder is used to drop the last batch if it is not full. This means that there is in general one less step to do in order to finish an epoch, which has to be changed in the steps_per_epoch argument of the training part. In my opinion, the main reason why it’s worth getting familiar with TFRecords is to be able to use Colab’s free TPUs. These are made to be much faster than GPUs but are more complicated to use. It is not as simple as switching the runtime so I describe here how to do it. It is not necessary to use TFRecords, but is highly recommended. The first roadblock is that when running on a TPU, TensorFlow 2 cannot read local files. This problem is fixed by saving the data in Google Cloud Storage. Every Google account can store a good amount of data on there for free, so it’s not much of a problem. It is also surprisingly simple to save data on GCS when using Colab and TensorFlow. The only special step needed is to authenticate your Google account. If your account is authenticated, using the exact same function as before to make the TFRecords but with a GCS bucket link (of the form gs://bucket-name/path) does the trick. TensorFlow is smart enough to recognize that the path is from GCS and knows how to read and save the data there. One caveat is that saving the data cannot be done on the TPU since local files are necessary. Saving the data has to be done with a CPU/GPU and then it’s time to switch to a TPU for training. Apart from the data storage, the only major difference when training with a TPU is that a small bit of code needs to be added to the pipeline (lines 10–15). For some reason, the batches have to be full to use a TPU so this is why the drop_remainder argument was used above. It is also noteworthy that much larger batch sizes are recommended when working with a TPU. These large batch sizes would make a GPU crash, but actually improve the performance of TPUs. A similar thing can be said about other hyperparameters. TPUs are different beasts, so different combinations of hyperparameters to the ones used with CPU/GPU are normally optimal. The conclusions of the experiments are already discussed at the top so before finishing I want to emphasize a few things that I learned during the whole process. The first one is the profiler that is now part of Tensorboard. This is a very interesting tool that helps find the bottlenecks in a training pipeline. This is how I figured out that I was doing something wrong when I tried to convert the image labels using TensorFlow functions. This specific step in the data pipeline was taking 73% of the total training time, which is incredibly high, so I found a way to fix it. The training time dropped from above 200 seconds per epoch to just 45 for the dogs dataset. Without the profiler, I would have had no idea where the problem was. Another detail that seemed to make a good difference, especially when working with a TPU, is to parallelize the map method. Comparing with other possible improvements, this was by far the most efficient one. Next, as mentioned above, shuffling the data is extremely important. This is related more to the math behind neural network training than with data pipelines, but I saw an increase of 10 accuracy points just by shuffling the data correctly. Finally, one detail not mentioned anywhere in the article concerns the normalization of the data. Indeed it is common to divide an image’s pixels by 255 to only have values between 0 and 1 when training. In this case, it however looks like the normalization step is included in the EfficientNetB3 model itself, so the input must be raw pixels. As I saw before realizing this, this small detail makes a huge difference in performance! [1] Kuznetsova, A., Rom, H., Alldrin, N. et al. The Open Images Dataset V4. Int J Comput Vis 128, 1956–1981 (2020). https://doi.org/10.1007/s11263-020-01316-z [2] Aditya Khosla, Nityananda Jayadevaprakash, Bangpeng Yao and Li Fei-Fei. Novel dataset for Fine-Grained Image Categorization. First Workshop on Fine-Grained Visual Categorization (FGVC), IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2011. [3] J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li and L. Fei-Fei, ImageNet: A Large-Scale Hierarchical Image Database. IEEE Computer Vision and Pattern Recognition (CVPR), 2009.
[ { "code": null, "e": 766, "s": 171, "text": "When we start learning how to build deep neural networks with Keras, the first method we use to input data is simply loading it into NumPy arrays. At some point, especially when working with images, the data is too large to fit in memory so we need an alternative to arrays. From my experience, the go-to solution to that problem is to use the tool built into Keras called ImageDataGenerator. This creates a Python generator that feeds the data gradually to the neural network without keeping it into memory. Additionally, it includes data augmentation features that make it a very useful tool." }, { "code": null, "e": 1088, "s": 766, "text": "This could be the end of the story, but after working on image classification for some time now, I found out about new methods to create image input pipelines that are claimed to be more efficient. The goal of this article is to run a few experiments to figure out the best method out there. The main contestants will be:" }, { "code": null, "e": 1136, "s": 1088, "text": "tf.keras.preprocessing.image.ImageDataGenerator" }, { "code": null, "e": 1188, "s": 1136, "text": "tf.keras.preprocessing.image_dataset_from_directory" }, { "code": null, "e": 1221, "s": 1188, "text": "tf.data.Dataset with image files" }, { "code": null, "e": 1252, "s": 1221, "text": "tf.data.Dataset with TFRecords" }, { "code": null, "e": 1322, "s": 1252, "text": "The code for all the experiments can be found in this Colab notebook." }, { "code": null, "e": 1609, "s": 1322, "text": "To have a fair comparison of the pipelines, they will be used to perform exactly the same task: fine tune an EfficienNetB3 model to classify images in two different datasets. Before describing the datasets, here is the training pipeline that is used, strongly inspired by this tutorial." }, { "code": null, "e": 1955, "s": 1609, "text": "This code simply takes a pretrained EfficientNetB3 and adds a classification layer on top of it with the right number of neurons. This model is then trained for 5 epochs with a batch size of 32 with each tested method. The experiments are done on Google Colab, with the hardware available with Colab Pro. The version of TensorFlow used is 2.4.1." }, { "code": null, "e": 2200, "s": 1955, "text": "The first dataset used to test the pipelines is a subset of the Open Images Dataset [1] consisting only of fruit images. The second one is the Stanford Dogs Dataset [2–3] with images of various dog breeds. Here is a summary of the two datasets:" }, { "code": null, "e": 2387, "s": 2200, "text": "The datasets are pretty different since one has a small number of classes with less images that are larger in size. Code to download and prepare these datasets is presented in the colab." }, { "code": null, "e": 2583, "s": 2387, "text": "Since the rest of this article spends a good amount of time explaining the different input pipelines and some people may only care about the conclusions, here is a summary of all the experiments:" }, { "code": null, "e": 2915, "s": 2583, "text": "The numbers clearly show that the go-to solution ImageDataGenerator is far from being optimal in terms of speed. The only reason to keep using it could be because of how simple data augmentation is with this method. It is however not that hard to do with the other methods, and could be worth it given the big improvement in speed." }, { "code": null, "e": 3061, "s": 2915, "text": "In my opinion, image_dataset_from_directory should be the new go-to because it is not more complicated that the old method and is clearly faster." }, { "code": null, "e": 3213, "s": 3061, "text": "Building our own input pipeline using tf.data.Dataset improves speed a bit but is also a bit more complicated so to use it or not is a personal choice." }, { "code": null, "e": 3384, "s": 3213, "text": "Concerning TFRecords, it seems that if one is not working with TPUs they are not necessary since working directly with the image files makes no difference in performance." }, { "code": null, "e": 3754, "s": 3384, "text": "The optimal solution seems to be using TFRecords with a TPU and given the increase in speed it is worth the extra trouble. The drop in accuracy comes simply from the fact that different hyperparameter combinations are efficient with the TPUs but the tests used the same as the GPU. Using the right hyperparameters lead to similar accuracies than with the other methods." }, { "code": null, "e": 3873, "s": 3754, "text": "Let’s now jump into the details of each method, starting with a review of the reigning champion, which is very simple." }, { "code": null, "e": 4236, "s": 3873, "text": "The Keras method takes the data stored into a folder, with each subfolder corresponding to an individual class. In this example, it resizes the images and creates batches automatically. The labels are generated from the subfolder names. The ‘sparse’ format is used to have labels of the form 0,1,2,3,... because the sparse metrics are used in the model building." }, { "code": null, "e": 4433, "s": 4236, "text": "The main advantages of this method are its extreme simplicity and the fact that data augmentation can be done simply by specifying the transformations (rotation, flip, zoom, etc) in the arguments." }, { "code": null, "e": 4505, "s": 4433, "text": "The next option is also pretty simple and is included in Keras as well." }, { "code": null, "e": 4716, "s": 4505, "text": "The format of the data is the same as for the first method, the images are again resized and batched, and the labels are generated automatically. There are however no options to do data augmentation on the fly." }, { "code": null, "e": 5137, "s": 4716, "text": "The main difference in this method is that the output is not a python generator but a tf.data.Dataset object. This allows it to fit nicely with the rest of the pipelining tools discussed below. For example, a prefetch of the data is done here to help make the calculations faster. Any form of data augmentation done with TensorFlow can be done on this kind of dataset. It is a bit less simple but much more customizable." }, { "code": null, "e": 5630, "s": 5137, "text": "TensorFlow recommends using tf.data when working with the library to achieve optimal performance. This is a set of tools to create a dataset made of tensors, apply transformations to the data and iterate over the dataset to train neural networks. It works with any type of data, like tables, images or text. The data can be imported in multiple ways. The most common ones are NumPy arrays, python generators, CSVs, TFRecords and strings. Much more detail can be found on Tensorflow’s website." }, { "code": null, "e": 5746, "s": 5630, "text": "Let’s start by showing the code used for this specific case of image classification, and then explain how it works." }, { "code": null, "e": 6117, "s": 5746, "text": "The first step that is done here is to format the data needed correctly before feeding it to TensorFlow. The format that is used here is a filepath and an integer label for each image. This processing is done in lines 19–22. It is extremely important to not forget to shuffle the list of images because the performance of the model would be greatly affected. Trust me..." }, { "code": null, "e": 6428, "s": 6117, "text": "Note: An alternate method is to directly get the list of files using tf.data.Dataset.list_files . The problem with this is that the labels must be extracted using TensorFlow operations, which is very inefficient. This slows down the pipeline by a lot so it is preferred to get the labels with pure python code." }, { "code": null, "e": 6692, "s": 6428, "text": "The labels part is simple because the list of labels is converted to a dataset using the method from_tensor_slices , which converts any tensor-like object (numpy array, list, dictionary). The list of filenames is also converted to a dataset using the same method." }, { "code": null, "e": 7089, "s": 6692, "text": "The next step is to apply the parse_image function to the filenames dataset using the map method, which applies a TensorFlow function to all the elements of a dataset. This particular function loads the image from the file, converts is to RGB format if necessary and resizes it. The num_parallel_calls argument is set to be fixed automatically by Tensorflow to increase speed as much as possible." }, { "code": null, "e": 7237, "s": 7089, "text": "Once the two parts of the dataset are finished, they are combined using the zip method, which is similar to the python function with the same name." }, { "code": null, "e": 8036, "s": 7237, "text": "The final step is to make sure the dataset can be iterated over correctly to train a neural network. This is done with the configure_for_performance function, which is applied directly to the whole dataset, so no need to use map . The first part of the function does a shuffle. The goal of this one is to take the next X images, where X is the buffer size, and mix them every time we pass over the dataset, This ensures that the data is shuffled differently at every epoch of the training, but since the buffer size has to be small for performance sake, it does not replace the original shuffling of the full dataset. The data is then separated in batches and then repeated forever. The last step is to prefetch some data, which preloads the data to be used in the future, to help with performance." }, { "code": null, "e": 8174, "s": 8036, "text": "The output of this whole pipeline is a dataset made of tensors. To help visualizing it, we can iterate over it with the following method:" }, { "code": null, "e": 8254, "s": 8174, "text": "for image, label in ds.take(1): print(image.numpy()) print(label.numpy())" }, { "code": null, "e": 8504, "s": 8254, "text": "The data is in tensor form so it has to be converted to usual arrays for simplicity. It is important to understand that even if one element is taken from the dataset, there are 32 images loaded because an element in this case corresponds to a batch." }, { "code": null, "e": 8601, "s": 8504, "text": "This dataset can be used directly to train a neural network, as was done with the other methods." }, { "code": null, "e": 8921, "s": 8601, "text": "The only new (and very important) thing is the steps_per_epoch argument. Since the dataset was made to repeat indefinitely, TensorFlow needs to know how many steps correspond to one epoch. This is basically the total number of images divided by the batch size, rounded up since the last batch is typically not complete." }, { "code": null, "e": 9160, "s": 8921, "text": "As mentioned above, doing data augmentation is not hard with tf.data . The only extra step is to apply a new TensorFlow function, like tf.image.flip_left_right , to the resulting dataset. This can be customized at will, as discussed here." }, { "code": null, "e": 9435, "s": 9160, "text": "With a small enough dataset, the cache method makes the training extra fast because the data is saved in memory after the first epoch. For larger datasets, it may be possible to cache the data to a file, or use something called a snapshot, but I didn’t explore any of those." }, { "code": null, "e": 9866, "s": 9435, "text": "The final complexity jump in this chain of input pipelines involves saving the images into TensorFlow Record format. This is a file format that plays especially well with TensorFlow and, since it stores the objects in binary format, training a model goes faster, especially for large datasets. This section will describe the specifics for image classification, but the TensorFlow page is clear about how TFRecords work in general." }, { "code": null, "e": 9934, "s": 9866, "text": "Here is the code used to transform an image dataset into TFRecords." }, { "code": null, "e": 10273, "s": 9934, "text": "The majority of the make_tfrecords function is very similar to the data preparation step used before. The data consisting of filepaths and integer labels, randomized, is found using simple python code. The only difference is that the full image is loaded to be saved in the TFRecords. The TFRecordWriter method is used to write the files." }, { "code": null, "e": 10697, "s": 10273, "text": "The only major addition needed to create TFRecords is in the serialize_example function. Each data point has to be transformed into Features, stored in a dictionary (lines 7–10), which are then transformed into an Example (line 12), that is finally written into a String (line 13). This is what the TFRecord files contain. The process seems complicated at first, but is actually pretty much the same for all possible cases." }, { "code": null, "e": 11146, "s": 10697, "text": "The advantages of this way of working are numerous. All this processing has to be done only once and the data is ready for any training in the future. It is also easier to share, with fewer files of smaller sizes. Transformations like resizing can be done before and saved for later training, which can increase the speed. For larger datasets, the TFRecords can be split into multiple smaller files, called shards, to make the training even faster." }, { "code": null, "e": 11400, "s": 11146, "text": "Once the tf.data.Dataset section above is understood, reading TFRecords is easy to understand. Indeed the process is almost exactly the same. The data is loaded from TFRecords files instead of from image files, but the subsequent processing is the same." }, { "code": null, "e": 11839, "s": 11400, "text": "The dataset is first initialized in read_dataset by reading the TFRecords file(s) with the method TFRecordDataset . The _parse_image_funtion is then applied to convert the content of the TFRecords back to images and labels. This is done in lines 2–7, where the dictionary used to create the TFRecords is used to tell TensorFlow what the contents are supposed to correspond to. The rest of the steps is the exact same processing as before." }, { "code": null, "e": 12200, "s": 11839, "text": "A small detail that is introduced here because it is necessary for the next section appears in the batching step. The extra argument drop_remainder is used to drop the last batch if it is not full. This means that there is in general one less step to do in order to finish an epoch, which has to be changed in the steps_per_epoch argument of the training part." }, { "code": null, "e": 12537, "s": 12200, "text": "In my opinion, the main reason why it’s worth getting familiar with TFRecords is to be able to use Colab’s free TPUs. These are made to be much faster than GPUs but are more complicated to use. It is not as simple as switching the runtime so I describe here how to do it. It is not necessary to use TFRecords, but is highly recommended." }, { "code": null, "e": 12948, "s": 12537, "text": "The first roadblock is that when running on a TPU, TensorFlow 2 cannot read local files. This problem is fixed by saving the data in Google Cloud Storage. Every Google account can store a good amount of data on there for free, so it’s not much of a problem. It is also surprisingly simple to save data on GCS when using Colab and TensorFlow. The only special step needed is to authenticate your Google account." }, { "code": null, "e": 13428, "s": 12948, "text": "If your account is authenticated, using the exact same function as before to make the TFRecords but with a GCS bucket link (of the form gs://bucket-name/path) does the trick. TensorFlow is smart enough to recognize that the path is from GCS and knows how to read and save the data there. One caveat is that saving the data cannot be done on the TPU since local files are necessary. Saving the data has to be done with a CPU/GPU and then it’s time to switch to a TPU for training." }, { "code": null, "e": 13585, "s": 13428, "text": "Apart from the data storage, the only major difference when training with a TPU is that a small bit of code needs to be added to the pipeline (lines 10–15)." }, { "code": null, "e": 14069, "s": 13585, "text": "For some reason, the batches have to be full to use a TPU so this is why the drop_remainder argument was used above. It is also noteworthy that much larger batch sizes are recommended when working with a TPU. These large batch sizes would make a GPU crash, but actually improve the performance of TPUs. A similar thing can be said about other hyperparameters. TPUs are different beasts, so different combinations of hyperparameters to the ones used with CPU/GPU are normally optimal." }, { "code": null, "e": 14809, "s": 14069, "text": "The conclusions of the experiments are already discussed at the top so before finishing I want to emphasize a few things that I learned during the whole process. The first one is the profiler that is now part of Tensorboard. This is a very interesting tool that helps find the bottlenecks in a training pipeline. This is how I figured out that I was doing something wrong when I tried to convert the image labels using TensorFlow functions. This specific step in the data pipeline was taking 73% of the total training time, which is incredibly high, so I found a way to fix it. The training time dropped from above 200 seconds per epoch to just 45 for the dogs dataset. Without the profiler, I would have had no idea where the problem was." }, { "code": null, "e": 15017, "s": 14809, "text": "Another detail that seemed to make a good difference, especially when working with a TPU, is to parallelize the map method. Comparing with other possible improvements, this was by far the most efficient one." }, { "code": null, "e": 15258, "s": 15017, "text": "Next, as mentioned above, shuffling the data is extremely important. This is related more to the math behind neural network training than with data pipelines, but I saw an increase of 10 accuracy points just by shuffling the data correctly." }, { "code": null, "e": 15692, "s": 15258, "text": "Finally, one detail not mentioned anywhere in the article concerns the normalization of the data. Indeed it is common to divide an image’s pixels by 255 to only have values between 0 and 1 when training. In this case, it however looks like the normalization step is included in the EfficientNetB3 model itself, so the input must be raw pixels. As I saw before realizing this, this small detail makes a huge difference in performance!" }, { "code": null, "e": 15851, "s": 15692, "text": "[1] Kuznetsova, A., Rom, H., Alldrin, N. et al. The Open Images Dataset V4. Int J Comput Vis 128, 1956–1981 (2020). https://doi.org/10.1007/s11263-020-01316-z" }, { "code": null, "e": 16114, "s": 15851, "text": "[2] Aditya Khosla, Nityananda Jayadevaprakash, Bangpeng Yao and Li Fei-Fei. Novel dataset for Fine-Grained Image Categorization. First Workshop on Fine-Grained Visual Categorization (FGVC), IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2011." } ]
How To Deal With Imbalanced Classification, Without Re-balancing the Data | by David B Rosen (PhD) | Towards Data Science
In machine learning, when building a classification model with data having far more instances of one class than another, the initial default classifier is often unsatisfactory because it classifies almost every case as the majority class. Many articles show you how you could use oversampling (e.g. SMOTE) or sometimes undersampling or simply class-based sample weighting to retrain the model on “rebalanced” data, but this isn’t always necessary. Here we aim instead to show how much you can do without balancing the data or retraining the model. We do this by simply adjusting the the threshold for which we say “Class 1” when the model’s predicted probability of Class 1 is above it in two-class classification, rather than naïvely using the default classification rule which chooses which ever class is predicted to be most probable (probability threshold of 0.5). We will see how this gives you the flexibility to make any desired trade-off between false positive and false negative classifications while avoiding problems created by rebalancing the data. We will use the credit card fraud identification data set from Kaggle to illustrate. Each row of the data set represents a credit card transaction, with the target variable Class==0 indicating a legitimate transaction and Class==1 indicating that the transaction turned out to be a fraud. There are 284,807 transactions, of which only 492 (0.173%) are frauds — very imbalanced indeed. We will use a gradient boosting classifier because these often give good results. Specifically Scikit-Learn’s new HistGradientBoostingClassifier because it is much faster than their original GradientBoostingClassifier when the data set is relatively large like this one. First let’s import some libraries and read in the data set. import numpy as npimport pandas as pdfrom sklearn import model_selection, metricsfrom sklearn.experimental import enable_hist_gradient_boostingfrom sklearn.ensemble import HistGradientBoostingClassifierdf=pd.read_csv('creditcard.csv')df.info() V1 through V28 (from a principal components analysis) and the transaction Amount are the features, which are all numeric and there is no missing data. Because we are only using a tree-based classifier, we don’t need to standardize or normalize the features. We will now train the model after splitting the data into train and test sets. This took about half a minute on my laptop. We use the n_iter_no_change to stop the training early if the performance on a validation subset starts to deteriorate due to overfitting. I separately did a little bit of hyperparameter tuning to choose the learning_rate and max_leaf_nodes, but this is not the focus of the present article. Xtrain, Xtest, ytrain, ytest = model_selection.train_test_split( df.loc[:,'V1':'Amount'], df.Class, stratify=df.Class, test_size=0.3, random_state=42)gbc=HistGradientBoostingClassifier(learning_rate=0.01, max_iter=2000, max_leaf_nodes=6, validation_fraction=0.2, n_iter_no_change=15, random_state=42).fit(Xtrain,ytrain) Now we apply this model to the test data as the default hard-classifier, predicting 0 or 1 for each transaction. We are implicitly applying decision threshold 0.5 to the model’s continuous probability prediction as a soft-classifier. When the probability prediction is over 0.5 we say “1” and when it is under 0.5 we say “0”. We also print the confusion matrix for the result, considering Class 1 (fraud) to be the “positive” class, by convention because it is the rarer class. The confusion matrix shows the number of True Negatives, False Positives, False Negatives, and True Positives. The normalized confusion matrix rates (e.g. FNR = False Negative Rate) are included as percentages in parentheses. hardpredtst=gbc.predict(Xtest)def conf_matrix(y,pred): ((tn, fp), (fn, tp)) = metrics.confusion_matrix(y, pred) ((tnr,fpr),(fnr,tpr))= metrics.confusion_matrix(y, pred, normalize='true') return pd.DataFrame([[f'TN = {tn} (TNR = {tnr:1.2%})', f'FP = {fp} (FPR = {fpr:1.2%})'], [f'FN = {fn} (FNR = {fnr:1.2%})', f'TP = {tp} (TPR = {tpr:1.2%})']], index=['True 0(Legit)', 'True 1(Fraud)'], columns=['Pred 0(Approve as Legit)', 'Pred 1(Deny as Fraud)'])conf_matrix(ytest,hardpredtst) We see that the Recall for Class 1 (a.k.a. Sensitivity or True Positive Rate shown as TPR above) is only 71.62%, meaning that 71.62% of the true frauds are correctly identified as frauds and thus denied. So 28.38% of the true frauds are unfortunately approved as if legitimate. Especially with imbalanced data (or generally any time false positives and false negatives may have different consequences), it’s important not to limit ourselves to using the default implicit classification decision threshold of 0.5, as we did above by using “.predict( )”. We want to improve the Recall of class 1 (the TPR) to reduce our fraud losses (reduce false negatives). To do this, we can reduce the threshold for which we say “Class 1” when we predict a probability above the threshold. This way we say “Class 1” for a wider range of predicted probabilities. Such strategies are known as threshold-moving. Ultimately it is a business decision to what extent we want to reduce these False Negatives since as a trade-off the number of False Positives (true legitimate transactions rejected as frauds) will inevitably increase as we adjust the threshold that we apply to the model’s probability prediction (obtained from “.predict_proba( )” instead of “.predict( )”). To elucidate this trade-off and help us choose a threshold, we plot the False Positive Rate and False Negative Rate against the Threshold. This is a variant of the Receiver Operating Characteristic (ROC) curve, but emphasizing the threshold. predtst=gbc.predict_proba(Xtest)[:,1]fpr, tpr, thresholds = metrics.roc_curve(ytest, predtst)dfplot=pd.DataFrame({'Threshold':thresholds, 'False Positive Rate':fpr, 'False Negative Rate': 1.-tpr})ax=dfplot.plot(x='Threshold', y=['False Positive Rate', 'False Negative Rate'], figsize=(10,6))ax.plot([0.00035,0.00035],[0,0.1]) #mark example thresh.ax.set_xbound(0,0.0008); ax.set_ybound(0,0.3) #zoom in Although there exist some rules of thumb or proposed metrics for choosing the optimal threshold, ultimately it depends solely on the cost to the business of false negatives vs. false positives. For example, looking at the plot above, we might choose to apply a threshold of 0.00035 (vertical green line has been added) as follows. hardpredtst_tuned_thresh = np.where(predtst >= 0.00035, 1, 0)conf_matrix(ytest, hardpredtst_tuned_thresh) We have reduced our False Negative Rate from 28.38% down to 9.46% (i.e. identified and denied 90.54% of our true frauds as our new Recall or Sensitivity or True Positive Rate or TPR), while our False Positive Rate (FPR) has increased from 0.01% to 5.75% (i.e. still approved 94.25% of our legitimate transactions). It might well be worth the trade-off to us of denying about 6% of the legitimate transactions as the price we pay in order to approve only less than 10% of the fraudulent transactions, down from a very costly 28% of the frauds when we were using the default hard-classifier with an implicit classification decision threshold of 0.5. One reason to avoid “balancing” your imbalanced training data is that such methods bias/distort the resulting trained model’s probability predictions so that these become miscalibrated, by systematically increasing the model’s predicted probabilities of the original minority class, and are thus reduced to being merely relative ordinal discriminant scores or decision functions or confidence scores rather than being potentially accurate predicted class probabilities in the original (“imbalanced”) train and test set and future data that the classifier may make predictions on. In the event that such rebalancing for training is truly needed, but numerically-accurate probability predictions are still desired, one would then have to recalibrate the predicted probabilities to a data set having the original/imbalanced class proportions, or apply an appropriate correction to the predicted probabilities from the balanced model — see here, here, or here. Another problem with balancing your data by oversampling (as opposed to class-dependent instance weighting which doesn’t have this problem) is that it biases naïve cross-validation, potentially leading to excessive overfitting that is not detected in the cross-validation. If you perform oversampling on the full training set, then in cross-validation, each time the data gets split into a “fold” subset, there may be instances in one fold that are duplicates of, or were generated from, instances in another fold. Thus the folds are not truly independent as cross-validation assumes — there is data “bleed” or “leakage”. For example see Cross-Validation for Imbalanced Datasets which describes how you could re-implement cross-validation correctly for this situation by performing the oversampling only on each set of training folds, inside the cross-validation loop, as in this example. However, in scikit-learn, at least for the case of oversampling by instance duplication (not necessarily SMOTE), this can alternatively be worked around by using model_selection.GroupKFold for cross-validation, which groups the instances according to a selected group identifier that has the same value for all duplicates of a given instance — see my reply to a response to the aforelinked article. Instead of naïvely or implicitly applying a default threshold of 0.5, or immediately re-training using re-balanced training data, we can try using the original model (trained on the original “imbalanced” data set) and simply plot the trade-off between false positives and false negatives to choose a threshold that may produce a desirable business result. Please leave a response if you have questions or comments, or read others’ responses and my replies: tap the Response speech bubble 🗨️ (actually a round one) down below next to the Clap (applause) icon. The average probability prediction produced by your model will approximate the proportion of training instances that are class 1, because this is the average actual value of the target class variable (which has values of 0 and 1). The same is true in regression: the average predicted value of the target variable is expected to approximate the average actual value of the target variable. When the data is highly imbalanced and class 1 is the minority class, this average probability prediction will be much less than 0.5 and the vast majority of predictions of the probability of class 1 will be less than 0.5 and therefore classified as class 0 (majority class). If you rebalance the training data, the average predicted probability increases to 0.5 and so then many instances will be above a default threshold of 0.5 as well as many below — the predicted classes will be more balanced. So instead of reducing the threshold so that more often the probability predictions are above it and give class 1 (minority class), rebalancing increases the the predicted probabilities so that more often the probability predictions will be above the default threshold of 0.5 and give class 1. If you want to get similar (not identical) results to those of rebalancing, without actually rebalancing or reweighting the data, you could try simply setting the threshold equal to the average or median value of the model’s predicted probability of class 1. But of course this won’t necessarily be the threshold that provides the optimal balance between false positives and false negatives for your particular business problem, nor will rebalancing your data and using a threshold of 0.5. It is possible that there are situations and models where rebalancing the data will materially improve the model beyond merely moving the average predicted probability to equal the default threshold of 0.5. But the mere fact that the model chooses the majority class the vast majority of the time when using the default threshold of 0.5 does not in itself support a claim that rebalancing the data will accomplish anything beyond making the average probability prediction equal to the threshold. If you want the average probability prediction to be equal to the threshold, you could simply set the threshold equal to the average probability prediction, without modifying or reweighting your training data in order to distort the probability predictions. If your classifier doesn’t have a predict_proba method, e.g. support vector classifiers, you can just as well use its decision_function method in its place, producing an ordinal discriminant score or confidence score model output which can be thresholded in the same way even if it is not interpretable as a probability prediction between 0 and 1. Depending on how a particular classifier model calculates its confidence scores for the two classes, it might sometimes be necessary, instead of applying the threshold directly to the confidence score of class 1 (which we did above as the predicted probability of class 1 because the predicted probability of class 0 is simply one minus that), to alternatively apply the threshold to the difference between the confidence score for class 0 and that for class 1, with the default threshold being 0 for the case where the cost of a false positive is assumed to be the same as that of a false negative. This article assumes a two-class classification problem. Some rights reserved
[ { "code": null, "e": 719, "s": 171, "text": "In machine learning, when building a classification model with data having far more instances of one class than another, the initial default classifier is often unsatisfactory because it classifies almost every case as the majority class. Many articles show you how you could use oversampling (e.g. SMOTE) or sometimes undersampling or simply class-based sample weighting to retrain the model on “rebalanced” data, but this isn’t always necessary. Here we aim instead to show how much you can do without balancing the data or retraining the model." }, { "code": null, "e": 1233, "s": 719, "text": "We do this by simply adjusting the the threshold for which we say “Class 1” when the model’s predicted probability of Class 1 is above it in two-class classification, rather than naïvely using the default classification rule which chooses which ever class is predicted to be most probable (probability threshold of 0.5). We will see how this gives you the flexibility to make any desired trade-off between false positive and false negative classifications while avoiding problems created by rebalancing the data." }, { "code": null, "e": 1618, "s": 1233, "text": "We will use the credit card fraud identification data set from Kaggle to illustrate. Each row of the data set represents a credit card transaction, with the target variable Class==0 indicating a legitimate transaction and Class==1 indicating that the transaction turned out to be a fraud. There are 284,807 transactions, of which only 492 (0.173%) are frauds — very imbalanced indeed." }, { "code": null, "e": 1889, "s": 1618, "text": "We will use a gradient boosting classifier because these often give good results. Specifically Scikit-Learn’s new HistGradientBoostingClassifier because it is much faster than their original GradientBoostingClassifier when the data set is relatively large like this one." }, { "code": null, "e": 1949, "s": 1889, "text": "First let’s import some libraries and read in the data set." }, { "code": null, "e": 2193, "s": 1949, "text": "import numpy as npimport pandas as pdfrom sklearn import model_selection, metricsfrom sklearn.experimental import enable_hist_gradient_boostingfrom sklearn.ensemble import HistGradientBoostingClassifierdf=pd.read_csv('creditcard.csv')df.info()" }, { "code": null, "e": 2451, "s": 2193, "text": "V1 through V28 (from a principal components analysis) and the transaction Amount are the features, which are all numeric and there is no missing data. Because we are only using a tree-based classifier, we don’t need to standardize or normalize the features." }, { "code": null, "e": 2866, "s": 2451, "text": "We will now train the model after splitting the data into train and test sets. This took about half a minute on my laptop. We use the n_iter_no_change to stop the training early if the performance on a validation subset starts to deteriorate due to overfitting. I separately did a little bit of hyperparameter tuning to choose the learning_rate and max_leaf_nodes, but this is not the focus of the present article." }, { "code": null, "e": 3218, "s": 2866, "text": "Xtrain, Xtest, ytrain, ytest = model_selection.train_test_split( df.loc[:,'V1':'Amount'], df.Class, stratify=df.Class, test_size=0.3, random_state=42)gbc=HistGradientBoostingClassifier(learning_rate=0.01, max_iter=2000, max_leaf_nodes=6, validation_fraction=0.2, n_iter_no_change=15, random_state=42).fit(Xtrain,ytrain)" }, { "code": null, "e": 3544, "s": 3218, "text": "Now we apply this model to the test data as the default hard-classifier, predicting 0 or 1 for each transaction. We are implicitly applying decision threshold 0.5 to the model’s continuous probability prediction as a soft-classifier. When the probability prediction is over 0.5 we say “1” and when it is under 0.5 we say “0”." }, { "code": null, "e": 3922, "s": 3544, "text": "We also print the confusion matrix for the result, considering Class 1 (fraud) to be the “positive” class, by convention because it is the rarer class. The confusion matrix shows the number of True Negatives, False Positives, False Negatives, and True Positives. The normalized confusion matrix rates (e.g. FNR = False Negative Rate) are included as percentages in parentheses." }, { "code": null, "e": 4563, "s": 3922, "text": "hardpredtst=gbc.predict(Xtest)def conf_matrix(y,pred): ((tn, fp), (fn, tp)) = metrics.confusion_matrix(y, pred) ((tnr,fpr),(fnr,tpr))= metrics.confusion_matrix(y, pred, normalize='true') return pd.DataFrame([[f'TN = {tn} (TNR = {tnr:1.2%})', f'FP = {fp} (FPR = {fpr:1.2%})'], [f'FN = {fn} (FNR = {fnr:1.2%})', f'TP = {tp} (TPR = {tpr:1.2%})']], index=['True 0(Legit)', 'True 1(Fraud)'], columns=['Pred 0(Approve as Legit)', 'Pred 1(Deny as Fraud)'])conf_matrix(ytest,hardpredtst)" }, { "code": null, "e": 4841, "s": 4563, "text": "We see that the Recall for Class 1 (a.k.a. Sensitivity or True Positive Rate shown as TPR above) is only 71.62%, meaning that 71.62% of the true frauds are correctly identified as frauds and thus denied. So 28.38% of the true frauds are unfortunately approved as if legitimate." }, { "code": null, "e": 5457, "s": 4841, "text": "Especially with imbalanced data (or generally any time false positives and false negatives may have different consequences), it’s important not to limit ourselves to using the default implicit classification decision threshold of 0.5, as we did above by using “.predict( )”. We want to improve the Recall of class 1 (the TPR) to reduce our fraud losses (reduce false negatives). To do this, we can reduce the threshold for which we say “Class 1” when we predict a probability above the threshold. This way we say “Class 1” for a wider range of predicted probabilities. Such strategies are known as threshold-moving." }, { "code": null, "e": 5816, "s": 5457, "text": "Ultimately it is a business decision to what extent we want to reduce these False Negatives since as a trade-off the number of False Positives (true legitimate transactions rejected as frauds) will inevitably increase as we adjust the threshold that we apply to the model’s probability prediction (obtained from “.predict_proba( )” instead of “.predict( )”)." }, { "code": null, "e": 6058, "s": 5816, "text": "To elucidate this trade-off and help us choose a threshold, we plot the False Positive Rate and False Negative Rate against the Threshold. This is a variant of the Receiver Operating Characteristic (ROC) curve, but emphasizing the threshold." }, { "code": null, "e": 6483, "s": 6058, "text": "predtst=gbc.predict_proba(Xtest)[:,1]fpr, tpr, thresholds = metrics.roc_curve(ytest, predtst)dfplot=pd.DataFrame({'Threshold':thresholds, 'False Positive Rate':fpr, 'False Negative Rate': 1.-tpr})ax=dfplot.plot(x='Threshold', y=['False Positive Rate', 'False Negative Rate'], figsize=(10,6))ax.plot([0.00035,0.00035],[0,0.1]) #mark example thresh.ax.set_xbound(0,0.0008); ax.set_ybound(0,0.3) #zoom in" }, { "code": null, "e": 6814, "s": 6483, "text": "Although there exist some rules of thumb or proposed metrics for choosing the optimal threshold, ultimately it depends solely on the cost to the business of false negatives vs. false positives. For example, looking at the plot above, we might choose to apply a threshold of 0.00035 (vertical green line has been added) as follows." }, { "code": null, "e": 6920, "s": 6814, "text": "hardpredtst_tuned_thresh = np.where(predtst >= 0.00035, 1, 0)conf_matrix(ytest, hardpredtst_tuned_thresh)" }, { "code": null, "e": 7568, "s": 6920, "text": "We have reduced our False Negative Rate from 28.38% down to 9.46% (i.e. identified and denied 90.54% of our true frauds as our new Recall or Sensitivity or True Positive Rate or TPR), while our False Positive Rate (FPR) has increased from 0.01% to 5.75% (i.e. still approved 94.25% of our legitimate transactions). It might well be worth the trade-off to us of denying about 6% of the legitimate transactions as the price we pay in order to approve only less than 10% of the fraudulent transactions, down from a very costly 28% of the frauds when we were using the default hard-classifier with an implicit classification decision threshold of 0.5." }, { "code": null, "e": 8525, "s": 7568, "text": "One reason to avoid “balancing” your imbalanced training data is that such methods bias/distort the resulting trained model’s probability predictions so that these become miscalibrated, by systematically increasing the model’s predicted probabilities of the original minority class, and are thus reduced to being merely relative ordinal discriminant scores or decision functions or confidence scores rather than being potentially accurate predicted class probabilities in the original (“imbalanced”) train and test set and future data that the classifier may make predictions on. In the event that such rebalancing for training is truly needed, but numerically-accurate probability predictions are still desired, one would then have to recalibrate the predicted probabilities to a data set having the original/imbalanced class proportions, or apply an appropriate correction to the predicted probabilities from the balanced model — see here, here, or here." }, { "code": null, "e": 9814, "s": 8525, "text": "Another problem with balancing your data by oversampling (as opposed to class-dependent instance weighting which doesn’t have this problem) is that it biases naïve cross-validation, potentially leading to excessive overfitting that is not detected in the cross-validation. If you perform oversampling on the full training set, then in cross-validation, each time the data gets split into a “fold” subset, there may be instances in one fold that are duplicates of, or were generated from, instances in another fold. Thus the folds are not truly independent as cross-validation assumes — there is data “bleed” or “leakage”. For example see Cross-Validation for Imbalanced Datasets which describes how you could re-implement cross-validation correctly for this situation by performing the oversampling only on each set of training folds, inside the cross-validation loop, as in this example. However, in scikit-learn, at least for the case of oversampling by instance duplication (not necessarily SMOTE), this can alternatively be worked around by using model_selection.GroupKFold for cross-validation, which groups the instances according to a selected group identifier that has the same value for all duplicates of a given instance — see my reply to a response to the aforelinked article." }, { "code": null, "e": 10171, "s": 9814, "text": "Instead of naïvely or implicitly applying a default threshold of 0.5, or immediately re-training using re-balanced training data, we can try using the original model (trained on the original “imbalanced” data set) and simply plot the trade-off between false positives and false negatives to choose a threshold that may produce a desirable business result." }, { "code": null, "e": 10374, "s": 10171, "text": "Please leave a response if you have questions or comments, or read others’ responses and my replies: tap the Response speech bubble 🗨️ (actually a round one) down below next to the Clap (applause) icon." }, { "code": null, "e": 11558, "s": 10374, "text": "The average probability prediction produced by your model will approximate the proportion of training instances that are class 1, because this is the average actual value of the target class variable (which has values of 0 and 1). The same is true in regression: the average predicted value of the target variable is expected to approximate the average actual value of the target variable. When the data is highly imbalanced and class 1 is the minority class, this average probability prediction will be much less than 0.5 and the vast majority of predictions of the probability of class 1 will be less than 0.5 and therefore classified as class 0 (majority class). If you rebalance the training data, the average predicted probability increases to 0.5 and so then many instances will be above a default threshold of 0.5 as well as many below — the predicted classes will be more balanced. So instead of reducing the threshold so that more often the probability predictions are above it and give class 1 (minority class), rebalancing increases the the predicted probabilities so that more often the probability predictions will be above the default threshold of 0.5 and give class 1." }, { "code": null, "e": 12048, "s": 11558, "text": "If you want to get similar (not identical) results to those of rebalancing, without actually rebalancing or reweighting the data, you could try simply setting the threshold equal to the average or median value of the model’s predicted probability of class 1. But of course this won’t necessarily be the threshold that provides the optimal balance between false positives and false negatives for your particular business problem, nor will rebalancing your data and using a threshold of 0.5." }, { "code": null, "e": 12802, "s": 12048, "text": "It is possible that there are situations and models where rebalancing the data will materially improve the model beyond merely moving the average predicted probability to equal the default threshold of 0.5. But the mere fact that the model chooses the majority class the vast majority of the time when using the default threshold of 0.5 does not in itself support a claim that rebalancing the data will accomplish anything beyond making the average probability prediction equal to the threshold. If you want the average probability prediction to be equal to the threshold, you could simply set the threshold equal to the average probability prediction, without modifying or reweighting your training data in order to distort the probability predictions." }, { "code": null, "e": 13807, "s": 12802, "text": "If your classifier doesn’t have a predict_proba method, e.g. support vector classifiers, you can just as well use its decision_function method in its place, producing an ordinal discriminant score or confidence score model output which can be thresholded in the same way even if it is not interpretable as a probability prediction between 0 and 1. Depending on how a particular classifier model calculates its confidence scores for the two classes, it might sometimes be necessary, instead of applying the threshold directly to the confidence score of class 1 (which we did above as the predicted probability of class 1 because the predicted probability of class 0 is simply one minus that), to alternatively apply the threshold to the difference between the confidence score for class 0 and that for class 1, with the default threshold being 0 for the case where the cost of a false positive is assumed to be the same as that of a false negative. This article assumes a two-class classification problem." } ]
QlikView - Quick Guide
QlikView is a leading Business Discovery Platform. It is unique in many ways as compared to the traditional BI platforms. As a data analysis tool, it always maintains the relationship between the data and this relationship can be seen visually using colors. It also shows the data that are not related. It provides both direct and indirect searches by using individual searches in the list boxes. QlikView's core and patented technology has the feature of in-memory data processing, which gives superfast result to the users. It calculates aggregations on the fly and compresses data to 10% of original size. Neither users nor developers of QlikView applications manage the relationship between data. It is managed automatically. QlikView has patented technology, which enables it to have many features that are useful in creating advanced reports from multiple data sources quickly. Following is a list of features that makes QlikView very unique. Data Association is maintained automatically − QlikView automatically recognizes the relationship between each piece of data that is present in a dataset. Users need not preconfigure the relationship between different data entities. Data Association is maintained automatically − QlikView automatically recognizes the relationship between each piece of data that is present in a dataset. Users need not preconfigure the relationship between different data entities. Data is held in memory for multiple users, for a super-fast user experience − The structure, data and calculations of a report are all held in the memory (RAM) of the server. Data is held in memory for multiple users, for a super-fast user experience − The structure, data and calculations of a report are all held in the memory (RAM) of the server. Aggregations are calculated on the fly as needed − As the data is held in memory, calculations are done on the fly. No need of storing pre-calculated aggregate values. Aggregations are calculated on the fly as needed − As the data is held in memory, calculations are done on the fly. No need of storing pre-calculated aggregate values. Data is compressed to 10% of its original size − QlikView heavily uses data dictionary. Only essential bits of data in memory is required for any analysis. Hence, it compresses the original data to a very small size. Data is compressed to 10% of its original size − QlikView heavily uses data dictionary. Only essential bits of data in memory is required for any analysis. Hence, it compresses the original data to a very small size. Visual relationship using colors − The relationship between data is not shown by arrow or lines but by colors. Selecting a piece of data gives specific colors to the related data and another color to unrelated data. Visual relationship using colors − The relationship between data is not shown by arrow or lines but by colors. Selecting a piece of data gives specific colors to the related data and another color to unrelated data. Direct and Indirect searches − Instead of giving the direct value a user is looking for, they can input some related data and get the exact result because of the data association. Of course, they can also search for a value directly. Direct and Indirect searches − Instead of giving the direct value a user is looking for, they can input some related data and get the exact result because of the data association. Of course, they can also search for a value directly. The Free Personal Edition of QlikView can be downloaded from QlikView Personal Edition. You need to register with your details to be able to download. After downloading, the installation is a very straightforward process in which you need to accept the license agreement and provide the target folder for installation. The screen shots given below describe the entire setup process. Double clicking the QlikViewDesktop_x64Setup.exe will present a screen to select the language of your choice. On selecting English, the following screen is displayed. Then click Next. Read the license agreement and if you agree, choose the "I accept the terms in the license agreement" option. Then click "Next". Provide your name and organization details. Then Click "Next". You may accept the default destination for installation or alter it. Then click "Next". Choose the setup type as "Complete". Then click "Next". In this screen, you finally decide to really start the installation. You can still go back and change some options if needed. Assuming you are fine with everything so far, click "Install". The installation completion screen appears after successful installation. Click "Finish". You can verify the installation by going to the Windows Start menu and clicking on the QlikView icon. The screen appears as shown below. You are now ready to learn QlikView. As a leading Business Discovery Platform, QlikView is built with a very different approach to data discovery than other traditional platforms. QlikView does not first build a query and then fetch the result based on the query. Rather, it forms associations between different data objects as soon as it is loaded and prompts the user to explore the data in any way. There is no predefined data drill down paths. The data drill down paths can happen in any direction as long as the data is available and associated. Of course, a user can also play a role in creating the associations between data elements using data modeling approach available in QlikView. QlikView's architecture consists of a front end to visualize the processed data and a back end to provide the security and publication mechanism for QlikView user documents. The diagram given below depicts the internal working of QlikView. The architecture is discussed in detail below the picture. The Front end in QlikView is a browser-based access point for viewing the QlikView documents. It contains the QlikView Server, which is mainly used by the Business users to access the already created BI reports through an internet or intranet URL. Business users explore and interact with data using this front end and derive conclusions about the data. They also collaborate with other users on a given set of reports by sharing insights and exploring data together, in real time or off-line. These user documents are in the format .qvw, which can also be stored in the windows OS as a standalone document The QlikView server in the front end manages the client server communication between the user and QlikView backend system. The QlikView backend consists of QlikView desktop and QlikView publisher. The QlikView desktop is a wizard-driven Windows environment, which has the features to load and transform data from its source. Its drag and drop feature is used to create the GUI layout of the reports that becomes visible in the frontend. The file types, which are created by QlikView desktop are stored with an extension of .qvw. These are the files that are passed on to the QlikView server in the front end, which serves the users with these files. Also .qvw files can be modified to store the data-inly files, which are known as .qvd files. They are binary files, which contain only the data and not the GUI components. The QlikView publisher is used as distribution service to distribute the .qvw documents among various QlikView servers and users. It handles the authorization and access privileges. It also does the direct loading of data from data sources by using the connection strings defined in the .qvw files. In this chapter, we will get acquainted with the screens available to a user for doing various operations. We will learn the basic navigation and know the different functions performed by the icons available in QlikView. This screen is a gentle introduction to navigate around QlikView. This screen comes up when you start QlikView and keep the Show start page when launching QlikView option checked. If you scroll down the examples section in the left, you can click any of the examples like − Movies Database, Data Visualization etc. to invoke it and see how QlikView works. Feel free to click around! On moving to the right, you notice the Recent and Favourites link, which show all the recently visited QlikView documents and the documents you want to visit frequently. On closing the ‘Getting Started’ window, we get the main interface with all the available Menu commands. They represent the entire set of features available in QlikView. Given below is an overview of each section of the Menu Commands. This menu is used to create a new QlikView file and open the existing files from both local system and QlikView server. The important features in this menu are − Mail as attachment to email the currently open document as an attachment. Mail as attachment to email the currently open document as an attachment. Reduce Data to view only the report layout and database structure without any data. Reduce Data to view only the report layout and database structure without any data. Table viewer option is used to see the structure of the tables, fields and their association in a graphical view. Table viewer option is used to see the structure of the tables, fields and their association in a graphical view. This menu is used to carry out the editing options like copy, paste, cut and using format painter. The important features in this menu are − Active All option activates all the sheet objects present in the opened sheet. Active All option activates all the sheet objects present in the opened sheet. Removeto remove a sheet from the active window. Removeto remove a sheet from the active window. Advanced search option is used to do a search with advanced search expressions using multi box. Advanced search option is used to do a search with advanced search expressions using multi box. This menu is used to view the standard toolbars and zoom in/ zoom out features. It also displays all the active sheets as a cascade menu. The important features in this menu are − Turn on/off WebView mode toggles the WebView mode and local view mode. Turn on/off WebView mode toggles the WebView mode and local view mode. Current Selections displays the field name and file values of the selected sheet objects. Current Selections displays the field name and file values of the selected sheet objects. Design Grid is used to toggle the sheet object placeholders for active object(s) and snap-to-grid for sizing and moving objects in the layout. Design Grid is used to toggle the sheet object placeholders for active object(s) and snap-to-grid for sizing and moving objects in the layout. This menu is used to select and clear the selection of values in the sheet objects. It also provides the feature of going back and forward into different logical statements of the sheet, you are working on. The important features in this menu are − Lock locks all the values in current selection. Unlock unlocks all the locked values in the current selection. Layout Menu is used to add tabbed sheets, select different sheets and rearrange sheet objects. The important features in this menu are − Promote sheet moves the current sheet or tab one step forward. Demote sheet moves the current sheet or tab one step backward. Delete sheet deletes the active sheet and everything in it. Settings menu is used to set the user preferences, document properties, and sheet properties. The important features in this menu are − Variable overview all the non-hidden variables and their values in a single list. Expression Overview shows expressions from the document, sheet and sheet objects as a single list. This menu is used to create bookmarks to different documents for faster retrieval. Reports menu is used to create new reports and edit the existing reports. You can edit the layout, add pages to the report, and also delete reports. Tools menu is a very prominent menu, frequently used for creating charts and opening the QlikView management console. The important features in this menu are − Quick Chart Wizard creates simple charts without using the great number of different settings and options available. Quick Chart Wizard creates simple charts without using the great number of different settings and options available. Time Chart Wizard creates time series charts. Time Chart Wizard creates time series charts. Statistics Chart Wizard is used to apply common statistical tests on data. Statistics Chart Wizard is used to apply common statistical tests on data. This menu is used to create new sheet objects and modify the existing ones. The sheet properties option opens the page to set the parameters defining the sheet. The important features in this menu are − Copy Sheet − creates a copy of the sheet along with the all the sheet objects. Copy Sheet − creates a copy of the sheet along with the all the sheet objects. Copy Image to Clipboard − Copies a bitmap picture of the sheet area to Clipboard. Copy Image to Clipboard − Copies a bitmap picture of the sheet area to Clipboard. Remove − completely removes the sheet along with the sheet objects. Remove − completely removes the sheet along with the sheet objects. The Window and Help menus are used to organize the different windows of QlikView application and provide help documentation. QlikView accepts Excel spreadsheet for data analysis by simple drag and drop action. You need to open the QlikView main window and drag and drop the excel file into the interface. It will automatically create the sheet showing the excel data. Keep the main window of QlikView open and browse for the excel file you want to use. On dropping the excel file into the main window, the File wizard appears. The File Type is already chosen as Excel. Under Labels, choose Embedded Labels. Click "Next step" to proceed. The Load script appears which shows the command that loads the data into the QlikView document. This command can be edited. Now, the Excel wizard prompts to save the file in the form of *.qvw file extension. It asks to select a location where you need to save the file. Click "Next step" to proceed. Now it is time to see the data that is loaded from the Excel file. We use a Table Box sheet object to display this data. The Table Box is a sheet object to display the available data as a table. It is invoked from the menu Layout → New Sheet Object → Table Box. On clicking Next, we get the option to choose the fields from the Table Box. You can use the Promote or Demote buttons to rearrange the fields. On completing the above step, the Table Box Sheet Object appears which shows the data that is read from the Excel file. QlikView can use the data in plane text file where the fields are separated by characters like comma, tab, semicolon etc. Here, we will take CSV as an example. A file in which each column of data is separated by a comma is known as a CSV file. It is a very widely used file format to store plane text-data organized as columns and rows. QlikView loads csv files using the Data from files options available in the script editor under the File Menu. Alternatively, you can also open a new QlikView document and press control+E to get the script editor window as shown below. Choose the file Product_details.csv from the appropriate path. On opening the selected CSV file, a window as shown below comes up. Under Labels choose Embedded Labels, as our file has a header row as its first row. Click Finish. The loading of the file into QlikView is done through the load script, which can be seen in the screen shot below. Hence, when we use any delimited file, we can tweak the below script as per the file format. Now the script wizard prompts to save the file in the form of *.qvw file extension. It asks to select a location where you need to save the file. Click "Next step" to proceed. Now, it is time to see the data that is loaded from the delimited file. We use a Table Box sheet object to display this data. The Table Box is a sheet object to display the available data as a table. It is invoked from the menu Layout → New Sheet Object → Table Box. On clicking Next, we get the option to choose the fields from the Table Box. You can use the Promote or Demote buttons to rearrange the fields. On completing the above step, the Table Box Sheet Object appears which shows the data that is read from the Excel file. XML is a file format, which shares both the file format and the data on the World Wide Web, intranets, and elsewhere using standard ASCII text. It stands for Extensible Markup Language (XML). Similar to HTML it contains markup tags. However, unlike HTML where the markup tag describes structure of the page, in XML the markup tags describe the meaning of the data contained into the file. QlikView can use the data from XML files. The process to load the data from XML files is similar to the loading of delimited files we have seen earlier. Open the script editor. Click on the menu Insert → Load Statement → Load from File. Browse for the XML file you wish to load. In this example, we are choosing the employee_dat.xml file. On opening the selected XML file, a window comes up as shown below. Under the File Type section in the left, choose XML. The content of the XML file now appears as a table along with the header column. Click Finish. The loading of the XML file into QlikView is done through the load script, which can be seen below. So when we use any XML file, we can tweak the below given script to rename the columns or change the file location etc. Now the script wizard prompts you to save the file in the form of *.qvw file extension. It asks to select a location where you need to save the file. Click "Next step" to proceed. Now it is time to see the data that is loaded from the XML file. We use a Table Box sheet object to display this data. The Table Box is a sheet object to display the available data as a table. It is invoked from the menu Layout → New Sheet Object → Table Box. On clicking Next, we get the option to choose the fields from the Table Box. You can use the Promote or Demote buttons to rearrange the fields. On completing the above step, the Table Box Sheet Object appears which shows the data that is read from the Excel file. QlikView can process files from the web, which are in the HTML format. It can extract data from HTML tables. The URL of the web file to be processed is given as an input and QlikView fetches both, the structure and content of the file. Then it analyzes the structure of the page extracting the relevant data from the HTML tables present in the page. We choose the Web files option from the Data from files section under the Data tab of script Editor. On selecting the Web files option, we get a new window to give the URL as input. In this example, we are choosing the List of sovereign states and dependent territories in Asia as the input page from Wikipedia. Mention the URL and click Next. On opening the selected Web file, the window shown below comes up. Here we can see the various tables present in the webpage labeled as @1, @1, @3 and so on. Choose the first table and click Next twice. From the above table, we can choose only the columns we need by removing the unwanted columns using the cross sign. The loading of the file into QlikView is done through the load script, which can be seen in the screen shot given below. Hence, when we use any delimited file, we can tweak the below given script as per the file format. Now the script wizard prompts to save the file in the form of *.qvw file extension. It asks to select a location where you need to save the file. Click "Next step" to proceed. Now it is time to see the data that is loaded from the web file. We use a Table Box sheet object to display this data. The Table Box is a sheet object to display the available data as a table. It is invoked from the menu Layout → New Sheet Object → Table Box. On clicking Next, we get the option to choose the fields from the Table Box. You can use the Promote or Demote buttons to rearrange the fields. On completing the above step, the Table Box Sheet Object appears, which shows the data that is read from the Web file. Mark the Non-English characters !! QlikView can connect to most of the popular databases like MySQL, SQL Server, Oracle, Postgress etc. It can fetch data and table structures into QlikView environment and store the results in its memory for further analysis. The steps to connect to any of these databases involves creating an ODBC connection using a DSN and then using this DSN to fetch the data. For this tutorial, we will be connecting to MySQL database. This tutorial assumes you have a MySQL environment available. Create an ODBC DSN (Data Source Name) for MySQL, following these steps − to create DSN. Name the DSN as mysqluserdsn or you may prefer to use the existing one if you have already created a DSN for MySql. For this chapter we will use the MySql inbuilt database named sakila. We create a new QlikView document and open the script editor (pressing Control+E). Under the tab Data, we locate the section named Database. Choose ODBC from the drop down list and click Connect. The following window opens. Choose the DSN named mysqluserdns and click Test Connection. The message Connection Test succeeded should appear. On successful connection, the screen given below appears showing the connection to the DB in the main window of the script editor. Click Select iin the above window to get the list of tables and columns. Here as we have created the DSN with sakila as the default database we get the list of tables and columns from this database. We can choose another database from the database drop down list as shown in the screenshot given below. We will continue using the sakila database for this chapter. On Clicking OK in the above window, we get back to the main script editor showing the script for using the table named actor. Now the data loaded into QlikView document needs to be stored permanently to be analyzed further. For this, we will edit the script to store the data in the form of a qvd file. Press Control+E to open the edit script window and write the following code. In the code, we give appropriate names to the columns and mention the table name above the load statement. In addition, we give a path where the generated qvd file will be stored. Save this file as QV_mysql.qvw The qvd file can be loaded into the main document and used to create graphs and tables for further analysis. Press Control+R to reload the QV_mysql.qvw file and click Next in the chart wizard. Choose the straight table to be created with actor_id, first_name, last_name as the dimensions and count of actor_id as the expression. A chart appears as given below. Data can be entered into a QlikView document by directly typing or pasting it. This feature is a quick method to get the data from the clipboard into the QlikView. The script editor provides this feature under the Insert tab. To open the Inline data load option, we open the script editor and go to Insert → Load Statement → Load Inline. On opening the above screen, we get a spreadsheet-like document where we can type the values. We can also paste the values already available in the clipboard. Please note the column headers are created automatically. Click Finish. The command, which loads the data, is created in the background which can be seen in the script editor. On creating a Table Box Sheet Object, we see the data that is read from the Inline data load option. QlikView can load data from tables already existing in its RAM, which is already processed by a script. This requirement arises when you want to create a table deriving data from an already existing table in the same script. Please note that both the new table and the existing table should be in the same script. Open the script editor (or use Control+E) and mention the following script. Here we create an inline table named Regions with sales data for different regions. Then we create another table named Total to calculate the total sales by Region Names. Finally we drop the table Regions, as in this .qvw file we only need the table named Total for data analysis. On creating a Table Box Sheet Object, we see the data that is read from the resident data load option. QlikView Preceding load is a load type in which we use a load statement, which takes the columns of another load statement present in the same script. The data read by the first Load statement, which is at the bottom of the script editor window and then used by the load statements above it. The below given screen shot shows the script for data, which is loaded as Inline data and then the max function is applied to one of the columns. The load statement at the bottom makes the data available in QlikView's memory, which is used by the second load statement above the first load statement. The second load statement applies the max function with group by clause. On creating a Table Box Sheet Object, we see the data that is read from the Inline data load option. As the volume of data in the data source of a QlikView document increases, the time taken to load the file also increases which slows down the process of analysis. One approach to minimize this time taken to load data is to load only the records that are new in the source or the updated ones. This concept of loading only the new or changed records from the source into the QlikView document is called Incremental Load. To identify the new records from source, we use either a sequential unique key or a date time stamp for each row. These values of unique key or data time field has to flow from the source file to QlikView document. Let us consider the following source file containing product details in a retail store. Save this as a .csv file in the local system where it is accessible by QlikView. Over a period of time some more products are added and the description of some product changes. Product_Id,Product_Line,Product_category,Product_Subcategory 1,Sporting Goods,Outdoor Recreation,Winter Sports & Activities 2,"Food, Beverages & Tobacco",Food Items,Fruits & Vegetables 3,Apparel & Accessories,Clothing,Uniforms 4,Sporting Goods,Athletics,Rugby 5,Health & Beauty,Personal Care 6,Arts & Entertainment,Hobbies & Creative Arts,Musical Instruments 7,Arts & Entertainment,Hobbies & Creative Arts,Orchestra Accessories 8,Arts & Entertainment,Hobbies & Creative Arts,Crafting Materials 9,Hardware,Tool Accessories,Power Tool Batteries 10,Home & Garden,Bathroom Accessories,Bath Caddies 11,"Food, Beverages & Tobacco",Food Items,Frozen Vegetables 12,Home & Garden,Lawn & Garden,Power Equipment We will load the above CSV file using the script editor (Control+E) by choosing the Table Files option as shown below. Here we also save the data into a QVD file in the local system. Save the QlikView document as a .qvw file. We can check the data loaded to QlikView document by creating a sheet object called Table Box. This is available in the Layout menu and New Sheet Objects sub-menu. On selecting the Table Box sheet object, we get to the next screen, which is used to select the columns and their positions in the table to be created. We choose the following columns and their positions and click Finish. The following chart showing the data as laid out in the previous step appears. Let us add the following three more records to the source data. Here, the Product IDs are the unique numbers, which represent new records. 13,Office Supplies,Presentation Supplies,Display 14,Hardware,Tool Accessories,Jigs 15,Baby & Toddler,Diapering,Baby Wipes Now, we write the script to pull only the new records form the source. // Load the data from the stored qvd. Stored_Products: LOAD Product_Id, Product_Line, Product_category, Product_Subcategory FROM [E:\Qlikview\data\products.qvd] (qvd); //Select the maximum value of Product ID. Max_Product_ID: Load max(Product_Id) as MaxId resident Stored_Products; //Store the Maximum value of product Id in a variable. Let MaxId = peek('MaxId',-1); drop table Stored_Products; //Pull the rows that are new. NewProducts: LOAD Product_Id,Product_Line, Product_category,Product_Subcategory from [E:\Qlikview\data\product_categories.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq) where Product_Id > $(MaxId); //Concatenate the new values with existing qvd. Concatenate LOAD Product_Id,Product_Line, Product_category, Product_Subcategory FROM [E:\Qlikview\data\products.qvd](qvd); //Store the values in qvd. store NewProducts into [E:\Qlikview\data\products.qvd](qvd); The above script fetches only the new records, which are loaded and stored into the qvd file. As we see the records with the new Product IDs 13, 14 and 15. One of the important features of QlikView, which makes it so distinguished is the ability to store very large amount of data in a very compressed size and store it along with the QlikView documents. Therefore, once the document is created we need not connect to the data source, as the data is already stored along with the layout of the document. This is achieved through QVD file, which is a flat file stored with the .qvd extension. A QVD file stores data for one QlikView document and it is created using the script editor available in the QlikView document. The advantages of using QVD files in QlikView are as follows − Faster Loading of Data Gracefully support scaling up as the data volume grows Used in incremental load Data from multiple sources can be clubbed to one data set Extract data in parallel QVD files are created using the STORE statement during the loading of QlikView files. This statement creates a single qvd file, which gets stored in the specified location as a file; separate than the QVW file through which it is created. Given below is an example of storing the qvd file after the data is loaded into the QlikView document by reading a source file. A QVD file is loaded to a QlikView document in a similar way as other files like CSV, Excel and delimited files are used. We use the the Open option available under the File menu and browse for the QVD file we created before. On opening it gives us a window to see the data, select the column headers and do any data transformation required On clicking Finish, the edit script window appears which shows the code used to load the QVD file. We can edit this code further. For example, to get only the few of the columns to be displayed or apply any inbuilt function etc. Click finish to load the file into the current QlikView document. Save the QlikView document as use_qvd.qvw. Reload the document by using Control+R and choose the menu option Layout → New Sheet Objects → Table Box. A window appears showing all the columns from the table present in the QVD file. Select "Add All" to add all the columns to the display table. Use the "Promote/Demote" option to change the order of the columns. Click "Finish". The following screen appears showing the content of the QVD file. Every QlikView document is made of at least one worksheet called Main. We can add more sheets, which are like many pages of the same QlikView document. Sheets help us display multiple data formats like - multiple charts or multiple tables. Each sheet can contain various sheet objects. In addition, sheets can be rearranged using Promote Sheet/Demote Sheet option and can be removed from the QlikView document using Remove Sheet option. Sheets have various properties, which can be set to customize the sheets. For example, we can set the name of the sheets and its colors. Right click anywhere in the sheet and choose the Properties option. Then choose the following properties. Sheet Settings → Color. − This will set the background colour of the Sheet. Sheet Settings → Color. − This will set the background colour of the Sheet. Tab Settings → Custom Colors. − This will set the color for the Tab where the Sheet name appears. Tab Settings → Custom Colors. − This will set the color for the Tab where the Sheet name appears. Title. − This will set the name of the Sheet. Title. − This will set the name of the Sheet. Sheet Objects are the QlikView data elements that are embedded in the sheet. They display the data that is loaded into the QlikView's memory. Each sheet object is tied to a data source and one or more of its columns. Sheet Objects are created from the layout menu as shown below. Sheet Objects display the data from a data source and all the objects in a sheet are associated with each other. Let's create a List Box and a Multi Box and see this association on action. The List box displays data from a column of a table available in QlikView memory. Choose the option List Box from the Add Sheet Objects option and set the properties as given below. A Multi Box represents data from multiple columns from a table. Choose the option Multi Box from the Add Sheet Objects option and set the properties as shown below. On completing the above given steps, the following window appears which shows both the objects. We can see how the sheet objects are linked to each other by choosing the one option from the Multi Box, which highlights the associated row in the List Box. Let us choose "Diapering" under the Product Category drop down list in Multi Box. The window shown below appears. Scripting is a very powerful feature in QlikView, which enables the control of the data load options and data transformations. It enables the use of many inbuilt functions available in QlikView and creates subroutines to be used across multiple scripts within a QlikViewdocument. Scripting is done using the Script Editor. It is accessed from the File menu using Script Editor. We can also press Control +E to open the script editor window. It prepopulates some data formats that are set as default formats for the data to be processed. For example, the Thousand separator is a comma and date is in Month-day-year format. These can be changed to suit the incoming data as per the need. Script editor has many features, which are accessed from the menu in the script editor window, which is a different menu from the main menu. Given below is a list of important features. Reload − Reloads the script and fetches the new data. Reload − Reloads the script and fetches the new data. Upper/Lower Case − Converts the case of words as QlikView is case sensitive. Upper/Lower Case − Converts the case of words as QlikView is case sensitive. Comment − Used to comment blocks of code. Comment − Used to comment blocks of code. Clear Entire Script − Clears the active script tab. Clear Entire Script − Clears the active script tab. Open Script File − Opens the saved script files. Open Script File − Opens the saved script files. Table Viewer − Used to see the tabular view of the data being loaded. Table Viewer − Used to see the tabular view of the data being loaded. Environment Variables − Inserts a standard list of Environment variables. Environment Variables − Inserts a standard list of Environment variables. Script Files − Allows to browse for script files and insert them. Script Files − Allows to browse for script files and insert them. Connect/Disconnect Statement − Used to connect or disconnect from external databases. Connect/Disconnect Statement − Used to connect or disconnect from external databases. Insert Tab − Inserts a Tab at the current cursor position. Insert Tab − Inserts a Tab at the current cursor position. Promote/Demote Tab − Allows to move the tabs from left to right and vice versa. Promote/Demote Tab − Allows to move the tabs from left to right and vice versa. Merge with Previous − Used to merge the content of active tag with previous tab. Merge with Previous − Used to merge the content of active tag with previous tab. ODBC Administrator 64 bit/ODBC Administrator 32 bit − Allows to set the correct DSN information for data sources. ODBC Administrator 64 bit/ODBC Administrator 32 bit − Allows to set the correct DSN information for data sources. Editor Preferences − Allows you to configure the text font and size, help features, shortcuts, default-scripting engine etc. Editor Preferences − Allows you to configure the text font and size, help features, shortcuts, default-scripting engine etc. Syntax Check − Used to validate the syntax of the script code. Syntax Check − Used to validate the syntax of the script code. QlikView has many built-in functions, which are available to be applied to data that is already available in memory. These functions are organized into many categories and the syntax of the function appears as soon as it is selected. We can click on the Paste button to get the expression into the editor and supply the arguments. Create a Table Box by following the menu as shown in the screen shot given below. On completing the above given step, we get a window to show the Calculation condition at the bottom left. Click on the button next to calculation condition and go to the Function tab. It shows the list of functions available. On choosing String from the functions category, we can see only few functions, which take a string as an argument. In the next chapters, we will see the use of many important functions. QlikView IntervalMatch is a powerful function used to match distinct numeric values to numeric intervals. It is useful in analyzing how the events actually happened versus the planned events. The example of a scenario where it is used is in the assembly lines of the production houses where the belts are planned to run at certain times and for certain duration. However, the actual run can happen at different points in time because of breakdown etc. Consider an assembly line where there are three belts named A, B and C. They are planned to start & stop at specific times of a day. In a given day, we study the actual start and end time and analyze what all happened in that day. For this, we consider two sets of observations as shown below. # Data Set for AssembilyLine. StartTime,EndTime, BeltNo 00:05,4:20, A 1:50,2:45,B 3:15,10:30,C # Data set for the events happened. ActualTime,Product 1:10,Start Belt A 2:24,Stop Belt A 3:25,Restart Belt A 4:35,Stop Belt A 2:20,Start Belt B 3:11, Stop Belt B 3:15,Start Belt C 11:20, Stop Belt C We open the script editor in a new QlikView document using Control+E. The following code creates the required tables as inline data. After creating this script, press control+R to reload the data into the QlikView document. Let us create a Table Box sheet object to show the data generated by the IntervalMatch function. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. On clicking OK in the above window, a table appears showing the field ActualTime matched to the intervals StartTime and EndTime. QlikView Aggregate functions are used to produce aggregate data from the rows of the table. The functions are applied to the columns when creating the load script. Given below is a sample list of Aggregate functions. We also need to apply the Group by clause appropriately when applying the aggregate functions. SUM gives the sum of the numeric values of the column. AVG gives the average of the numeric values of the column. MAX gives the maximum of the numeric values of the column. MIN gives the minimum of the numeric values of the column. Consider the following data stored as product_sales.csv in the local system. It represents the sales figures for different product lines and product category in a store. Product_Line,Product_category,Quantity,Value Sporting Goods,Outdoor Recreation,12,5642 Food, Beverages & Tobacco,38,2514 Apparel & Accessories,Clothing,54,2365 Apparel & Accessories,Costumes & Accessories,29,4487 Sporting Goods,Athletics,11,812 Health & Beauty,Personal Care,21,6912 Arts & Entertainment,Hobbies & Creative Arts,58,5201 Arts & Entertainment,Paintings,73,8451 Arts & Entertainment,Musical Instruments,41,1245 Hardware,Tool Accessories,2,456 Home & Garden,Bathroom Accessories,36,241 Food,Drinks,54,1247 Home & Garden,Lawn & Garden,29,5462 Office Supplies,Presentation Supplies,22,577 Hardware,Blocks,53,548 Baby & Toddler,Diapering,19,1247 We open the script editor in a new QlikView document using Control+E. The following code creates the required tables as inline data. After creating this script press control+R to reload the data into the QlikView document. Let us create a Table Box sheet object to show the data generated by the Aggregate function. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and the select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below. Given below is the load script to find the sum of the sales quantity and sales value across the Product Lines and product categories. Click OK and press Control+R to reload the data into QlikView document. Now follow the same steps as given above in − Creating Sheet Objects to create a QlikView Table Box for displaying the result of the script as shown below. Given below is the load script to create the average of the sales quantity and sales value across each Product Line. # Average sales of Quantity and value in each Product Line. LOAD Product_Line, avg(Quantity), avg(Value) FROM [E:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq) Group by Product_Line; Click OK and press Control+R to reload the data into QlikView document. Now follow the same steps as given above in − Creating Sheet Objects to create a QlikView Table Box for displaying the result of the script as shown below. Given below is the load script to create the maximum and minimum of the sales quantity across each Product Line. # Maximum and Minimum sales in each product Line. LOAD Product_Line, max(Quantity) as MaxQuantity, min(Quantity) as MinQuantity FROM [E:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq) Group by Product_Line; Click OK and Control+R to reload the data into QlikView document. Now follow the same steps as above in − Creating Sheet Objects to create a QlikView Table Box for displaying the result of the script as shown below. The Match() function in QlikView is used to match the value of a string on expression with data value present in a column. It is similar to the in function that we see in SQL language. It is useful to fetch rows containing specific strings and it also has an extension in form of wildmatch() function. Let us consider the following data as input file for the examples illustrated below. Product_Id,Product_Line,Product_category,Product_Subcategory 1,Sporting Goods,Outdoor Recreation,Winter Sports & Activities 2,Food, Beverages & Tobacco,Food Items,Fruits & Vegetables 3,Apparel & Accessories,Clothing,Uniforms 4,Sporting Goods,Athletics,Rugby 5,Health & Beauty,Personal Care 6,Arts & Entertainment,Hobbies & Creative Arts,Musical Instruments 7,Arts & Entertainment,Hobbies & Creative Arts,Orchestra Accessories 8,Arts & Entertainment,Hobbies & Creative Arts,Crafting Materials 9,Hardware,Tool Accessories,Power Tool Batteries 10,Home & Garden,Bathroom Accessories,Bath Caddies 11,Food, Beverages & Tobacco,Food Items,Frozen Vegetables 12,Home & Garden,Lawn & Garden,Power Equipment 13,Office Supplies,Presentation Supplies,Display 14,Hardware,Tool Accessories,Jigs 15,Baby & Toddler,Diapering,Baby Wipes The following script shows the Load script, which reads the file named product_categories.csv. We search the field Product_Line for values matching with strings 'Food' and 'Sporting Goods'. Let us create a Table Box sheet object to show the data generated by the match function. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below. The wildmatch() function is an extension of match() function in which we can use wildcards as part of the strings used to match the values with values in the fields being searched for. We search for the strings 'Off*','*ome*. Let us create a Table Box sheet object to show the data generated by the wildmatch function. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below. The Rank() function in QlikView is used to display the rank of the values in a field as well as return rows with specific rank value. So it is used in two scenarios. First scenario is in QlikView charts to display the ranks of the values in the field and second is in Aggregate function to display only the rows, which have a specific rank value. The data used in the examples describing Rank function is given below. You can save this as a .csv file in a path in your system where it is accessible by QlikView. Product_Id,Product_Line,Product_category,Quantity,Value 1,Sporting Goods,Outdoor Recreation,12,5642 2,Food, Beverages & Tobacco,38,2514 3,Apparel & Accessories,Clothing,54,2365 4,Apparel & Accessories,Costumes & Accessories,29,4487 5,Sporting Goods,Athletics,11,812 6,Health & Beauty,Personal Care,21,6912 7,Arts & Entertainment,Hobbies & Creative Arts,58,5201 8,Arts & Entertainment,Paintings,73,8451 9,Arts & Entertainment,Musical Instruments,41,1245 10,Hardware,Tool Accessories,2,456 11,Home & Garden,Bathroom Accessories,36,241 12,Food,Drinks,54,1247 13,Home & Garden,Lawn & Garden,29,5462 14,Office Supplies,Presentation Supplies,22,577 15,Hardware,Blocks,53,548 16,Baby & Toddler,Diapering,19,1247 17,Baby & Toddler,Toys,9,257 18,Home & Garden,Pipes,81,1241 19,Office Supplies,Display Board,29,2177 The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into QlikView's memory. Next, we follow the steps given below to create a chart, which shows the rank of the filed Value described with respect to the dimension Product_Line. Click on the Chart wizard and choose the option straight table as the chart type. Click Next. From the First Dimension drop down list, choose Product_Line as dimension. Click Next. In the custom expression field, mention the rank expression as shown below. Here we are considering the numeric field named Value, which represents the Sales value for each category under each Product Line. Click Next. On clicking Finish in the above step, the following chart appears which shows the rank of the sales value of each Product Line. The aggregate functions like − max, min etc. can take rank as an argument to return rows satisfying certain rank values. We consider the following expression to be out in the script editor, which will give the rows containing highest sales under each Product line. # Load the records with highest sales value for each product line. LOAD Product_Line, max(Value,1) FROM [E:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq) group by Product_Line; Let us create a Table Box sheet object to show the data generated by the above given script. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below. The peek() function in QlikView is used to fetch the value of a field from a previous record and use it in calculations. Let us consider the monthly sales figure as shown below. Save the data with file name monthly_sales.csv. Month,Sales Volume March,2145 April,2458 May,1245 June,5124 July,7421 August,2584 September,5314 October,7846 November,6532 December,4625 January,8547 February,3265 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into QlikView's memory. LOAD Month, [Sales Volume], peek('Sales Volume') as Prevmonth FROM [C:\Qlikview\data\monthly_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); Let us create a Table Box sheet object to show the data generated by the above script. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the csv file in the QlikView Table Box as shown below. Also set the sort order as shown below to get the result in the same order of the field Month as it is in the source. On completing the above steps and clicking Finish, we get the Table box showing the data as given below. The peek() can be used in calculations involving other columns. Let us display the percentage change for sales volume for each month. The following script achieves this result. LOAD Month, [Sales Volume], peek('Sales Volume') as Prevvolume, (([Sales Volume]-peek('Sales Volume')))/peek('Sales Volume')*100 as Difference FROM [C:\Qlikview\data\monthly_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); Let us create a Table Box sheet object to show the data generated by the above script. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below. The RangeSum() function in QlikView is used to do a selective sum on chosen fields which is not easily achieved by the sum function. It can take expressions containing other functions as its arguments and return the sum of those expressions. Let us consider the monthly sales figure as shown below. Save the data with file name monthly_sales.csv. Month,Sales Volume March,2145 April,2458 May,1245 June,5124 July,7421 August,2584 September,5314 October,7846 November,6532 December,4625 January,8547 February,3265 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into QlikView's memory. LOAD Month, [Sales Volume] FROM [C:\Qlikview\data\monthly_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); With the above data loaded into QlikView's memory, we edit the script to add a new column, which will give a rolling sum of the month wise sales volume. For this, we also take the help of the peek function discussed in the earlier chapter to hold the value of the previous record and add it to the sales volume of the current record. The following script achieves the result. LOAD Month, [Sales Volume], rangesum([Sales Volume],peek('Rolling')) as Rolling FROM [C:\Qlikview\data\monthly_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); Let us create a Table Box sheet object to show the data generated by the above given script. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below. QlikView documents are the files that contain all the objects used for the data presentation and analysis. It contains the sheets, variables, data model, source-data connection details, and even the data that is loaded after pulling it from the source. We can quickly find out the basic information of a QlikView document. Click on Help → document Support Info. Given below is a sample output. We can set an image as the background image for a document using the check box Wallpaper Image check box under the General tab. We choose an image and align it at the left top position using the dropdown buttons. The following screen appears on selecting the above options. The QlikView document contains various Sheet objects, which can be moved around by dragging them and placed anywhere in the document. Let us create two sheet objects, a Table box and a Statistics Box. You can follow the earlier chapters where we have already learnt to create sheet objects. In addition, we are using the file Product_sales.csv, which is mentioned here. Details of the Sheets objects can be seen using the "Sheets" tab. It shows all the sheets contained in the document and for each sheet, the sheet objects are shown. Both the sheets and sheet objects have unique IDs. We can also edit various properties of these objects from this tab itself. A QlikView document can be scheduled to refresh at some desired intervals. This is done using the Schedule tab available under the Document properties window. A list box represents the list of all the values of a specific field. Selecting a value in list box highlights the related values in other sheet objects. This helps in faster visual analysis. It is also very useful to follow a drill down path among various sheet objects. It also has a search feature, which allows to search for specific values in the list box which is very helpful for a very long list of values. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into QlikView's memory. LOAD Product_Line, Product_category, Value FROM [C:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); Creation of List Box involves navigating through menu Layout → New Sheet Object → List Box. The following screen shows these steps. Next, we choose Product category as the field on which we build the list box. Finishing the above steps brings the following screen, which shows the values of Product category as a list box. When the List Box contains very large number of values, it is difficult to scroll down and look for it. So the search box at the top of the list box can be used to type the search string. The relevant values appear as soon as the first letter is typed. Other Sheet Objects automatically get associated with the List Box and the association is easily observed by selecting values form the list box. A Multi Box represents the list of all the values from multiple fields as drop down values. Similar to list box, the selection of a value in Multi Box highlights the related values in other sheet objects. This helps in faster visual analysis. It is also very useful to follow a drill down path among various sheet objects. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into the QlikView's memory. LOAD Product_Line, Product_category, Value FROM [C:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); Creation of Multi Box involves navigating through menu Layout → New Sheet Object → Multi Box. The following screen shows these steps. Next we choose the fields of the Products sales tables to build the Multi Box. Finishing the above steps brings the following screen, which shows the values of Product category as a Multi box. Other Sheet Objects automatically get associated with the Multi Box and the association is easily observed by selecting values from the Multi Box. QlikView text Object is used to show some descriptive information about the QlikView report being displayed. It can also show calculations based on certain expressions. It is mainly used for displaying nicely formatted information using colors and different font types in a box separately from the other Sheet Objects. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. Edit the load script to add the following code. Click "OK" and press "Control+R" to load the data into the QlikView's memory. LOAD Product_Line, Product_category, Value FROM [C:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); For the above data, let us create a Table Box , which will show the data in a tabular form. Go to the menu Layout → New Sheet Object → Table Box and choose the column as shown below. Click Apply and then OK to finish creating the Table box. The following screen appears. For the above data, let us create a Text Object. Go to the menu Layout → New Sheet Object → Text Object as shown below. On the text box created above, right click and choose properties. Then enter the content to be displayed on the Text Object in the Text box under the General tab as shown below. The background color of the Text Object can be set using the background option in the General tab. The final Text Object is shown below. If we click on some Product Line to filter it, then the content in the Text Object changes accordingly to reflect the new values. Bar charts are very widely used charting method to study the relation between two dimensions in form of bars. The height of the bar in the graph represents the value of one dimension. The number of bars represent the sequence of values or grouped values of another dimension. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option form the "Data from Files" tab and browse for the file containing the above data. Edit the load script to add the following code. Click "OK" and press "Control+R" to load the data into the QlikView's memory. LOAD Product_Line, Product_category, Value FROM [C:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); For the above data, let us create a Table Box, which will show the data in a tabular form. Go to the menu Layout → New Sheet Object → Table Box and choose the column as shown below. Click Apply and then OK to finish creating the Table box. The below given screen appears. To start creating a bar chart, we will use the quick chart wizard. On clicking it, the following screen appears which prompts for selecting the chart type. Choose bar Chart and click Next. Choose Product Line as the First Dimension. The chart expression is used to apply the functions like Sum, Average, or Count on the fields with numeric values. We will apply the Sum function on the filed named Value. Click Next. The Chart format defines the style and orientation of the chart. We choose the first option in each category. Click Next. The Bar chart appears as shown below. It shows the height of the field value for different product lines. A pie-chart is a representation of values as slices of a circle with different colors. The slices are labeled and the numbers corresponding to each slice is also represented in the chart. QlikView creates pie-chart using the chart wizard or chart Sheet Object. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. Edit the load script to add the following code. Click "OK" and press "Control+R" to load the data into the QlikView's memory. LOAD Product_Line, Product_category, Value FROM [C:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); To start creating a Pie chart, we will use the quick chart wizard. On clicking it, the following screen appears which prompts for selecting the chart type. Choose Pie Chart and click Next. Choose Product Line as the First Dimension. The chart expression is used to apply the functions like Sum, Average or Count on the fields with numeric values. We will apply the Sum function on the filed named Value. Click Next. The Chart format defines the style and orientation of the chart. We choose the third option. Click Next. The Bar chart appears as shown below. It shows the height of the field value for different product lines. A Dashboard is a powerful feature to display values from many fields simultaneously. QlikeView's feature of data association in memory can display the dynamic values in all the sheet objects. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. Edit the load script to add the following code. Click "OK" and press "Control+R" to load the data into the QlikView's memory. LOAD Product_Line, Product_category, Value FROM [C:\Qlikview\data\product_sales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); We choose the fields from the above input data as matrices to be displayed in the dashboard. For this, we follow the steps in the menu Layout → Select Fields. In the next screen, choose the available fields to be displayed in the dashboard. Click "OK". The following screen appears displaying all the fields NNow we add a chart to the dashboard by right-clicking anywhere in the sheet and choosing New Sheet Object → Chart. Let us choose the chart type as a bar chart to display the sales values for various product Lines. Let us select the Product Line as the Chart Dimension. The expression to display the sales value for the Product Line dimension is written in the expression editor. Given below is the dashboard displayed after finishing the above steps. The values in the above Dashboard can be selected for filtering specific products and the chart changes accordingly. In addition, the associated values are highlighted. Data Transformation is the process of modifying the existing data to a new data format. It can also involve filtering out or adding some specific values to the existing data set. QlikView can carry out data transformation after reading it to its memory and using many in-built functions. Let us consider the following input data, which represents the sales figures of each month. This is stored as a csv file with name quarterly_sales.csv Month,SalesVolume March,2145 April,2458 May,1245 Sales Values in Q2 June,5124 July,7421 August,2584 Sales Values in Q3 September,5314 October,7846 November,6532 December,4625 January,8547 February,3265 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option form the "Data from Files" tab and browse for the file quarterlt_sales.csv. Click next. The next screen prompts us to choose some data transformation. Click on the button Enable Transformation Step. In this step, we will select the transformation to eliminate the rows, which describe the quarter. We select Garbage → delete marked and select the two rows, which are not required. Click Next. After selecting the type of Transformation and the rows to be removed, the next screen prompts us for any further transformation like selecting a where clause or adding any Prefixes. We will ignore this step and click Finish. The Load script for the above data after all the transformation steps are complete is given below. The transformed data can be displayed by using a Table Box sheet object. The steps to create it are given below. Next, we choose the fields for the Table Box. The Table Box now displays the data in the sheet. The Fill function in QlikView is used to fill values from existing fields into a new field. Let us consider the following input data, which represents the actual and forecasted sales figures. Month,Forecast,Actual March,2145,2247 April,2458, May,1245, June,5124,3652 July,7421,7514 August,2584, September,5314,4251 October,7846,6354 November,6532,7451 December,4625,1424 January,8547,7852 February,3265, The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. After clicking Next in the above step, we choose the Enable Transformation Step button to carry out the required data transformation. As we are going to use the Fill function, let us choose the Fill tab, which displays th empty values under the Actual Field. On clicking the Fill button, the option to choose target column and the cell condition appears. We choose column three, as we want to fill the empty values of this column with values from same row in column two. Also, choose the Cell Value as empty so that only the empty cells will be overwritten with new values. On completing the above steps, we get the transformed data as shown below. The load script for the transformed data can be seen using the script editor. The script shows the expression, which replaces the empty cell values. The transformed data can be seen by creating a Table Box using the option in the menu Layout → New Sheet Object. Column Manipulation is a type of Data Transformation in which a new column is populated with values from an existing column, which meets certain criteria. The criteria can be an expression, which is created as part of the Data Transformation step. Let us consider the following input data, which represents the actual and forecasted sales figures. Month,Forecast,Actual March,2145,2247 April,2458,2125 May,1245,2320 June,5124,3652 July,7421,7514 August,2584,3110 September,5314,4251 October,7846,6354 November,6532,7451 December,4625,1424 January,8547,7852 February,3265,2916 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. After clicking Next, we choose the Enable Transformation Step button to carry out the required data transformation. Choose the Column tab and then choose the New button. It asks to specify the New column and the Row Condition. We specify column 3 as the source column and pick the values, which start with two as the Row Condition. On completing the above steps, we get the transformed data as shown below. The load script for the Transformed data can be seen using the script editor. The script shows the expression, which creates the new column with required values. The transformed data can be seen by creating a Table Box using the option in the menu Layout → New Sheet Object. The Rotating table in QlikView is similar to the column and row transpose feature in Microsoft Excel but with some additional options. We can transpose columns in multiple directions and they give different results. In this chapter, we will be seeing the normal transpose option of converting rows to columns. Let us consider the following input data, which represents the actual and forecasted sales figures. Month,Forecast,Actual March,2145,2247 April,2458, May,1245, June,5124,3652 July,7421,7514 August,2584, September,5314,4251 October,7846,6354 November,6532,7451 December,4625,1424 January,8547,7852 February,3265, The above data is loaded to QlikView memory by using the script editor. Open the script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. After clicking Next, we choose the Enable Transformation Step button to carry out the required data transformation. As we are going to use the Rotate function, let us choose the Rotate tab which displays the values of all the fields. We click the Transpose button to transpose the above data. The transposed data appears as shown below. The load script for the Transformed data can be seen using the script editor. The script shows the expression, which replaces the empty cell values. The transformed data can be seen by creating a Table Box using the option in the menu Layout → New Sheet Object. Dimensions and Measures are fundamental entities, which are always used in data analysis. For example, consider the result of the analysis, “what is the percentage change in volume of sales for each quarter?” In this case, each quarter represents the Dimensions, which is the name of the quarter. The percentage change in volume represents the Measures, which is a calculation with respect to each value in the dimension. Below are some widely accepted definition of these two terms. Dimension − It is a descriptive field in the data set which represents few distinct values. Examples − Month, Year, Product ID etc. Measures − It is a numeric field on which some calculations are performed for each distinct value of dimension. Let us consider the following input data, which represents the sales volume and Revenue of different product lines and product categories in different regions. Save the data into a .csv file. ProductID,ProductCategory,Region,SalesVolume, Revenue 1,Outdoor Recreation,Europe,457,25841 2,Clothing,Europe,125,54281 3,Costumes & Accessories,South Asia,781,54872 4,Athletics,South Asia,839,87361 5,Personal Care,Australia,473,15425 6,Arts & Entertainment,North AMerica,625,84151 7,Hardware,South America,772,45812 The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into the QlikView's memory We can see the structure of the table by following the menu File → Table Viewer or pressing Control+T. The following screen comes up in which we have marked the dimensions inside a green box and the measures inside a red box. Let us create a straight table chart showing the calculation using above dimensions and measures. Click on the Quick Chart Wizard as shown below. Next, click on the Straight Table option. Click Next. In this screen, we choose Region as the dimension as we want to select the total revenue for each region. The Next screen prompts for applying the calculation on a measure field. We choose to apply Sum on the field Revenue. On completing the above steps, we get the final chart which shows the total revenue(Measure) for each region(Dimension). A start schema model is a type of data model in which multiple dimensions are linked to a single fact table. Of course, in bigger models there can be multiple facts tables linked to multiple dimensions and other fact tables. The usefulness of this model lies in performing fast queries with minimal joins among various tables. The fact table contains data, which are measures and have numeric values. Calculations are applied on the fields in the fact table. The unique keys of the dimension tables are used in linking it to the fat table, which also has a key usually with the same field name. Therefore, the Fact table contains the keys from the entire dimension table and forms a concatenated primary key used in various queries. Given below is a list of tables, which contain the data for different products from various suppliers and regions. Also the supply happens at different time intervals, which are captured in the Time dimension table. It contains the Product Category and Product Names. The Product ID field is the unique Key. ProductID,ProductCategory,ProductName 1,Outdoor Recreation,Winter Sports & Activities 2,Clothing,Uniforms 3,Lawn & Garden Power, Equipment 4,Athletics,Rugby 5,Personal Care,Shaver 6,Arts & Entertainment,Crafting Materials 7,Hardware,Power Tool Batteries It contains the Region Names where the suppliers are based. The RegionID field is the unique Key. RegionID,Continent,Country 3,North America, USA 7,South America, Brazil 12,Asia,China 2,Asia,Japan 5,Europe,Belgium It contains the Supplier Names, which supply the above products. The SupplierID field is the unique Key. SupplierID,SupplierName 3S12,Supre Suppliers 4A15,ABC Suppliers 4S66,Max Sports 5F244,Nice Foods 8A45,Artistic angle It contains the Time periods when the supply of the above products occur. The TimeID field is the unique Key. TimeID,Year,Month 1,2012,Feb 2,2012,May 3,2012,Sep 4,2013,Aug 5,2014,Jan 6,2014,Nov It contains the values for the quantities supplied and percentage of defects in them. It joins to each of the above dimensions through keys with same name. ProductID,RegionID,TimeID,SupplierID,Quantity, DefectPercentage 1,3,3,5F244,8452,12 2,3,1,4S66,5124,8.25 3,7,1,8A45,5841,7.66 4,12,2,4A15,5123,1.25 5,5,3,4S66,7452,8.11 6,2,5,4A15,5142,3.66 7,2,1,4S66,452,2.06 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into QlikView's memory. Below is the script which appears after each of the above file is read. LOAD ProductID, ProductCategory, ProductName FROM [C:\Qlikview\images\StarSchema\Product_dimension.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); LOAD TimeID, Year, Month FROM [C:\Qlikview\images\StarSchema\Time.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); LOAD SupplierID, SupplierName FROM [C:\Qlikview\images\StarSchema\Suppliers.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); LOAD RegionID, Continent, Country FROM [C:\Qlikview\images\StarSchema\Regions.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); LOAD ProductID, RegionID, TimeID, SupplierID, Quantity, DefectPercentage FROM [C:\Qlikview\images\StarSchema\Supplier_quantity.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); After reading the above data into QlikView memory, we can look at the data model, which shows all the tables, fields, and relationship in form of a star schema. A Synthetic Key is QlikView's solution to create an artificial key when there is ambiguity about which key to use between two tables. This situation arises when two tables have two or more fields in common. QlikView's feature of creating association in memory automatically detects this scenario and creates an additional table, which will hold the value of the new key created. Let us consider the following two CSV data files, which are used as input for further illustrations. Sales: ProductID,ProductCategory,Country,SaleAmount 1,Outdoor Recreation,Italy,4579 2,Clothing,USA,4125 3,Costumes & Accessories,South Korea,6521 Product: ProductID, Country 3,Brazil 3,China 2,Korea 1,USA We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Next, we look at the data model by using the menu command for table viewer, Control+T. The following screen comes up, which shows the creation of a third table that supplies the value of the synthetic key as both the tables have ProductID and Country as matching keys. Synthetic keys indicate the flaw in the data model that is being used. They do not cause any issue in the correctness of the data or performance of the report. Things will work fine if a big data model has one or two instances of synthetic keys. However, if we have too many of them, then that is an implication to redesign the data model. Many times, we need some data to be generated programmatically by the software being used, which is not coming from a source. For example, 100 random numbers or just the dates of 23rd week of a year. A data analyst may need such data to be created to perform some analysis on the data that does not contain these values as it arrived. QlikView provides a function called Autogenerate, which can be used for such requirement. Consider a scenario where we need to find only the dates, which are a Thursday or a Sunday. We need to find it for the range starting today until the end of the year. We create the following script, which will achieve this. We declare two variables to capture the first day of the current month and end of the year. Next we apply various functions and a filter condition to generate the required values. The recno() function creates one record for each of these dates. We add Autogenerate function giving the variables as the range. On loading the above script to QlikView's memory and creating a Table Box using the menu Layout → New Sheet Objects → Table Box, we get the data created as shown below. While analyzing data, we come across situations where we desire columns to become rows and vice-versa. It is not just about transposing, it also involves rolling up many columns together or repeating many values in a row many times to achieve the desired column and row layout in the table. Consider the following input data, which shows region wise sales of a certain product for each quarter. We create a delimited file (CSV) with the below given data. Quarter,Region1,Region2,Region 3 Q1,124,421,471 Q2,415,214,584 Q3,417,321,582 Q4,751,256,95 We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. After choosing the options as shown below, click Next. In the next window (File Wizard → Options), click on the Crosstable button. It highlights the columns in different colors. The pink color shows the qualifier field, which is going to be repeated across many rows for each value of in the Attribute Field. The cell values under the Attribute fields are taken as the data. Click OK. The transformed data appears in which all the Region fields are clubbed to one column but with values repeating for each quarter. The Load script for the crosstable transformations shows the commands given below. On creating a Table Box sheet object using the menu Layout → New Sheet Objects → Table Box, we get the following output. Straight Tables are most widely used sheet object to display data in QlikView. They are very simple yet powerful with features like column rearrangement, sorting and coloring the background etc. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. The following screen appears. Click "OK" and press "Control+R" to load the data into the QlikView's memory Next, we create a new sheet Object of type Table Box. We follow the menu as shown below. QlikView prompts for the columns to be chosen which will be displayed in the final Table Box. We choose all the columns and use the Promote or Demote option to set the order of the columns. Next, we choose the style tab to give specific background colors to the display data. The current style option lists many pre-built styles. We choose Pyjama Red with Stripes every two rows. We can reorder the positions of the columns by pressing and holding the mouse button at the column headers and then dragging it to the desired position. Pivot Tables are widely used in data analysis to present sum of values across many dimensions available in the data. QlikView's Chart option has the feature to create a Pivot Table by choosing the appropriate chart type. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Value Sporting Goods,Outdoor Recreation,5642 Food, Beverages & Tobacco,2514 Apparel & Accessories,Clothing,2365 Apparel & Accessories,Costumes & Accessories,4487 Sporting Goods,Athletics,812 Health & Beauty,Personal Care,6912 Arts & Entertainment,Hobbies & Creative Arts,5201 Arts & Entertainment,Paintings,8451 Arts & Entertainment,Musical Instruments,1245 Hardware,Tool Accessories,456 Home & Garden,Bathroom Accessories,241 Food,Drinks,1247 Home & Garden,Lawn & Garden,5462 Office Supplies,Presentation Supplies,577 Hardware,Blocks,548 Baby & Toddler,Diapering,1247 Baby & Toddler,Toys,257 Home & Garden,Pipes,1241 Office Supplies,Display Board,2177 The above data is loaded to the QlikView’s memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. The following screen appears. Click "OK" and press "Control+R" to load the data into QlikView's memory. Next, we use the chart wizard to select the Pivot Table option. Click Next. In the next screen, we choose Product_Line as the first dimension for the chart. The next screen prompts us for selecting the chart expression where we choose the sum of value. On clicking next, we get the screen to choose chart format in which we select Pyjama Green as the style and the default mode. Completing the above steps gives us the final chart as below. QlikView's Set Analysis feature is used to segregate the data in different sheet objects into many sets and keeps the values unchanged in some of them. In simpler terms, it creates an option to not associate some sheet objects with others while the default behavior is all sheet objects get associated with each other. This helps in filtering the data in one sheet object and seeing the corresponding result in others, while the sheet object chosen as a different set displays values as per its own filters. Let us consider the following input data, which represents the sales figure of different product lines and product categories. Product_Line,Product_category,Month,Value Arts & Entertainment,Hobbies & Creative Arts,Jan,5201 Arts & Entertainment,Paintings,Feb,8451 Arts & Entertainment,Musical Instruments,Jan,1245 Baby & Toddler,Diapering,Mar,1247 Baby & Toddler,Toys,Dec,257 Apparel & Accessories,Clothing,Feb,574 Apparel & Accessories,Costumes & Accessories,Apr,1204 Arts & Entertainment,Musical Instruments,Apr,3625 Baby & Toddler,Diapering,Apr,1281 Apparel & Accessories,Clothing,Jul,2594 Arts & Entertainment,Paintings,Sep,6531 Baby & Toddler,Toys,May,7421 Apparel & Accessories,Clothing,Aug,2541 Arts & Entertainment,Paintings,Oct,2658 Arts & Entertainment,Musical Instruments,Mar,1185 Baby & Toddler,Diapering,Jun,1209 The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. A screen appears as shown below. Choose all the fields available to create a table box using the menu option Layout → New Sheet Objects → Table Box and a list box containing the month’s field using the menu option Layout → New Sheet Objects → List Box. Also, create a straight table chart showing the total sales under each product category. Now we can observe the association between these three sheet objects by selecting some values in one of them. Let us select the month Apr and Jan from the Month list Box. We can see the change in values in the Table Box and chart showing the related values. Next, we clone the sales sum chart to produce a new set of data not associated with other sheet objects. Right click on the chart Sales Sum and click on the option Clone as shown below. Another copy of the same chart appears in the QlikView document. Next, we choose the second copy of the chart Sales Sum and right click it to get the chart properties. We create an expression called Sales values writing the formula under the Definition tab as shown below. On completing the above given steps, we find that when we select the month June we get the associated values in the Table Box and Sales Sum chart. However, the April sales does not change as it is based on the data from the set expression. Joins in QlikView are used to combine data from two data sets into one. Joins in QlikView mean the same as in joins in SQL. Only the column and row values that match the join conditions are shown in the output. In case you are completely new to joins, you may like to first learn about them here. Let us consider the following two CSV data files, which are used as input for further illustrations. Product List: ProductID,ProductCategory 1,Outdoor Recreation 2,Clothing 3,Costumes & Accessories 4,Athletics 5,Personal Care 6,Hobbies & Creative Arts ProductSales: ProductID,ProductCategory,SaleAmount 4,Athletics,1212 5,Personal Care,5211 6,Hobbies & Creative Arts,1021 7,Display Board,2177 8,Game,1145 9,soap,1012 10,Beverages & Tobacco,2514 We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Then we edit the commands in the script to create an inner join between the tables. Inner join fetches only those rows, which are present in both the tables. In this case, the rows available in both Product List and Product Sales table are fetched. We create a Table Box using the menu Layout → New Sheet Objects → Table Box where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed. Left join involves fetching all the rows from the table in the left and the matching rows from the table in the right. Sales: LOAD ProductID, ProductCategory, SaleAmount FROM [C:\Qlikview\data\product_lists.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); LEFT JOIN(Sales) LOAD ProductID, ProductCategory FROM [C:\Qlikview\data\Productsales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); We create a Table Box using the menu Layout → New Sheet Objects → Table Box, where we choose all the three fields − ProductID, ProductCategory and SaleAmount to be displayed. Right join involves fetching all the rows from the table in the right and the matching rows from the table in the left. Sales: LOAD ProductID, ProductCategory, SaleAmount FROM [C:\Qlikview\data\product_lists.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); RIGHT JOIN(Sales) LOAD ProductID, ProductCategory FROM [C:\Qlikview\data\Productsales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); We create a Table Box using the menu Layout → New Sheet Objects → Table Box, where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed. Outer join involves fetching all the rows from the table in the right as well as from the table in the left. Sales: LOAD ProductID, ProductCategory, SaleAmount FROM [C:\Qlikview\data\product_lists.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); OUTER JOIN(Sales) LOAD ProductID, ProductCategory FROM [C:\Qlikview\data\Productsales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); We create a Table Box using the menu Layout → New Sheet Objects → Table Box where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed. The keep command in QlikView is used to combine data from two data sets keeping both the data sets available in memory. It is very similar to joins we covered in the previous chapter except for two major differences. First difference is − in case of keep; both the datasets are available in QlikView's memory while in join the load statements produce only one data set from which you have to choose the columns. The second difference being − there is no concept of outer keep where as we have outer join available in case of joins. Let us consider the following two CSV data files, which are used as input for further illustrations. Product List: ProductID,ProductCategory 1,Outdoor Recreation 2,Clothing 3,Costumes & Accessories 4,Athletics 5,Personal Care 6,Hobbies & Creative Arts Product Sales: ProductID,ProductCategory,SaleAmount 4,Athletics,1212 5,Personal Care,5211 6,Hobbies & Creative Arts,1021 7,Display Board,2177 8,Game,1145 9,soap,1012 10,Beverages & Tobacco,2514 We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Then we edit the commands in the script to create an inner keep between the tables. Inner keep fetches only those rows, which are present in both the tables. In this case, the rows available in both Product List and Product Sales table are fetched. We create a Table Boxes using the menu Layout → New Sheet Objects → Table Box. First, we choose only the productSales table, which gives us the fields - ProductID, ProductCategory and SaleAmount to be displayed. Next, we choose the ProductList data set, which gives us the fields ProductID and ProductCategory. Finally, we choose the All Tables option and get all the available fields from all the tables. The following report shows all the Tables Boxes from the above given steps. Left keep is similar to left join, which keeps all the rows from the table in the left along with both the data set being available in QlikView's memory. The following script is used to create the resulting data sets with left keep command. productsales: LOAD ProductID, ProductCategory, SaleAmount FROM [C:\Qlikview\data\product_lists.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); left keep(productsales) productlists: LOAD ProductID, ProductCategory FROM [C:\Qlikview\data\Productsales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); When we change the script as above and refresh the data in the report using Control+R, we get the following data in the sheet objects. Right keep is similar to left join, which keeps all the rows from the table in the right along with both the data set being available in QlikView's memory. The following script is used to create the resulting data sets with left keep command. productsales: LOAD ProductID, ProductCategory, SaleAmount FROM [C:\Qlikview\data\product_lists.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); right keep(productsales) productlists: LOAD ProductID, ProductCategory FROM [C:\Qlikview\data\Productsales.csv] (txt, codepage is 1252, embedded labels, delimiter is ',', msq); When we change the script as above and refresh the data in the report using Control+R, we get the following data in the sheet objects. Concatenation feature in QlikView is used to append the rows from one table to another. It happens even when the tables have different number of columns. It differs from both Join and Keep command, as it does not merge the matching rows from two tables into one row. Let us consider the following two CSV data files, which are used as input for further illustrations. Please note the second data set has an additional column named Country. SalesRegionOld.csv ProductID,ProductCategory,Region,SaleAmount 1,Outdoor Recreation,Europe,4579 2,Clothing,Europe,4125 3,Costumes & Accessories,South Asia,6521 4,Athletics,South Asia,4125 5,Personal Care,Australia,5124 6,Arts & Entertainment,North AMerica,1245 7,Hardware,South America,456 SalesRegionNew.csv ProductID,ProductCategory,Region,Country,SaleAmount 6,Arts & Entertainment,North AMerica,USA,1245 7,Hardware,South America,Brazil,456 8,Home & Garden,South America,Brazil,241 9,Food,South Asia,Singapore,1247 10,Home & Garden,South Asia,China,5462 11,Office Supplies,Australia,Australia,577 We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Then we edit the commands in the script to apply the concatenation between the tables. Next, we load the above data to QlikView's memory and create a Table Box by using the menu Layout → New Sheet Objects → Table Box where we choose all the available fields to be displayed as shown below. Completing above steps we get the Table box displayed as shown below. Please note the duplicate rows for the product ID 6 and 7. Concatenate does not eliminate the duplicates. In QlikView, many times we need to create a calendar reference object, which can be linked to any data set present in QlikView's memory. For example, you have a table that captures the sales amount and sales date but does not store the weekday or quarter, which corresponds to that date. In such a scenario, we create a Master Calendar which will supply the additional date fields like Quarter, Day etc. as required by any data set. Let us consider the following CSV data files, which are used as input for further illustrations. SalesDate,SalesVolume 3/28/2012,3152 3/30/2012,2458 3/31/2012,4105 4/8/2012,6245 4/10/2012,5816 4/11/2012,3522 We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Next, we load the above data to QlikView's memory and create a Table Box by using the menu Layout → New Sheet Objects → Table Box where we choose all the available fields to be displayed as shown below. Next, we create the Master Calendar by writing the following script in the script editor. Here we use the table DailySales as a resident table from which we capture the Maximum and Minimum dates. We load each of the dates within this range using the second load statement above the resident load. Finally, we have a third load statement, which extracts the year, quarter, month etc. from the SalesDate values. After creation of the complete load script along with the master calendar, we create a table box to view the data using the menu Layout → New Sheet Objects → Table Box The final output shows the table showing the Quarter and Month values, which are created using the Sales data and Master Calendar. Mapping table is a table, which is created to map the column values between two tables. It is also called a Lookup table, which is only used to look for a related value from some other table. Let us consider the following input data file, which represents the sales values in different regions. ProductID,ProductCategory,Region,SaleAmount 1,Outdoor Recreation,Europe,4579 2,Clothing,Europe,4125 3,Costumes & Accessories,South Asia,6521 4,Athletics,South Asia,4125 5,Personal Care,Australia,5124 6,Arts & Entertainment,North AMerica,1245 7,Hardware,South America,456 8,Home & Garden,South America,241 9,Food,South Asia,1247 10,Home & Garden,South Asia,5462 11,Office Supplies,Australia,577 The following data represents the countries and their regions. Region,Country Europe,Germany Europe,Italy South Asia,Singapore South Asia,Korea North AMerica,USA South America,Brazil South America,Peru South Asia,China South Asia,Sri Lanka The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and ess Control+R to load the data into the QlikView's memory. Let us create two table boxes for each of the above table as shown below. Here we cannot get the value of country in the Sales region report. The following script produces the mapping table, which maps the region value from the sales table with the country value from the MapCountryRegion table. On completing the above steps and creating a Table box to view the data, we get the country columns along with other columns from Sales table. Circular Reference occurs when we can traverse from one table to another using two or more different paths. This means you can join Table1 with Table2 directly using a column or you can also first join Table1 with Table3 and then table3 with Table2. This can lead to incorrect result in the output formed by a data model, which loads all these three tables. QlikView prevents the load of such data into its memory once it recognizes a circular reference. Let us consider the following three CSV data files, which are used as input for further illustrations. SalesCountries: ProductID,ProductCategory,Country,SaleAmount 1,Outdoor Recreation,Italy,4579 2,Clothing,USA,4125 3,Costumes & Accessories,South Korea,6521 4,Athletics,Japan,4125 5,Personal Care,Brazil,5124 6,Arts & Entertainment,China,1245 7,Hardware,South America,456 8,Home & Garden,Peru,241 9,Food,India,1247 10,Home & Garden,Singapore,5462 11,Office Supplies,Hungary,577 ProductCountry: ProductID, Country 3,Brazil 3,China 2,Korea 1,USA 2,Singapore 7,Sri Lanka 1,Italy We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. After creating the above script, we load the data to QlikView's memory using the command Control+R. This is when we get the error prompt mentioning the presence of circular loop in the tables getting loaded. To find the exact cause of the above warning we can look at the data model by using the menu command for table viewer - Control+T. The following screen comes up, which clearly shows the circular reference. Here the join between RegionCountry and SalesRegion can be directly achieved using the field Region. It can also be achieved by first going to the table ProductCountry, using the field Country and then mapping ProdcutID with Salesregion. The above circular reference can be resolved by renaming some of the columns in the data sets so that QlikView does not form an association between the tables automatically using the column names. For this, we will rename country column in RegionCountry to SalesCountry. In the data set ProdcuCountry, we rename the Country column to ProductCountry. The Rectified data model after renaming the column above can be seen using the command Control+T. Now we can see that the relationship between the tables does not form a loop. Pressing Control+R to reload the data does not give us the warning anymore and we can use this data to create reports. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3317, "s": 2920, "text": "QlikView is a leading Business Discovery Platform. It is unique in many ways as compared to the traditional BI platforms. As a data analysis tool, it always maintains the relationship between the data and this relationship can be seen visually using colors. It also shows the data that are not related. It provides both direct and indirect searches by using individual searches in the list boxes." }, { "code": null, "e": 3650, "s": 3317, "text": "QlikView's core and patented technology has the feature of in-memory data processing, which gives superfast result to the users. It calculates aggregations on the fly and compresses data to 10% of original size. Neither users nor developers of QlikView applications manage the relationship between data. It is managed automatically." }, { "code": null, "e": 3869, "s": 3650, "text": "QlikView has patented technology, which enables it to have many features that are useful in creating advanced reports from multiple data sources quickly. Following is a list of features that makes QlikView very unique." }, { "code": null, "e": 4102, "s": 3869, "text": "Data Association is maintained automatically − QlikView automatically recognizes the relationship between each piece of data that is present in a dataset. Users need not preconfigure the relationship between different data entities." }, { "code": null, "e": 4335, "s": 4102, "text": "Data Association is maintained automatically − QlikView automatically recognizes the relationship between each piece of data that is present in a dataset. Users need not preconfigure the relationship between different data entities." }, { "code": null, "e": 4510, "s": 4335, "text": "Data is held in memory for multiple users, for a super-fast user experience − The structure, data and calculations of a report are all held in the memory (RAM) of the server." }, { "code": null, "e": 4685, "s": 4510, "text": "Data is held in memory for multiple users, for a super-fast user experience − The structure, data and calculations of a report are all held in the memory (RAM) of the server." }, { "code": null, "e": 4853, "s": 4685, "text": "Aggregations are calculated on the fly as needed − As the data is held in memory, calculations are done on the fly. No need of storing pre-calculated aggregate values." }, { "code": null, "e": 5021, "s": 4853, "text": "Aggregations are calculated on the fly as needed − As the data is held in memory, calculations are done on the fly. No need of storing pre-calculated aggregate values." }, { "code": null, "e": 5238, "s": 5021, "text": "Data is compressed to 10% of its original size − QlikView heavily uses data\ndictionary. Only essential bits of data in memory is required for any analysis. Hence, it compresses the original data to a very small size." }, { "code": null, "e": 5455, "s": 5238, "text": "Data is compressed to 10% of its original size − QlikView heavily uses data\ndictionary. Only essential bits of data in memory is required for any analysis. Hence, it compresses the original data to a very small size." }, { "code": null, "e": 5671, "s": 5455, "text": "Visual relationship using colors − The relationship between data is not shown by arrow or lines but by colors. Selecting a piece of data gives specific colors to the related data and another color to unrelated data." }, { "code": null, "e": 5887, "s": 5671, "text": "Visual relationship using colors − The relationship between data is not shown by arrow or lines but by colors. Selecting a piece of data gives specific colors to the related data and another color to unrelated data." }, { "code": null, "e": 6121, "s": 5887, "text": "Direct and Indirect searches − Instead of giving the direct value a user is looking for, they can input some related data and get the exact result because of the data association. Of course, they can also search for a value directly." }, { "code": null, "e": 6355, "s": 6121, "text": "Direct and Indirect searches − Instead of giving the direct value a user is looking for, they can input some related data and get the exact result because of the data association. Of course, they can also search for a value directly." }, { "code": null, "e": 6508, "s": 6355, "text": "The Free Personal Edition of QlikView can be downloaded from QlikView Personal Edition. You need to register with your details to be able to download." }, { "code": null, "e": 6740, "s": 6508, "text": "After downloading, the installation is a very straightforward process in which you need to accept the license agreement and provide the target folder for installation. The screen shots given below describe the entire setup process." }, { "code": null, "e": 6924, "s": 6740, "text": "Double clicking the QlikViewDesktop_x64Setup.exe will present a screen to select the language of your choice. On selecting English, the following screen is displayed. Then click Next." }, { "code": null, "e": 7053, "s": 6924, "text": "Read the license agreement and if you agree, choose the \"I accept the terms in the license agreement\" option. Then click \"Next\"." }, { "code": null, "e": 7116, "s": 7053, "text": "Provide your name and organization details. Then Click \"Next\"." }, { "code": null, "e": 7204, "s": 7116, "text": "You may accept the default destination for installation or alter it. Then click \"Next\"." }, { "code": null, "e": 7260, "s": 7204, "text": "Choose the setup type as \"Complete\". Then click \"Next\"." }, { "code": null, "e": 7449, "s": 7260, "text": "In this screen, you finally decide to really start the installation. You can still go back and change some options if needed. Assuming you are fine with everything so far, click \"Install\"." }, { "code": null, "e": 7539, "s": 7449, "text": "The installation completion screen appears after successful installation. Click \"Finish\"." }, { "code": null, "e": 7676, "s": 7539, "text": "You can verify the installation by going to the Windows Start menu and clicking on the QlikView icon. The screen appears as shown below." }, { "code": null, "e": 7713, "s": 7676, "text": "You are now ready to learn QlikView." }, { "code": null, "e": 8227, "s": 7713, "text": "As a leading Business Discovery Platform, QlikView is built with a very different approach to data discovery than other traditional platforms. QlikView does not first build a query and then fetch the result based on the query. Rather, it forms associations between different data objects as soon as it is loaded and prompts the user to explore the data in any way. There is no predefined data drill down paths. The data drill down paths can happen in any direction as long as the data is available and associated." }, { "code": null, "e": 8369, "s": 8227, "text": "Of course, a user can also play a role in creating the associations between data elements using data modeling approach available in QlikView." }, { "code": null, "e": 8668, "s": 8369, "text": "QlikView's architecture consists of a front end to visualize the processed data and a back end to provide the security and publication mechanism for QlikView user documents. The diagram given below depicts the internal working of QlikView. The architecture is discussed in detail below the picture." }, { "code": null, "e": 8916, "s": 8668, "text": "The Front end in QlikView is a browser-based access point for viewing the QlikView documents. It contains the QlikView Server, which is mainly used by the Business users to access the already created BI reports through an internet or intranet URL." }, { "code": null, "e": 9275, "s": 8916, "text": "Business users explore and interact with data using this front end and derive conclusions about the data. They also collaborate with other users on a given set of reports by sharing insights and exploring data together, in real time or off-line. These user documents are in the format .qvw, which can also be stored in the windows OS as a standalone document" }, { "code": null, "e": 9398, "s": 9275, "text": "The QlikView server in the front end manages the client server communication between the user and QlikView backend system." }, { "code": null, "e": 9472, "s": 9398, "text": "The QlikView backend consists of QlikView desktop and QlikView publisher." }, { "code": null, "e": 10097, "s": 9472, "text": "The QlikView desktop is a wizard-driven Windows environment, which has the features to load and transform data from its source. Its drag and drop feature is used to create the GUI layout of the reports that becomes visible in the frontend. The file types, which are created by QlikView desktop are stored with an extension of .qvw. These are the files that are passed on to the QlikView server in the front end, which serves the users with these files. Also .qvw files can be modified to store the data-inly files, which are known as .qvd files. They are binary files, which contain only the data and not the GUI components." }, { "code": null, "e": 10396, "s": 10097, "text": "The QlikView publisher is used as distribution service to distribute the .qvw documents\namong various QlikView servers and users. It handles the authorization and access privileges. It also does the direct loading of data from data sources by using the connection strings defined in the .qvw files." }, { "code": null, "e": 10617, "s": 10396, "text": "In this chapter, we will get acquainted with the screens available to a user for doing various operations. We will learn the basic navigation and know the different functions performed by the icons available in QlikView." }, { "code": null, "e": 11170, "s": 10617, "text": "This screen is a gentle introduction to navigate around QlikView. This screen comes up when you start QlikView and keep the Show start page when launching QlikView option checked. If you scroll down the examples section in the left, you can click any of the examples like − Movies Database, Data Visualization etc. to invoke it and\nsee how QlikView works. Feel free to click around! On moving to the right, you notice the Recent and Favourites link, which show all the recently visited QlikView documents and the documents you want to visit frequently." }, { "code": null, "e": 11405, "s": 11170, "text": "On closing the ‘Getting Started’ window, we get the main interface with all the available Menu commands. They represent the entire set of features available in QlikView. Given below is an overview of each section of the Menu Commands." }, { "code": null, "e": 11567, "s": 11405, "text": "This menu is used to create a new QlikView file and open the existing files from both local system and QlikView server. The important features in this menu are −" }, { "code": null, "e": 11641, "s": 11567, "text": "Mail as attachment to email the currently open document as an attachment." }, { "code": null, "e": 11715, "s": 11641, "text": "Mail as attachment to email the currently open document as an attachment." }, { "code": null, "e": 11799, "s": 11715, "text": "Reduce Data to view only the report layout and database structure without any data." }, { "code": null, "e": 11883, "s": 11799, "text": "Reduce Data to view only the report layout and database structure without any data." }, { "code": null, "e": 11997, "s": 11883, "text": "Table viewer option is used to see the structure of the tables, fields and their association in a graphical view." }, { "code": null, "e": 12111, "s": 11997, "text": "Table viewer option is used to see the structure of the tables, fields and their association in a graphical view." }, { "code": null, "e": 12252, "s": 12111, "text": "This menu is used to carry out the editing options like copy, paste, cut and using format painter. The important features in this menu are −" }, { "code": null, "e": 12331, "s": 12252, "text": "Active All option activates all the sheet objects present in the opened sheet." }, { "code": null, "e": 12410, "s": 12331, "text": "Active All option activates all the sheet objects present in the opened sheet." }, { "code": null, "e": 12458, "s": 12410, "text": "Removeto remove a sheet from the active window." }, { "code": null, "e": 12506, "s": 12458, "text": "Removeto remove a sheet from the active window." }, { "code": null, "e": 12602, "s": 12506, "text": "Advanced search option is used to do a search with advanced search expressions using multi box." }, { "code": null, "e": 12698, "s": 12602, "text": "Advanced search option is used to do a search with advanced search expressions using multi box." }, { "code": null, "e": 12879, "s": 12698, "text": "This menu is used to view the standard toolbars and zoom in/ zoom out features. It also displays all the active sheets as a cascade menu. The important features in this menu are − " }, { "code": null, "e": 12950, "s": 12879, "text": "Turn on/off WebView mode toggles the WebView mode and local view mode." }, { "code": null, "e": 13021, "s": 12950, "text": "Turn on/off WebView mode toggles the WebView mode and local view mode." }, { "code": null, "e": 13111, "s": 13021, "text": "Current Selections displays the field name and file values of the selected sheet objects." }, { "code": null, "e": 13201, "s": 13111, "text": "Current Selections displays the field name and file values of the selected sheet objects." }, { "code": null, "e": 13344, "s": 13201, "text": "Design Grid is used to toggle the sheet object placeholders for active object(s) and snap-to-grid for sizing and moving objects in the layout." }, { "code": null, "e": 13487, "s": 13344, "text": "Design Grid is used to toggle the sheet object placeholders for active object(s) and snap-to-grid for sizing and moving objects in the layout." }, { "code": null, "e": 13736, "s": 13487, "text": "This menu is used to select and clear the selection of values in the sheet objects. It also provides the feature of going back and forward into different logical statements of the sheet, you are working on. The important features in this menu are −" }, { "code": null, "e": 13785, "s": 13736, "text": " Lock locks all the values in current selection." }, { "code": null, "e": 13849, "s": 13785, "text": "Unlock unlocks all the locked values in the current selection." }, { "code": null, "e": 13986, "s": 13849, "text": "Layout Menu is used to add tabbed sheets, select different sheets and rearrange sheet objects. The important features in this menu are −" }, { "code": null, "e": 14049, "s": 13986, "text": "Promote sheet moves the current sheet or tab one step forward." }, { "code": null, "e": 14113, "s": 14049, "text": "Demote sheet moves the current sheet or tab one step backward." }, { "code": null, "e": 14174, "s": 14113, "text": "Delete sheet deletes the active sheet and everything in it. " }, { "code": null, "e": 14310, "s": 14174, "text": "Settings menu is used to set the user preferences, document properties, and sheet properties. The important features in this menu are −" }, { "code": null, "e": 14392, "s": 14310, "text": "Variable overview all the non-hidden variables and their values in a single list." }, { "code": null, "e": 14491, "s": 14392, "text": "Expression Overview shows expressions from the document, sheet and sheet objects as a single list." }, { "code": null, "e": 14574, "s": 14491, "text": "This menu is used to create bookmarks to different documents for faster retrieval." }, { "code": null, "e": 14723, "s": 14574, "text": "Reports menu is used to create new reports and edit the existing reports. You can edit the layout, add pages to the report, and also delete reports." }, { "code": null, "e": 14883, "s": 14723, "text": "Tools menu is a very prominent menu, frequently used for creating charts and opening the QlikView management console. The important features in this menu are −" }, { "code": null, "e": 15000, "s": 14883, "text": "Quick Chart Wizard creates simple charts without using the great number of different settings and options available." }, { "code": null, "e": 15117, "s": 15000, "text": "Quick Chart Wizard creates simple charts without using the great number of different settings and options available." }, { "code": null, "e": 15163, "s": 15117, "text": "Time Chart Wizard creates time series charts." }, { "code": null, "e": 15209, "s": 15163, "text": "Time Chart Wizard creates time series charts." }, { "code": null, "e": 15284, "s": 15209, "text": "Statistics Chart Wizard is used to apply common statistical tests on data." }, { "code": null, "e": 15359, "s": 15284, "text": "Statistics Chart Wizard is used to apply common statistical tests on data." }, { "code": null, "e": 15563, "s": 15359, "text": "This menu is used to create new sheet objects and modify the existing ones. The sheet properties option opens the page to set the parameters defining the sheet. The important features in this menu are − " }, { "code": null, "e": 15642, "s": 15563, "text": "Copy Sheet − creates a copy of the sheet along with the all the sheet objects." }, { "code": null, "e": 15721, "s": 15642, "text": "Copy Sheet − creates a copy of the sheet along with the all the sheet objects." }, { "code": null, "e": 15803, "s": 15721, "text": "Copy Image to Clipboard − Copies a bitmap picture of the sheet area to Clipboard." }, { "code": null, "e": 15885, "s": 15803, "text": "Copy Image to Clipboard − Copies a bitmap picture of the sheet area to Clipboard." }, { "code": null, "e": 15953, "s": 15885, "text": "Remove − completely removes the sheet along with the sheet objects." }, { "code": null, "e": 16021, "s": 15953, "text": "Remove − completely removes the sheet along with the sheet objects." }, { "code": null, "e": 16146, "s": 16021, "text": "The Window and Help menus are used to organize the different windows of QlikView application and provide help documentation." }, { "code": null, "e": 16389, "s": 16146, "text": "QlikView accepts Excel spreadsheet for data analysis by simple drag and drop action. You need to open the QlikView main window and drag and drop the excel file into the interface. It will automatically create the sheet showing the excel data." }, { "code": null, "e": 16474, "s": 16389, "text": "Keep the main window of QlikView open and browse for the excel file you want to use." }, { "code": null, "e": 16658, "s": 16474, "text": "On dropping the excel file into the main window, the File wizard appears. The File Type is already chosen as Excel. Under Labels, choose Embedded Labels. Click \"Next step\" to proceed." }, { "code": null, "e": 16782, "s": 16658, "text": "The Load script appears which shows the command that loads the data into the QlikView document. This command can be edited." }, { "code": null, "e": 17079, "s": 16782, "text": "Now, the Excel wizard prompts to save the file in the form of *.qvw file extension. It asks to select a location where you need to save the file. Click \"Next step\" to proceed. Now it is time to see the data that is loaded from the Excel file. We use a Table Box sheet object to display this data." }, { "code": null, "e": 17220, "s": 17079, "text": "The Table Box is a sheet object to display the available data as a table. It is invoked from the menu Layout → New Sheet Object → Table Box." }, { "code": null, "e": 17364, "s": 17220, "text": "On clicking Next, we get the option to choose the fields from the Table Box. You can use the Promote or Demote buttons to rearrange the fields." }, { "code": null, "e": 17484, "s": 17364, "text": "On completing the above step, the Table Box Sheet Object appears which shows the data that is read from the Excel file." }, { "code": null, "e": 17821, "s": 17484, "text": "QlikView can use the data in plane text file where the fields are separated by characters like comma, tab, semicolon etc. Here, we will take CSV as an example. A file in which each column of data is separated by a comma is known as a CSV file. It is a very widely used file format to store plane text-data organized as columns and rows." }, { "code": null, "e": 18120, "s": 17821, "text": "QlikView loads csv files using the Data from files options available in the script editor\nunder the File Menu. Alternatively, you can also open a new QlikView document and press control+E to get the script editor window as shown below. Choose the file Product_details.csv from the appropriate path." }, { "code": null, "e": 18287, "s": 18120, "text": "On opening the selected CSV file, a window as shown below comes up. Under Labels choose Embedded Labels, as our file has a header row as its first row. Click Finish. " }, { "code": null, "e": 18495, "s": 18287, "text": "The loading of the file into QlikView is done through the load script, which can be seen in the screen shot below. Hence, when we use any delimited file, we can tweak the below script as per the file format." }, { "code": null, "e": 18797, "s": 18495, "text": "Now the script wizard prompts to save the file in the form of *.qvw file extension. It asks to select a location where you need to save the file. Click \"Next step\" to proceed. Now, it is time to see the data that is loaded from the delimited file. We use a Table Box sheet object to display this data." }, { "code": null, "e": 18938, "s": 18797, "text": "The Table Box is a sheet object to display the available data as a table. It is invoked from the menu Layout → New Sheet Object → Table Box." }, { "code": null, "e": 19082, "s": 18938, "text": "On clicking Next, we get the option to choose the fields from the Table Box. You can use the Promote or Demote buttons to rearrange the fields." }, { "code": null, "e": 19202, "s": 19082, "text": "On completing the above step, the Table Box Sheet Object appears which shows the data that is read from the Excel file." }, { "code": null, "e": 19633, "s": 19202, "text": "XML is a file format, which shares both the file format and the data on the World Wide Web, intranets, and elsewhere using standard ASCII text. It stands for Extensible Markup Language (XML). Similar to HTML it contains markup tags. However, unlike HTML where the markup tag describes structure of the page, in XML the markup tags describe the meaning of the data contained into the file. QlikView can use the data from XML files." }, { "code": null, "e": 19930, "s": 19633, "text": "The process to load the data from XML files is similar to the loading of delimited files we have seen earlier. Open the script editor. Click on the menu Insert → Load Statement → Load from File. Browse for the XML file you wish to load. In this example, we are choosing the employee_dat.xml file." }, { "code": null, "e": 20146, "s": 19930, "text": "On opening the selected XML file, a window comes up as shown below. Under the File Type section in the left, choose XML. The content of the XML file now appears as a table along with the header column. Click Finish." }, { "code": null, "e": 20366, "s": 20146, "text": "The loading of the XML file into QlikView is done through the load script, which can be seen below. So when we use any XML file, we can tweak the below given script to rename the columns or change the file location etc." }, { "code": null, "e": 20665, "s": 20366, "text": "Now the script wizard prompts you to save the file in the form of *.qvw file extension. It asks to select a location where you need to save the file. Click \"Next step\" to proceed. Now it is time to see the data that is loaded from the XML file. We use a Table Box sheet object to display this data." }, { "code": null, "e": 20806, "s": 20665, "text": "The Table Box is a sheet object to display the available data as a table. It is invoked from the menu Layout → New Sheet Object → Table Box." }, { "code": null, "e": 20950, "s": 20806, "text": "On clicking Next, we get the option to choose the fields from the Table Box. You can use the Promote or Demote buttons to rearrange the fields." }, { "code": null, "e": 21070, "s": 20950, "text": "On completing the above step, the Table Box Sheet Object appears which shows the data that is read from the Excel file." }, { "code": null, "e": 21521, "s": 21070, "text": "QlikView can process files from the web, which are in the HTML format. It can extract data from HTML tables. The URL of the web file to be processed is given as an input and QlikView fetches both, the structure and content of the file. Then it analyzes the structure of the page extracting the relevant data from the HTML tables present in the page. We choose the Web files option from the Data from files section under the Data tab of script Editor." }, { "code": null, "e": 21764, "s": 21521, "text": "On selecting the Web files option, we get a new window to give the URL as input. In this example, we are choosing the List of sovereign states and dependent territories in Asia as the input page from Wikipedia. Mention the URL and click Next." }, { "code": null, "e": 21967, "s": 21764, "text": "On opening the selected Web file, the window shown below comes up. Here we can see the various tables present in the webpage labeled as @1, @1, @3 and so on. Choose the first table and click Next twice." }, { "code": null, "e": 22083, "s": 21967, "text": "From the above table, we can choose only the columns we need by removing the unwanted columns using the cross sign." }, { "code": null, "e": 22303, "s": 22083, "text": "The loading of the file into QlikView is done through the load script, which can be seen in the screen shot given below. Hence, when we use any delimited file, we can tweak the below given script as per the file format." }, { "code": null, "e": 22598, "s": 22303, "text": "Now the script wizard prompts to save the file in the form of *.qvw file extension. It asks to select a location where you need to save the file. Click \"Next step\" to proceed. Now it is time to see the data that is loaded from the web file. We use a Table Box sheet object to display this data." }, { "code": null, "e": 22741, "s": 22598, "text": "The Table Box is a sheet object to display the available data as a table. It is invoked from\nthe menu Layout → New Sheet Object → Table Box.\n\n" }, { "code": null, "e": 22885, "s": 22741, "text": "On clicking Next, we get the option to choose the fields from the Table Box. You can use the Promote or Demote buttons to rearrange the fields." }, { "code": null, "e": 23039, "s": 22885, "text": "On completing the above step, the Table Box Sheet Object appears, which shows the data that is read from the Web file. Mark the Non-English characters !!" }, { "code": null, "e": 23402, "s": 23039, "text": "QlikView can connect to most of the popular databases like MySQL, SQL Server, Oracle, Postgress etc. It can fetch data and table structures into QlikView environment and store the results in its memory for further analysis. The steps to connect to any of these databases involves creating an ODBC connection using a DSN and then using this DSN to\nfetch the data." }, { "code": null, "e": 23728, "s": 23402, "text": "For this tutorial, we will be connecting to MySQL database. This tutorial assumes you have a MySQL environment available. Create an ODBC DSN (Data Source Name) for MySQL, following these steps − to create DSN. Name the DSN as mysqluserdsn or you may prefer to use the existing one if you have already created a DSN for MySql." }, { "code": null, "e": 24136, "s": 23728, "text": "For this chapter we will use the MySql inbuilt database named sakila. We create a new QlikView document and open the script editor (pressing Control+E). Under the tab Data, we locate the section named Database. Choose ODBC from the drop down list and click Connect. The following window opens. Choose the DSN named mysqluserdns and click Test Connection. The message Connection Test succeeded should appear." }, { "code": null, "e": 24267, "s": 24136, "text": "On successful connection, the screen given below appears showing the connection to the DB in the main window of the script editor." }, { "code": null, "e": 24631, "s": 24267, "text": "Click Select iin the above window to get the list of tables and columns. Here as we have created the DSN with sakila as the default database we get the list of tables and columns from this database. We can choose another database from the database drop down list as shown in the screenshot given below. We will continue using the sakila database for this\nchapter." }, { "code": null, "e": 24757, "s": 24631, "text": "On Clicking OK in the above window, we get back to the main script editor showing the script for using the table named actor." }, { "code": null, "e": 25011, "s": 24757, "text": "Now the data loaded into QlikView document needs to be stored permanently to be analyzed further. For this, we will edit the script to store the data in the form of a qvd file. Press Control+E to open the edit script window and write the following code." }, { "code": null, "e": 25222, "s": 25011, "text": "In the code, we give appropriate names to the columns and mention the table name above the load statement. In addition, we give a path where the generated qvd file will be stored. Save this file as QV_mysql.qvw" }, { "code": null, "e": 25583, "s": 25222, "text": "The qvd file can be loaded into the main document and used to create graphs and tables for further analysis. Press Control+R to reload the QV_mysql.qvw file and click Next in the chart wizard. Choose the straight table to be created with actor_id, first_name, last_name as the dimensions and count of actor_id as the expression. A chart appears as given below." }, { "code": null, "e": 25809, "s": 25583, "text": "Data can be entered into a QlikView document by directly typing or pasting it. This feature is a quick method to get the data from the clipboard into the QlikView. The script editor provides this feature under the Insert tab." }, { "code": null, "e": 25921, "s": 25809, "text": "To open the Inline data load option, we open the script editor and go to Insert → Load Statement → Load Inline." }, { "code": null, "e": 26152, "s": 25921, "text": "On opening the above screen, we get a spreadsheet-like document where we can type the values. We can also paste the values already available in the clipboard. Please note the column headers are created automatically. Click Finish." }, { "code": null, "e": 26256, "s": 26152, "text": "The command, which loads the data, is created in the background which can be seen in the script editor." }, { "code": null, "e": 26357, "s": 26256, "text": "On creating a Table Box Sheet Object, we see the data that is read from the Inline data load option." }, { "code": null, "e": 26671, "s": 26357, "text": "QlikView can load data from tables already existing in its RAM, which is already processed by a script. This requirement arises when you want to create a table deriving data from an already existing table in the same script. Please note that both the new table and the existing table should be in the same script." }, { "code": null, "e": 27029, "s": 26671, "text": "Open the script editor (or use Control+E) and mention the following script. Here we create an inline table named Regions with sales data for different regions. Then we create another table named Total to calculate the total sales by Region Names. Finally we drop the table Regions, as in this .qvw file we only need the table named Total for data analysis. " }, { "code": null, "e": 27132, "s": 27029, "text": "On creating a Table Box Sheet Object, we see the data that is read from the resident data load option." }, { "code": null, "e": 27424, "s": 27132, "text": "QlikView Preceding load is a load type in which we use a load statement, which takes the columns of another load statement present in the same script. The data read by the first Load statement, which is at the bottom of the script editor window and then used by the load statements above it." }, { "code": null, "e": 27798, "s": 27424, "text": "The below given screen shot shows the script for data, which is loaded as Inline data and then the max function is applied to one of the columns. The load statement at the bottom makes the data available in QlikView's memory, which is used by the second load statement above the first load statement. The second load statement applies the max function with group by clause." }, { "code": null, "e": 27899, "s": 27798, "text": "On creating a Table Box Sheet Object, we see the data that is read from the Inline data load option." }, { "code": null, "e": 28320, "s": 27899, "text": "As the volume of data in the data source of a QlikView document increases, the time taken to load the file also increases which slows down the process of analysis. One approach to minimize this time taken to load data is to load only the records that are new in the source or the updated ones. This concept of loading only the new or changed records from the source into the QlikView document is called Incremental Load." }, { "code": null, "e": 28535, "s": 28320, "text": "To identify the new records from source, we use either a sequential unique key or a date time stamp for each row. These values of unique key or data time field has to flow from the source file to QlikView document." }, { "code": null, "e": 28800, "s": 28535, "text": "Let us consider the following source file containing product details in a retail store. Save this as a .csv file in the local system where it is accessible by QlikView. Over a period of time some more products are added and the description of some product changes." }, { "code": null, "e": 29502, "s": 28800, "text": "Product_Id,Product_Line,Product_category,Product_Subcategory\n1,Sporting Goods,Outdoor Recreation,Winter Sports & Activities\n2,\"Food, Beverages & Tobacco\",Food Items,Fruits & Vegetables\n3,Apparel & Accessories,Clothing,Uniforms\n4,Sporting Goods,Athletics,Rugby\n5,Health & Beauty,Personal Care\n6,Arts & Entertainment,Hobbies & Creative Arts,Musical Instruments\n7,Arts & Entertainment,Hobbies & Creative Arts,Orchestra Accessories\n8,Arts & Entertainment,Hobbies & Creative Arts,Crafting Materials\n9,Hardware,Tool Accessories,Power Tool Batteries\n10,Home & Garden,Bathroom Accessories,Bath Caddies\n11,\"Food, Beverages & Tobacco\",Food Items,Frozen Vegetables\n12,Home & Garden,Lawn & Garden,Power Equipment\n" }, { "code": null, "e": 29728, "s": 29502, "text": "We will load the above CSV file using the script editor (Control+E) by choosing the Table Files option as shown below. Here we also save the data into a QVD file in the local system. Save the QlikView document as a .qvw file." }, { "code": null, "e": 29892, "s": 29728, "text": "We can check the data loaded to QlikView document by creating a sheet object called Table Box. This is available in the Layout menu and New Sheet Objects sub-menu." }, { "code": null, "e": 30114, "s": 29892, "text": "On selecting the Table Box sheet object, we get to the next screen, which is used to select the columns and their positions in the table to be created. We choose the following columns and their positions and click Finish." }, { "code": null, "e": 30193, "s": 30114, "text": "The following chart showing the data as laid out in the previous step appears." }, { "code": null, "e": 30332, "s": 30193, "text": "Let us add the following three more records to the source data. Here, the Product IDs are the unique numbers, which represent new records." }, { "code": null, "e": 30455, "s": 30332, "text": "13,Office Supplies,Presentation Supplies,Display\n14,Hardware,Tool Accessories,Jigs\n15,Baby & Toddler,Diapering,Baby Wipes\n" }, { "code": null, "e": 30526, "s": 30455, "text": "Now, we write the script to pull only the new records form the source." }, { "code": null, "e": 31473, "s": 30526, "text": "// Load the data from the stored qvd.\nStored_Products:\nLOAD Product_Id, \n Product_Line, \n Product_category, \n Product_Subcategory\nFROM\n[E:\\Qlikview\\data\\products.qvd]\n(qvd);\n\n//Select the maximum value of Product ID.\nMax_Product_ID:\nLoad max(Product_Id) as MaxId\nresident Stored_Products;\n\n//Store the Maximum value of product Id in a variable.\nLet MaxId = peek('MaxId',-1);\n\n\t drop table Stored_Products;\n\n\n//Pull the rows that are new.\t \nNewProducts:\nLOAD Product_Id,Product_Line, Product_category,Product_Subcategory\n\t from [E:\\Qlikview\\data\\product_categories.csv]\n\t (txt, codepage is 1252, embedded labels, delimiter is ',', msq)\n\t where Product_Id > $(MaxId);\n\t \n//Concatenate the new values with existing qvd.\nConcatenate\nLOAD Product_Id,Product_Line, Product_category, \n Product_Subcategory\nFROM [E:\\Qlikview\\data\\products.qvd](qvd);\n\n//Store the values in qvd.\nstore NewProducts into [E:\\Qlikview\\data\\products.qvd](qvd);" }, { "code": null, "e": 31629, "s": 31473, "text": "The above script fetches only the new records, which are loaded and stored into the qvd file. As we see the records with the new Product IDs 13, 14 and 15." }, { "code": null, "e": 32192, "s": 31629, "text": "One of the important features of QlikView, which makes it so distinguished is the ability to store very large amount of data in a very compressed size and store it along with the QlikView documents. Therefore, once the document is created we need not connect to the data source, as the data is already stored along with the layout of the document. This is achieved through QVD file, which is a flat file stored with the .qvd extension. A QVD file stores data for one QlikView document and it is created using the script editor available in the QlikView document." }, { "code": null, "e": 32255, "s": 32192, "text": "The advantages of using QVD files in QlikView are as follows −" }, { "code": null, "e": 32278, "s": 32255, "text": "Faster Loading of Data" }, { "code": null, "e": 32333, "s": 32278, "text": "Gracefully support scaling up as the data volume grows" }, { "code": null, "e": 32358, "s": 32333, "text": "Used in incremental load" }, { "code": null, "e": 32416, "s": 32358, "text": "Data from multiple sources can be clubbed to one data set" }, { "code": null, "e": 32441, "s": 32416, "text": "Extract data in parallel" }, { "code": null, "e": 32680, "s": 32441, "text": "QVD files are created using the STORE statement during the loading of QlikView files. This statement creates a single qvd file, which gets stored in the specified location as a file; separate than the QVW file through which it is created." }, { "code": null, "e": 32808, "s": 32680, "text": "Given below is an example of storing the qvd file after the data is loaded into the QlikView document by reading a source file." }, { "code": null, "e": 33149, "s": 32808, "text": "A QVD file is loaded to a QlikView document in a similar way as other files like CSV, Excel and delimited files are used. We use the the Open option available under the File menu and browse for the QVD file we created before. On opening it gives us a window to see the data, select the column headers and do any data transformation required" }, { "code": null, "e": 33487, "s": 33149, "text": "On clicking Finish, the edit script window appears which shows the code used to load the QVD file. We can edit this code further. For example, to get only the few of the columns to be displayed or apply any inbuilt function etc. Click finish to load the file into the current QlikView document. Save the QlikView document as use_qvd.qvw." }, { "code": null, "e": 33886, "s": 33487, "text": "Reload the document by using Control+R and choose the menu option Layout → New Sheet Objects → Table Box. A window appears showing all the columns from the table present in the QVD file. Select \"Add All\" to add all the columns to the display table. Use the \"Promote/Demote\" option to change the order of the columns. Click \"Finish\". The following screen appears showing the content of the QVD file." }, { "code": null, "e": 34323, "s": 33886, "text": "Every QlikView document is made of at least one worksheet called Main. We can add more sheets, which are like many pages of the same QlikView document. Sheets help us display multiple data formats like - multiple charts or multiple tables. Each sheet can contain various sheet objects. In addition, sheets can be rearranged using Promote Sheet/Demote Sheet option and can be removed from the QlikView document using Remove Sheet option." }, { "code": null, "e": 34566, "s": 34323, "text": "Sheets have various properties, which can be set to customize the sheets. For example, we can set the name of the sheets and its colors. Right click anywhere in the sheet and choose the Properties option. Then choose the following properties." }, { "code": null, "e": 34642, "s": 34566, "text": "Sheet Settings → Color. − This will set the background colour of the Sheet." }, { "code": null, "e": 34718, "s": 34642, "text": "Sheet Settings → Color. − This will set the background colour of the Sheet." }, { "code": null, "e": 34816, "s": 34718, "text": "Tab Settings → Custom Colors. − This will set the color for the Tab where the Sheet name appears." }, { "code": null, "e": 34914, "s": 34816, "text": "Tab Settings → Custom Colors. − This will set the color for the Tab where the Sheet name appears." }, { "code": null, "e": 34960, "s": 34914, "text": "Title. − This will set the name of the Sheet." }, { "code": null, "e": 35006, "s": 34960, "text": "Title. − This will set the name of the Sheet." }, { "code": null, "e": 35286, "s": 35006, "text": "Sheet Objects are the QlikView data elements that are embedded in the sheet. They display the data that is loaded into the QlikView's memory. Each sheet object is tied to a data source and one or more of its columns. Sheet Objects are created from the layout menu as shown below." }, { "code": null, "e": 35475, "s": 35286, "text": "Sheet Objects display the data from a data source and all the objects in a sheet are associated with each other. Let's create a List Box and a Multi Box and see this association on action." }, { "code": null, "e": 35657, "s": 35475, "text": "The List box displays data from a column of a table available in QlikView memory. Choose the option List Box from the Add Sheet Objects option and set the properties as given below." }, { "code": null, "e": 35822, "s": 35657, "text": "A Multi Box represents data from multiple columns from a table. Choose the option Multi Box from the Add Sheet Objects option and set the properties as shown below." }, { "code": null, "e": 35918, "s": 35822, "text": "On completing the above given steps, the following window appears which shows both the objects." }, { "code": null, "e": 36190, "s": 35918, "text": "We can see how the sheet objects are linked to each other by choosing the one option from the Multi Box, which highlights the associated row in the List Box. Let us choose \"Diapering\" under the Product Category drop down list in Multi Box. The window shown below appears." }, { "code": null, "e": 36470, "s": 36190, "text": "Scripting is a very powerful feature in QlikView, which enables the control of the data load options and data transformations. It enables the use of many inbuilt functions available in QlikView and creates subroutines to be used across multiple scripts within a QlikViewdocument." }, { "code": null, "e": 36876, "s": 36470, "text": "Scripting is done using the Script Editor. It is accessed from the File menu using Script Editor. We can also press Control +E to open the script editor window. It prepopulates some data formats that are set as default formats for the data to be processed. For example, the Thousand separator is a comma and date is in Month-day-year format. These can be changed to suit the incoming data as per the need." }, { "code": null, "e": 37062, "s": 36876, "text": "Script editor has many features, which are accessed from the menu in the script editor window, which is a different menu from the main menu. Given below is a list of important features." }, { "code": null, "e": 37116, "s": 37062, "text": "Reload − Reloads the script and fetches the new data." }, { "code": null, "e": 37170, "s": 37116, "text": "Reload − Reloads the script and fetches the new data." }, { "code": null, "e": 37247, "s": 37170, "text": "Upper/Lower Case − Converts the case of words as QlikView is case sensitive." }, { "code": null, "e": 37324, "s": 37247, "text": "Upper/Lower Case − Converts the case of words as QlikView is case sensitive." }, { "code": null, "e": 37366, "s": 37324, "text": "Comment − Used to comment blocks of code." }, { "code": null, "e": 37408, "s": 37366, "text": "Comment − Used to comment blocks of code." }, { "code": null, "e": 37460, "s": 37408, "text": "Clear Entire Script − Clears the active script tab." }, { "code": null, "e": 37512, "s": 37460, "text": "Clear Entire Script − Clears the active script tab." }, { "code": null, "e": 37561, "s": 37512, "text": "Open Script File − Opens the saved script files." }, { "code": null, "e": 37610, "s": 37561, "text": "Open Script File − Opens the saved script files." }, { "code": null, "e": 37680, "s": 37610, "text": "Table Viewer − Used to see the tabular view of the data being loaded." }, { "code": null, "e": 37750, "s": 37680, "text": "Table Viewer − Used to see the tabular view of the data being loaded." }, { "code": null, "e": 37824, "s": 37750, "text": "Environment Variables − Inserts a standard list of Environment variables." }, { "code": null, "e": 37898, "s": 37824, "text": "Environment Variables − Inserts a standard list of Environment variables." }, { "code": null, "e": 37964, "s": 37898, "text": "Script Files − Allows to browse for script files and insert them." }, { "code": null, "e": 38030, "s": 37964, "text": "Script Files − Allows to browse for script files and insert them." }, { "code": null, "e": 38116, "s": 38030, "text": "Connect/Disconnect Statement − Used to connect or disconnect from external databases." }, { "code": null, "e": 38202, "s": 38116, "text": "Connect/Disconnect Statement − Used to connect or disconnect from external databases." }, { "code": null, "e": 38261, "s": 38202, "text": "Insert Tab − Inserts a Tab at the current cursor position." }, { "code": null, "e": 38320, "s": 38261, "text": "Insert Tab − Inserts a Tab at the current cursor position." }, { "code": null, "e": 38400, "s": 38320, "text": "Promote/Demote Tab − Allows to move the tabs from left to right and vice versa." }, { "code": null, "e": 38480, "s": 38400, "text": "Promote/Demote Tab − Allows to move the tabs from left to right and vice versa." }, { "code": null, "e": 38561, "s": 38480, "text": "Merge with Previous − Used to merge the content of active tag with previous tab." }, { "code": null, "e": 38642, "s": 38561, "text": "Merge with Previous − Used to merge the content of active tag with previous tab." }, { "code": null, "e": 38756, "s": 38642, "text": "ODBC Administrator 64 bit/ODBC Administrator 32 bit − Allows to set the correct DSN information for data sources." }, { "code": null, "e": 38870, "s": 38756, "text": "ODBC Administrator 64 bit/ODBC Administrator 32 bit − Allows to set the correct DSN information for data sources." }, { "code": null, "e": 38995, "s": 38870, "text": "Editor Preferences − Allows you to configure the text font and size, help features, shortcuts, default-scripting engine etc." }, { "code": null, "e": 39120, "s": 38995, "text": "Editor Preferences − Allows you to configure the text font and size, help features, shortcuts, default-scripting engine etc." }, { "code": null, "e": 39183, "s": 39120, "text": "Syntax Check − Used to validate the syntax of the script code." }, { "code": null, "e": 39246, "s": 39183, "text": "Syntax Check − Used to validate the syntax of the script code." }, { "code": null, "e": 39577, "s": 39246, "text": "QlikView has many built-in functions, which are available to be applied to data that is already available in memory. These functions are organized into many categories and the syntax of the function appears as soon as it is selected. We can click on the Paste button to get the expression into the editor and supply the arguments." }, { "code": null, "e": 39659, "s": 39577, "text": "Create a Table Box by following the menu as shown in the screen shot given below." }, { "code": null, "e": 39765, "s": 39659, "text": "On completing the above given step, we get a window to show the Calculation condition at the bottom left." }, { "code": null, "e": 39885, "s": 39765, "text": "Click on the button next to calculation condition and go to the Function tab. It shows the list of functions available." }, { "code": null, "e": 40000, "s": 39885, "text": "On choosing String from the functions category, we can see only few functions, which take a string as an argument." }, { "code": null, "e": 40071, "s": 40000, "text": "In the next chapters, we will see the use of many important functions." }, { "code": null, "e": 40523, "s": 40071, "text": "QlikView IntervalMatch is a powerful function used to match distinct numeric values to numeric intervals. It is useful in analyzing how the events actually happened versus the planned events. The example of a scenario where it is used is in the assembly lines of the production houses where the belts are planned to run at certain times and for certain duration. However, the actual run can happen at different points in time because of breakdown etc." }, { "code": null, "e": 40817, "s": 40523, "text": "Consider an assembly line where there are three belts named A, B and C. They are planned to start & stop at specific times of a day. In a given day, we study the actual start and end time and analyze what all happened in that day. For this, we consider two sets of observations as shown below." }, { "code": null, "e": 41114, "s": 40817, "text": "# Data Set for AssembilyLine.\nStartTime,EndTime, BeltNo\n00:05,4:20, A\n1:50,2:45,B\n3:15,10:30,C\n\t\n# Data set for the events happened.\nActualTime,Product\n1:10,Start Belt A\n2:24,Stop Belt A\n3:25,Restart Belt A\n4:35,Stop Belt A\n2:20,Start Belt B\n3:11, Stop Belt B\n3:15,Start Belt C\n11:20, Stop Belt C" }, { "code": null, "e": 41338, "s": 41114, "text": "We open the script editor in a new QlikView document using Control+E. The following code creates the required tables as inline data. After creating this script, press control+R to reload the data into the QlikView document." }, { "code": null, "e": 41614, "s": 41338, "text": "Let us create a Table Box sheet object to show the data generated by the IntervalMatch\nfunction. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed." }, { "code": null, "e": 41743, "s": 41614, "text": "On clicking OK in the above window, a table appears showing the field ActualTime matched to the intervals StartTime and EndTime." }, { "code": null, "e": 42055, "s": 41743, "text": "QlikView Aggregate functions are used to produce aggregate data from the rows of the table. The functions are applied to the columns when creating the load script. Given below is a sample list of Aggregate functions. We also need to apply the Group by clause appropriately when applying the aggregate functions." }, { "code": null, "e": 42110, "s": 42055, "text": "SUM gives the sum of the numeric values of the column." }, { "code": null, "e": 42169, "s": 42110, "text": "AVG gives the average of the numeric values of the column." }, { "code": null, "e": 42228, "s": 42169, "text": "MAX gives the maximum of the numeric values of the column." }, { "code": null, "e": 42287, "s": 42228, "text": "MIN gives the minimum of the numeric values of the column." }, { "code": null, "e": 42457, "s": 42287, "text": "Consider the following data stored as product_sales.csv in the local system. It represents the sales figures for different product lines and product category in a store." }, { "code": null, "e": 43113, "s": 42457, "text": "Product_Line,Product_category,Quantity,Value\nSporting Goods,Outdoor Recreation,12,5642\nFood, Beverages & Tobacco,38,2514\nApparel & Accessories,Clothing,54,2365\nApparel & Accessories,Costumes & Accessories,29,4487\nSporting Goods,Athletics,11,812\nHealth & Beauty,Personal Care,21,6912\nArts & Entertainment,Hobbies & Creative Arts,58,5201\nArts & Entertainment,Paintings,73,8451\nArts & Entertainment,Musical Instruments,41,1245\nHardware,Tool Accessories,2,456\nHome & Garden,Bathroom Accessories,36,241\nFood,Drinks,54,1247\nHome & Garden,Lawn & Garden,29,5462\nOffice Supplies,Presentation Supplies,22,577\nHardware,Blocks,53,548\nBaby & Toddler,Diapering,19,1247\n" }, { "code": null, "e": 43336, "s": 43113, "text": "We open the script editor in a new QlikView document using Control+E. The following\ncode creates the required tables as inline data. After creating this script press control+R to reload the data into the QlikView document." }, { "code": null, "e": 43697, "s": 43336, "text": "Let us create a Table Box sheet object to show the data generated by the Aggregate function. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and the select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table\nBox as shown below." }, { "code": null, "e": 43831, "s": 43697, "text": "Given below is the load script to find the sum of the sales quantity and sales value across the Product Lines and product categories." }, { "code": null, "e": 44059, "s": 43831, "text": "Click OK and press Control+R to reload the data into QlikView document. Now follow the same steps as given above in − Creating Sheet Objects to create a QlikView Table Box for displaying the result of the script as shown below." }, { "code": null, "e": 44176, "s": 44059, "text": "Given below is the load script to create the average of the sales quantity and sales value across each Product Line." }, { "code": null, "e": 44418, "s": 44176, "text": "# Average sales of Quantity and value in each Product Line.\nLOAD Product_Line, \n avg(Quantity),\n\t avg(Value)\nFROM\n[E:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq)\nGroup by Product_Line;" }, { "code": null, "e": 44646, "s": 44418, "text": "Click OK and press Control+R to reload the data into QlikView document. Now follow the same steps as given above in − Creating Sheet Objects to create a QlikView Table Box for displaying the result of the script as shown below." }, { "code": null, "e": 44759, "s": 44646, "text": "Given below is the load script to create the maximum and minimum of the sales quantity across each Product Line." }, { "code": null, "e": 45026, "s": 44759, "text": "# Maximum and Minimum sales in each product Line.\nLOAD Product_Line,\n max(Quantity) as MaxQuantity,\n min(Quantity) as MinQuantity\nFROM\n[E:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq)\nGroup by Product_Line;" }, { "code": null, "e": 45242, "s": 45026, "text": "Click OK and Control+R to reload the data into QlikView document. Now follow the same steps as above in − Creating Sheet Objects to create a QlikView Table Box for displaying the result of the script as shown below." }, { "code": null, "e": 45545, "s": 45242, "text": "The Match() function in QlikView is used to match the value of a string on expression with data value present in a column. It is similar to the in function that we see in SQL language. It is useful to fetch rows containing specific strings and it also has an extension in form of wildmatch() function." }, { "code": null, "e": 45630, "s": 45545, "text": "Let us consider the following data as input file for the examples illustrated below." }, { "code": null, "e": 46450, "s": 45630, "text": "Product_Id,Product_Line,Product_category,Product_Subcategory\n1,Sporting Goods,Outdoor Recreation,Winter Sports & Activities\n2,Food, Beverages & Tobacco,Food Items,Fruits & Vegetables\n3,Apparel & Accessories,Clothing,Uniforms\n4,Sporting Goods,Athletics,Rugby\n5,Health & Beauty,Personal Care\n6,Arts & Entertainment,Hobbies & Creative Arts,Musical Instruments\n7,Arts & Entertainment,Hobbies & Creative Arts,Orchestra Accessories\n8,Arts & Entertainment,Hobbies & Creative Arts,Crafting Materials\n9,Hardware,Tool Accessories,Power Tool Batteries\n10,Home & Garden,Bathroom Accessories,Bath Caddies\n11,Food, Beverages & Tobacco,Food Items,Frozen Vegetables\n12,Home & Garden,Lawn & Garden,Power Equipment\n13,Office Supplies,Presentation Supplies,Display\n14,Hardware,Tool Accessories,Jigs\n15,Baby & Toddler,Diapering,Baby Wipes\n" }, { "code": null, "e": 46641, "s": 46450, "text": "The following script shows the Load script, which reads the file named product_categories.csv. We search the field Product_Line for values matching with strings 'Food' and 'Sporting Goods'. " }, { "code": null, "e": 46999, "s": 46641, "text": "Let us create a Table Box sheet object to show the data generated by the match function. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below." }, { "code": null, "e": 47225, "s": 46999, "text": "The wildmatch() function is an extension of match() function in which we can use wildcards as part of the strings used to match the values with values in the fields being searched for. We search for the strings 'Off*','*ome*." }, { "code": null, "e": 47592, "s": 47225, "text": "Let us create a Table Box sheet object to show the data generated by the wildmatch\nfunction. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below." }, { "code": null, "e": 47939, "s": 47592, "text": "The Rank() function in QlikView is used to display the rank of the values in a field as well as return rows with specific rank value. So it is used in two scenarios. First scenario is in QlikView charts to display the ranks of the values in the field and second is in Aggregate function to display only the rows, which have a specific rank value." }, { "code": null, "e": 48104, "s": 47939, "text": "The data used in the examples describing Rank function is given below. You can save this as a .csv file in a path in your system where it is accessible by QlikView." }, { "code": null, "e": 48911, "s": 48104, "text": "Product_Id,Product_Line,Product_category,Quantity,Value\n1,Sporting Goods,Outdoor Recreation,12,5642\n2,Food, Beverages & Tobacco,38,2514\n3,Apparel & Accessories,Clothing,54,2365\n4,Apparel & Accessories,Costumes & Accessories,29,4487\n5,Sporting Goods,Athletics,11,812\n6,Health & Beauty,Personal Care,21,6912\n7,Arts & Entertainment,Hobbies & Creative Arts,58,5201\n8,Arts & Entertainment,Paintings,73,8451\n9,Arts & Entertainment,Musical Instruments,41,1245\n10,Hardware,Tool Accessories,2,456\n11,Home & Garden,Bathroom Accessories,36,241\n12,Food,Drinks,54,1247\n13,Home & Garden,Lawn & Garden,29,5462\n14,Office Supplies,Presentation Supplies,22,577\n15,Hardware,Blocks,53,548\n16,Baby & Toddler,Diapering,19,1247\n17,Baby & Toddler,Toys,9,257\n18,Home & Garden,Pipes,81,1241\n19,Office Supplies,Display Board,29,2177\n" }, { "code": null, "e": 49229, "s": 48911, "text": "The above data is loaded to the QlikView memory by using the script editor. Open the\nScript editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into QlikView's memory." }, { "code": null, "e": 49380, "s": 49229, "text": "Next, we follow the steps given below to create a chart, which shows the rank of the filed Value described with respect to the dimension Product_Line." }, { "code": null, "e": 49474, "s": 49380, "text": "Click on the Chart wizard and choose the option straight table as the chart type. Click Next." }, { "code": null, "e": 49561, "s": 49474, "text": "From the First Dimension drop down list, choose Product_Line as dimension. Click Next." }, { "code": null, "e": 49780, "s": 49561, "text": "In the custom expression field, mention the rank expression as shown below. Here we are considering the numeric field named Value, which represents the Sales value for each category under each Product Line. Click Next." }, { "code": null, "e": 49908, "s": 49780, "text": "On clicking Finish in the above step, the following chart appears which shows the rank of\nthe sales value of each Product Line." }, { "code": null, "e": 50173, "s": 49908, "text": "The aggregate functions like − max, min etc. can take rank as an argument to return rows satisfying certain rank values. We consider the following expression to be out in the script editor, which will give the rows containing highest sales under each Product line." }, { "code": null, "e": 50407, "s": 50173, "text": "# Load the records with highest sales value for each product line.\nLOAD Product_Line, \n max(Value,1)\nFROM\n[E:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq)\ngroup by Product_Line;" }, { "code": null, "e": 50764, "s": 50407, "text": "Let us create a Table Box sheet object to show the data generated by the above given\nscript. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below." }, { "code": null, "e": 50885, "s": 50764, "text": "The peek() function in QlikView is used to fetch the value of a field from a previous record\nand use it in calculations." }, { "code": null, "e": 50990, "s": 50885, "text": "Let us consider the monthly sales figure as shown below. Save the data with file name\nmonthly_sales.csv." }, { "code": null, "e": 51156, "s": 50990, "text": "Month,Sales Volume\nMarch,2145\nApril,2458\nMay,1245\nJune,5124\nJuly,7421\nAugust,2584\nSeptember,5314\nOctober,7846\nNovember,6532\nDecember,4625\nJanuary,8547\nFebruary,3265\n" }, { "code": null, "e": 51484, "s": 51156, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from for the file containing the above data. Edit the load\nscript to add the following code. Click OK and click Control+R to load the data into QlikView's memory." }, { "code": null, "e": 51664, "s": 51484, "text": "LOAD Month, \n [Sales Volume],\n peek('Sales Volume') as Prevmonth\nFROM\n[C:\\Qlikview\\data\\monthly_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 52138, "s": 51664, "text": "Let us create a Table Box sheet object to show the data generated by the above script. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the csv file in the QlikView Table Box as shown below. Also set the sort order as shown below to get the result in the same order of the field Month as it is in the source." }, { "code": null, "e": 52243, "s": 52138, "text": "On completing the above steps and clicking Finish, we get the Table box showing the data as given below." }, { "code": null, "e": 52420, "s": 52243, "text": "The peek() can be used in calculations involving other columns. Let us display the percentage change for sales volume for each month. The following script achieves this result." }, { "code": null, "e": 52672, "s": 52420, "text": "LOAD\nMonth, [Sales Volume],\npeek('Sales Volume') as Prevvolume,\n(([Sales Volume]-peek('Sales Volume')))/peek('Sales Volume')*100 as Difference\nFROM\n[C:\\Qlikview\\data\\monthly_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq); " }, { "code": null, "e": 53028, "s": 52672, "text": "Let us create a Table Box sheet object to show the data generated by the above script.\nGo to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below." }, { "code": null, "e": 53270, "s": 53028, "text": "The RangeSum() function in QlikView is used to do a selective sum on chosen fields which\nis not easily achieved by the sum function. It can take expressions containing other functions as its arguments and return the sum of those expressions." }, { "code": null, "e": 53375, "s": 53270, "text": "Let us consider the monthly sales figure as shown below. Save the data with file name monthly_sales.csv." }, { "code": null, "e": 53541, "s": 53375, "text": "Month,Sales Volume\nMarch,2145\nApril,2458\nMay,1245\nJune,5124\nJuly,7421\nAugust,2584\nSeptember,5314\nOctober,7846\nNovember,6532\nDecember,4625\nJanuary,8547\nFebruary,3265\n" }, { "code": null, "e": 53903, "s": 53541, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into QlikView's memory." }, { "code": null, "e": 54038, "s": 53903, "text": "LOAD \nMonth, [Sales Volume]\nFROM\n[C:\\Qlikview\\data\\monthly_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 54414, "s": 54038, "text": "With the above data loaded into QlikView's memory, we edit the script to add a new column, which will give a rolling sum of the month wise sales volume. For this, we also take the help of the peek function discussed in the earlier chapter to hold the value of the previous record and add it to the sales volume of the current record. The following script achieves the result." }, { "code": null, "e": 54601, "s": 54414, "text": "LOAD\nMonth, [Sales Volume],\nrangesum([Sales Volume],peek('Rolling')) as Rolling\nFROM\n[C:\\Qlikview\\data\\monthly_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 54748, "s": 54601, "text": "Let us create a Table Box sheet object to show the data generated by the above given script. Go to the menu Layout → New Sheet Object → Table Box." }, { "code": null, "e": 54958, "s": 54748, "text": "The following window appears in which we mention the Title of the table and select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below." }, { "code": null, "e": 55211, "s": 54958, "text": "QlikView documents are the files that contain all the objects used for the data presentation and analysis. It contains the sheets, variables, data model, source-data connection details, and even the data that is loaded after pulling it from the source." }, { "code": null, "e": 55352, "s": 55211, "text": "We can quickly find out the basic information of a QlikView document. Click on Help → document Support Info. Given below is a sample output." }, { "code": null, "e": 55565, "s": 55352, "text": "We can set an image as the background image for a document using the check box Wallpaper Image check box under the General tab. We choose an image and align it at the left top position using the dropdown buttons." }, { "code": null, "e": 55626, "s": 55565, "text": "The following screen appears on selecting the above options." }, { "code": null, "e": 55996, "s": 55626, "text": "The QlikView document contains various Sheet objects, which can be moved around by dragging them and placed anywhere in the document. Let us create two sheet objects, a Table box and a Statistics Box. You can follow the earlier chapters where we have already learnt to create sheet objects. In addition, we are using the file Product_sales.csv, which is mentioned here." }, { "code": null, "e": 56287, "s": 55996, "text": "Details of the Sheets objects can be seen using the \"Sheets\" tab. It shows all the sheets contained in the document and for each sheet, the sheet objects are shown. Both the sheets and sheet objects have unique IDs. We can also edit various properties of these objects from this tab itself." }, { "code": null, "e": 56446, "s": 56287, "text": "A QlikView document can be scheduled to refresh at some desired intervals. This is done using the Schedule tab available under the Document properties window." }, { "code": null, "e": 56861, "s": 56446, "text": "A list box represents the list of all the values of a specific field. Selecting a value in list box highlights the related values in other sheet objects. This helps in faster visual analysis.\nIt is also very useful to follow a drill down path among various sheet objects. It also has a search feature, which allows to search for specific values in the list box which is very helpful for a very long list of values." }, { "code": null, "e": 56988, "s": 56861, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 57672, "s": 56988, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 58034, "s": 57672, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into QlikView's memory." }, { "code": null, "e": 58196, "s": 58034, "text": "LOAD Product_Line, \n Product_category, \n Value\nFROM\n[C:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 58328, "s": 58196, "text": "Creation of List Box involves navigating through menu Layout → New Sheet Object → List Box. The following screen shows these steps." }, { "code": null, "e": 58406, "s": 58328, "text": "Next, we choose Product category as the field on which we build the list box." }, { "code": null, "e": 58519, "s": 58406, "text": "Finishing the above steps brings the following screen, which shows the values of Product category as a list box." }, { "code": null, "e": 58772, "s": 58519, "text": "When the List Box contains very large number of values, it is difficult to scroll down and look for it. So the search box at the top of the list box can be used to type the search string. The relevant values appear as soon as the first letter is typed." }, { "code": null, "e": 58917, "s": 58772, "text": "Other Sheet Objects automatically get associated with the List Box and the association is easily observed by selecting values form the list box." }, { "code": null, "e": 59240, "s": 58917, "text": "A Multi Box represents the list of all the values from multiple fields as drop down values. Similar to list box, the selection of a value in Multi Box highlights the related values in other sheet objects. This helps in faster visual analysis. It is also very useful to follow a drill down path among various sheet objects." }, { "code": null, "e": 59367, "s": 59240, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 60051, "s": 59367, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 60417, "s": 60051, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Edit the load script to add the following code. Click OK and click Control+R to load the data into the QlikView's memory." }, { "code": null, "e": 60579, "s": 60417, "text": "LOAD Product_Line, \n Product_category, \n Value\nFROM\n[C:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 60713, "s": 60579, "text": "Creation of Multi Box involves navigating through menu Layout → New Sheet Object → Multi Box. The following screen shows these steps." }, { "code": null, "e": 60792, "s": 60713, "text": "Next we choose the fields of the Products sales tables to build the Multi Box." }, { "code": null, "e": 60906, "s": 60792, "text": "Finishing the above steps brings the following screen, which shows the values of Product category as a Multi box." }, { "code": null, "e": 61053, "s": 60906, "text": "Other Sheet Objects automatically get associated with the Multi Box and the association is easily observed by selecting values from the Multi Box." }, { "code": null, "e": 61372, "s": 61053, "text": "QlikView text Object is used to show some descriptive information about the QlikView report being displayed. It can also show calculations based on certain expressions. It is mainly used for displaying nicely formatted information using colors and different font types in a box separately from the other Sheet Objects." }, { "code": null, "e": 61499, "s": 61372, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 62183, "s": 61499, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 62557, "s": 62183, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data. Edit the load script to add the following code. Click \"OK\" and press \"Control+R\" to load the data into the QlikView's memory." }, { "code": null, "e": 62719, "s": 62557, "text": "LOAD Product_Line, \n Product_category, \n Value\nFROM\n[C:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 62902, "s": 62719, "text": "For the above data, let us create a Table Box , which will show the data in a tabular form.\nGo to the menu Layout → New Sheet Object → Table Box and choose the column as shown below." }, { "code": null, "e": 62990, "s": 62902, "text": "Click Apply and then OK to finish creating the Table box. The following screen appears." }, { "code": null, "e": 63111, "s": 62990, "text": "For the above data, let us create a Text Object. Go to the menu Layout → New Sheet Object → Text Object as shown below." }, { "code": null, "e": 63289, "s": 63111, "text": "On the text box created above, right click and choose properties. Then enter the content to be displayed on the Text Object in the Text box under the General tab as shown below." }, { "code": null, "e": 63388, "s": 63289, "text": "The background color of the Text Object can be set using the background option in the General tab." }, { "code": null, "e": 63556, "s": 63388, "text": "The final Text Object is shown below. If we click on some Product Line to filter it, then the content in the Text Object changes accordingly to reflect the new values." }, { "code": null, "e": 63832, "s": 63556, "text": "Bar charts are very widely used charting method to study the relation between two dimensions in form of bars. The height of the bar in the graph represents the value of one dimension. The number of bars represent the sequence of values or grouped values of another dimension." }, { "code": null, "e": 63959, "s": 63832, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 64643, "s": 63959, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 65021, "s": 64643, "text": "The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option form the \"Data from Files\" tab and browse for the file containing the above data. Edit the load script to add the following code. Click \"OK\" and press \"Control+R\" to load the data into\nthe QlikView's memory." }, { "code": null, "e": 65183, "s": 65021, "text": "LOAD Product_Line, \n Product_category, \n Value\nFROM\n[C:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 65365, "s": 65183, "text": "For the above data, let us create a Table Box, which will show the data in a tabular form. Go to the menu Layout → New Sheet Object → Table Box and choose the column as shown below." }, { "code": null, "e": 65455, "s": 65365, "text": "Click Apply and then OK to finish creating the Table box. The below given screen appears." }, { "code": null, "e": 65644, "s": 65455, "text": "To start creating a bar chart, we will use the quick chart wizard. On clicking it, the following\nscreen appears which prompts for selecting the chart type. Choose bar Chart and click\nNext." }, { "code": null, "e": 65688, "s": 65644, "text": "Choose Product Line as the First Dimension." }, { "code": null, "e": 65872, "s": 65688, "text": "The chart expression is used to apply the functions like Sum, Average, or Count on the fields with numeric values. We will apply the Sum function on the filed named Value. Click Next." }, { "code": null, "e": 65994, "s": 65872, "text": "The Chart format defines the style and orientation of the chart. We choose the first option\nin each category. Click Next." }, { "code": null, "e": 66100, "s": 65994, "text": "The Bar chart appears as shown below. It shows the height of the field value for different product lines." }, { "code": null, "e": 66361, "s": 66100, "text": "A pie-chart is a representation of values as slices of a circle with different colors. The slices are labeled and the numbers corresponding to each slice is also represented in the chart. QlikView creates pie-chart using the chart wizard or chart Sheet Object." }, { "code": null, "e": 66488, "s": 66361, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 67172, "s": 66488, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 67546, "s": 67172, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data. Edit the load script to add the following code. Click \"OK\" and press \"Control+R\" to load the data into the QlikView's memory." }, { "code": null, "e": 67708, "s": 67546, "text": "LOAD Product_Line, \n Product_category, \n Value\nFROM\n[C:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 67897, "s": 67708, "text": "To start creating a Pie chart, we will use the quick chart wizard. On clicking it, the following screen appears which prompts for selecting the chart type. Choose Pie Chart and click Next." }, { "code": null, "e": 67941, "s": 67897, "text": "Choose Product Line as the First Dimension." }, { "code": null, "e": 68124, "s": 67941, "text": "The chart expression is used to apply the functions like Sum, Average or Count on the fields with numeric values. We will apply the Sum function on the filed named Value. Click Next." }, { "code": null, "e": 68229, "s": 68124, "text": "The Chart format defines the style and orientation of the chart. We choose the third option. Click Next." }, { "code": null, "e": 68335, "s": 68229, "text": "The Bar chart appears as shown below. It shows the height of the field value for different\nproduct lines." }, { "code": null, "e": 68527, "s": 68335, "text": "A Dashboard is a powerful feature to display values from many fields simultaneously. QlikeView's feature of data association in memory can display the dynamic values in all the sheet objects." }, { "code": null, "e": 68654, "s": 68527, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 69338, "s": 68654, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 69712, "s": 69338, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data. Edit the load script to add the following code. Click \"OK\" and press \"Control+R\" to load the data into the QlikView's memory." }, { "code": null, "e": 69874, "s": 69712, "text": "LOAD Product_Line, \n Product_category, \n Value\nFROM\n[C:\\Qlikview\\data\\product_sales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 70033, "s": 69874, "text": "We choose the fields from the above input data as matrices to be displayed in the dashboard. For this, we follow the steps in the menu Layout → Select Fields." }, { "code": null, "e": 70127, "s": 70033, "text": "In the next screen, choose the available fields to be displayed in the dashboard. Click \"OK\"." }, { "code": null, "e": 70182, "s": 70127, "text": "The following screen appears displaying all the fields" }, { "code": null, "e": 70298, "s": 70182, "text": "NNow we add a chart to the dashboard by right-clicking anywhere in the sheet and choosing New Sheet Object → Chart." }, { "code": null, "e": 70397, "s": 70298, "text": "Let us choose the chart type as a bar chart to display the sales values for various product Lines." }, { "code": null, "e": 70452, "s": 70397, "text": "Let us select the Product Line as the Chart Dimension." }, { "code": null, "e": 70562, "s": 70452, "text": "The expression to display the sales value for the Product Line dimension is written in the expression editor." }, { "code": null, "e": 70634, "s": 70562, "text": "Given below is the dashboard displayed after finishing the above steps." }, { "code": null, "e": 70803, "s": 70634, "text": "The values in the above Dashboard can be selected for filtering specific products and the chart changes accordingly. In addition, the associated values are highlighted." }, { "code": null, "e": 71093, "s": 70803, "text": "Data Transformation is the process of modifying the existing data to a new data format. It can also involve filtering out or adding some specific values to the existing data set. QlikView can carry out data transformation after reading it to its memory and using many in-built functions. " }, { "code": null, "e": 71244, "s": 71093, "text": "Let us consider the following input data, which represents the sales figures of each month. This is stored as a csv file with name quarterly_sales.csv" }, { "code": null, "e": 71447, "s": 71244, "text": "Month,SalesVolume\nMarch,2145\nApril,2458\nMay,1245\nSales Values in Q2\nJune,5124\nJuly,7421\nAugust,2584\nSales Values in Q3\nSeptember,5314\nOctober,7846\nNovember,6532\nDecember,4625\nJanuary,8547\nFebruary,3265\n" }, { "code": null, "e": 71701, "s": 71447, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option form the \"Data from Files\" tab and browse for the file quarterlt_sales.csv. Click next." }, { "code": null, "e": 71812, "s": 71701, "text": "The next screen prompts us to choose some data transformation. Click on the button Enable Transformation Step." }, { "code": null, "e": 72006, "s": 71812, "text": "In this step, we will select the transformation to eliminate the rows, which describe the quarter. We select Garbage → delete marked and select the two rows, which are not required. Click Next." }, { "code": null, "e": 72232, "s": 72006, "text": "After selecting the type of Transformation and the rows to be removed, the next screen prompts us for any further transformation like selecting a where clause or adding any Prefixes. We will ignore this step and click Finish." }, { "code": null, "e": 72331, "s": 72232, "text": "The Load script for the above data after all the transformation steps are complete is given\nbelow." }, { "code": null, "e": 72444, "s": 72331, "text": "The transformed data can be displayed by using a Table Box sheet object. The steps to create it are given below." }, { "code": null, "e": 72490, "s": 72444, "text": "Next, we choose the fields for the Table Box." }, { "code": null, "e": 72540, "s": 72490, "text": "The Table Box now displays the data in the sheet." }, { "code": null, "e": 72633, "s": 72540, "text": "The Fill function in QlikView is used to fill values from existing fields into a new field. " }, { "code": null, "e": 72733, "s": 72633, "text": "Let us consider the following input data, which represents the actual and forecasted sales figures." }, { "code": null, "e": 72946, "s": 72733, "text": "Month,Forecast,Actual\nMarch,2145,2247\nApril,2458,\nMay,1245,\nJune,5124,3652\nJuly,7421,7514\nAugust,2584,\nSeptember,5314,4251\nOctober,7846,6354\nNovember,6532,7451\nDecember,4625,1424\nJanuary,8547,7852\nFebruary,3265,\n" }, { "code": null, "e": 73198, "s": 72946, "text": "The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data." }, { "code": null, "e": 73332, "s": 73198, "text": "After clicking Next in the above step, we choose the Enable Transformation Step button to carry out the required data transformation." }, { "code": null, "e": 73457, "s": 73332, "text": "As we are going to use the Fill function, let us choose the Fill tab, which displays th empty values under the Actual Field." }, { "code": null, "e": 73772, "s": 73457, "text": "On clicking the Fill button, the option to choose target column and the cell condition appears. We choose column three, as we want to fill the empty values of this column with values from same row in column two. Also, choose the Cell Value as empty so that only the empty cells will be overwritten with new values." }, { "code": null, "e": 73847, "s": 73772, "text": "On completing the above steps, we get the transformed data as shown below." }, { "code": null, "e": 73996, "s": 73847, "text": "The load script for the transformed data can be seen using the script editor. The script shows the expression, which replaces the empty cell values." }, { "code": null, "e": 74109, "s": 73996, "text": "The transformed data can be seen by creating a Table Box using the option in the menu Layout → New Sheet Object." }, { "code": null, "e": 74357, "s": 74109, "text": "Column Manipulation is a type of Data Transformation in which a new column is populated with values from an existing column, which meets certain criteria. The criteria can be an expression, which is created as part of the Data Transformation step." }, { "code": null, "e": 74457, "s": 74357, "text": "Let us consider the following input data, which represents the actual and forecasted sales figures." }, { "code": null, "e": 74686, "s": 74457, "text": "Month,Forecast,Actual\nMarch,2145,2247\nApril,2458,2125\nMay,1245,2320\nJune,5124,3652\nJuly,7421,7514\nAugust,2584,3110\nSeptember,5314,4251\nOctober,7846,6354\nNovember,6532,7451\nDecember,4625,1424\nJanuary,8547,7852\nFebruary,3265,2916\n" }, { "code": null, "e": 75050, "s": 74686, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data. After clicking Next, we choose the Enable Transformation Step button to carry out the required data transformation." }, { "code": null, "e": 75266, "s": 75050, "text": "Choose the Column tab and then choose the New button. It asks to specify the New column and the Row Condition. We specify column 3 as the source column and pick the values, which start with two as the Row Condition." }, { "code": null, "e": 75341, "s": 75266, "text": "On completing the above steps, we get the transformed data as shown below." }, { "code": null, "e": 75503, "s": 75341, "text": "The load script for the Transformed data can be seen using the script editor. The script shows the expression, which creates the new column with required values." }, { "code": null, "e": 75616, "s": 75503, "text": "The transformed data can be seen by creating a Table Box using the option in the menu Layout → New Sheet Object." }, { "code": null, "e": 75926, "s": 75616, "text": "The Rotating table in QlikView is similar to the column and row transpose feature in\nMicrosoft Excel but with some additional options. We can transpose columns in multiple directions and they give different results. In this chapter, we will be seeing the normal transpose option of converting rows to columns." }, { "code": null, "e": 76026, "s": 75926, "text": "Let us consider the following input data, which represents the actual and forecasted sales figures." }, { "code": null, "e": 76239, "s": 76026, "text": "Month,Forecast,Actual\nMarch,2145,2247\nApril,2458,\nMay,1245,\nJune,5124,3652\nJuly,7421,7514\nAugust,2584,\nSeptember,5314,4251\nOctober,7846,6354\nNovember,6532,7451\nDecember,4625,1424\nJanuary,8547,7852\nFebruary,3265,\n" }, { "code": null, "e": 76487, "s": 76239, "text": "The above data is loaded to QlikView memory by using the script editor. Open the script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data." }, { "code": null, "e": 76603, "s": 76487, "text": "After clicking Next, we choose the Enable Transformation Step button to carry out the required data transformation." }, { "code": null, "e": 76721, "s": 76603, "text": "As we are going to use the Rotate function, let us choose the Rotate tab which displays the values of all the fields." }, { "code": null, "e": 76824, "s": 76721, "text": "We click the Transpose button to transpose the above data. The transposed data appears as shown below." }, { "code": null, "e": 76974, "s": 76824, "text": "The load script for the Transformed data can be seen using the script editor. The script shows the expression, which replaces the empty cell values. " }, { "code": null, "e": 77087, "s": 76974, "text": "The transformed data can be seen by creating a Table Box using the option in the menu Layout → New Sheet Object." }, { "code": null, "e": 77571, "s": 77087, "text": "Dimensions and Measures are fundamental entities, which are always used in data analysis. For example, consider the result of the analysis, “what is the percentage change in volume of sales for each quarter?” In this case, each quarter represents the Dimensions, which is the name of the quarter. The percentage change in volume represents the Measures, which is a calculation with respect to each value in the dimension. Below are some widely accepted definition of these two terms." }, { "code": null, "e": 77703, "s": 77571, "text": "Dimension − It is a descriptive field in the data set which represents few distinct values. Examples − Month, Year, Product ID etc." }, { "code": null, "e": 77815, "s": 77703, "text": "Measures − It is a numeric field on which some calculations are performed for each distinct value of dimension." }, { "code": null, "e": 78007, "s": 77815, "text": "Let us consider the following input data, which represents the sales volume and Revenue of different product lines and product categories in different regions. Save the data into a .csv file." }, { "code": null, "e": 78325, "s": 78007, "text": "ProductID,ProductCategory,Region,SalesVolume, Revenue\n1,Outdoor Recreation,Europe,457,25841\n2,Clothing,Europe,125,54281\n3,Costumes & Accessories,South Asia,781,54872\n4,Athletics,South Asia,839,87361\n5,Personal Care,Australia,473,15425\n6,Arts & Entertainment,North AMerica,625,84151\n7,Hardware,South America,772,45812\n" }, { "code": null, "e": 78646, "s": 78325, "text": "The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into the QlikView's memory" }, { "code": null, "e": 78872, "s": 78646, "text": "We can see the structure of the table by following the menu File → Table Viewer or pressing Control+T. The following screen comes up in which we have marked the dimensions inside a green box and the measures inside a red box." }, { "code": null, "e": 79018, "s": 78872, "text": "Let us create a straight table chart showing the calculation using above dimensions and measures. Click on the Quick Chart Wizard as shown below." }, { "code": null, "e": 79072, "s": 79018, "text": "Next, click on the Straight Table option. Click Next." }, { "code": null, "e": 79178, "s": 79072, "text": "In this screen, we choose Region as the dimension as we want to select the total revenue for each region." }, { "code": null, "e": 79296, "s": 79178, "text": "The Next screen prompts for applying the calculation on a measure field. We choose to apply Sum on the field Revenue." }, { "code": null, "e": 79417, "s": 79296, "text": "On completing the above steps, we get the final chart which shows the total revenue(Measure) for each region(Dimension)." }, { "code": null, "e": 80150, "s": 79417, "text": "A start schema model is a type of data model in which multiple dimensions are linked to a single fact table. Of course, in bigger models there can be multiple facts tables linked to multiple dimensions and other fact tables. The usefulness of this model lies in performing fast queries with minimal joins among various tables. The fact table contains data, which are measures and have numeric values. Calculations are applied on the fields in the fact table. The unique keys of the dimension tables are used in linking it to the fat table, which also has a key usually with the same field name. Therefore, the Fact table contains the keys from the entire dimension table and forms a concatenated primary key used in various queries." }, { "code": null, "e": 80366, "s": 80150, "text": "Given below is a list of tables, which contain the data for different products from various suppliers and regions. Also the supply happens at different time intervals, which are captured in the Time dimension table." }, { "code": null, "e": 80458, "s": 80366, "text": "It contains the Product Category and Product Names. The Product ID field is the unique Key." }, { "code": null, "e": 80713, "s": 80458, "text": "ProductID,ProductCategory,ProductName\n1,Outdoor Recreation,Winter Sports & Activities\n2,Clothing,Uniforms\n3,Lawn & Garden\tPower, Equipment\n4,Athletics,Rugby\n5,Personal Care,Shaver\n6,Arts & Entertainment,Crafting Materials\n7,Hardware,Power Tool Batteries\n" }, { "code": null, "e": 80811, "s": 80713, "text": "It contains the Region Names where the suppliers are based. The RegionID field is the unique Key." }, { "code": null, "e": 80928, "s": 80811, "text": "RegionID,Continent,Country\n3,North America, USA\n7,South America, Brazil\n12,Asia,China\n2,Asia,Japan\n5,Europe,Belgium\n" }, { "code": null, "e": 81033, "s": 80928, "text": "It contains the Supplier Names, which supply the above products. The SupplierID field is the unique Key." }, { "code": null, "e": 81151, "s": 81033, "text": "SupplierID,SupplierName\n3S12,Supre Suppliers\n4A15,ABC Suppliers\n4S66,Max Sports\n5F244,Nice Foods\n8A45,Artistic angle\n" }, { "code": null, "e": 81261, "s": 81151, "text": "It contains the Time periods when the supply of the above products occur. The TimeID field is the unique Key." }, { "code": null, "e": 81346, "s": 81261, "text": "TimeID,Year,Month\n1,2012,Feb\n2,2012,May\n3,2012,Sep\n4,2013,Aug\n5,2014,Jan\n6,2014,Nov\n" }, { "code": null, "e": 81502, "s": 81346, "text": "It contains the values for the quantities supplied and percentage of defects in them. It joins to each of the above dimensions through keys with same name." }, { "code": null, "e": 81713, "s": 81502, "text": "ProductID,RegionID,TimeID,SupplierID,Quantity, DefectPercentage\n1,3,3,5F244,8452,12\n2,3,1,4S66,5124,8.25\n3,7,1,8A45,5841,7.66\n4,12,2,4A15,5123,1.25\n5,5,3,4S66,7452,8.11\n6,2,5,4A15,5142,3.66\n7,2,1,4S66,452,2.06\n" }, { "code": null, "e": 82099, "s": 81713, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into QlikView's memory. Below is the script which appears after each of the above file is read." }, { "code": null, "e": 82971, "s": 82099, "text": "LOAD ProductID, \n ProductCategory, \n ProductName\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Product_dimension.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLOAD TimeID, \n Year, \n Month\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Time.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLOAD SupplierID, \n SupplierName\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Suppliers.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLOAD RegionID, \n Continent, \n Country\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Regions.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLOAD ProductID, \n RegionID, \n TimeID, \n SupplierID, \n Quantity, \n DefectPercentage\nFROM\n[C:\\Qlikview\\images\\StarSchema\\Supplier_quantity.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 83132, "s": 82971, "text": "After reading the above data into QlikView memory, we can look at the data model, which shows all the tables, fields, and relationship in form of a star schema." }, { "code": null, "e": 83511, "s": 83132, "text": "A Synthetic Key is QlikView's solution to create an artificial key when there is ambiguity about which key to use between two tables. This situation arises when two tables have two or more fields in common. QlikView's feature of creating association in memory\nautomatically detects this scenario and creates an additional table, which will hold the value of the new key created." }, { "code": null, "e": 83612, "s": 83511, "text": "Let us consider the following two CSV data files, which are used as input for further illustrations." }, { "code": null, "e": 83819, "s": 83612, "text": "Sales:\nProductID,ProductCategory,Country,SaleAmount\n1,Outdoor Recreation,Italy,4579\n2,Clothing,USA,4125\n3,Costumes & Accessories,South Korea,6521\n\nProduct:\nProductID, Country\n3,Brazil\n3,China\n2,Korea\n1,USA\n" }, { "code": null, "e": 83974, "s": 83819, "text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file." }, { "code": null, "e": 84243, "s": 83974, "text": "Next, we look at the data model by using the menu command for table viewer, Control+T. The following screen comes up, which shows the creation of a third table that supplies the value of the synthetic key as both the tables have ProductID and Country as matching keys." }, { "code": null, "e": 84583, "s": 84243, "text": "Synthetic keys indicate the flaw in the data model that is being used. They do not cause any issue in the correctness of the data or performance of the report. Things will work fine if a big data model has one or two instances of synthetic keys. However, if we have too many of them, then that is an implication to redesign the data model." }, { "code": null, "e": 85008, "s": 84583, "text": "Many times, we need some data to be generated programmatically by the software being used, which is not coming from a source. For example, 100 random numbers or just the dates of 23rd week of a year. A data analyst may need such data to be created to perform\nsome analysis on the data that does not contain these values as it arrived. QlikView provides a function called Autogenerate, which can be used for such requirement." }, { "code": null, "e": 85232, "s": 85008, "text": "Consider a scenario where we need to find only the dates, which are a Thursday or a Sunday. We need to find it for the range starting today until the end of the year. We create the following script, which will achieve this." }, { "code": null, "e": 85541, "s": 85232, "text": "We declare two variables to capture the first day of the current month and end of the year. Next we apply various functions and a filter condition to generate the required values. The recno() function creates one record for each of these dates. We add Autogenerate function giving the variables as the range." }, { "code": null, "e": 85710, "s": 85541, "text": "On loading the above script to QlikView's memory and creating a Table Box using the menu Layout → New Sheet Objects → Table Box, we get the data created as shown below." }, { "code": null, "e": 86001, "s": 85710, "text": "While analyzing data, we come across situations where we desire columns to become rows and vice-versa. It is not just about transposing, it also involves rolling up many columns together or repeating many values in a row many times to achieve the desired column and row layout in the table." }, { "code": null, "e": 86165, "s": 86001, "text": "Consider the following input data, which shows region wise sales of a certain product for each quarter. We create a delimited file (CSV) with the below given data." }, { "code": null, "e": 86258, "s": 86165, "text": "Quarter,Region1,Region2,Region 3\nQ1,124,421,471\nQ2,415,214,584\nQ3,417,321,582\nQ4,751,256,95\n" }, { "code": null, "e": 86468, "s": 86258, "text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. After choosing the options as shown below, click Next." }, { "code": null, "e": 86798, "s": 86468, "text": "In the next window (File Wizard → Options), click on the Crosstable button. It highlights\nthe columns in different colors. The pink color shows the qualifier field, which is going to be repeated across many rows for each value of in the Attribute Field. The cell values under the Attribute fields are taken as the data. Click OK." }, { "code": null, "e": 86928, "s": 86798, "text": "The transformed data appears in which all the Region fields are clubbed to one column but with values repeating for each quarter." }, { "code": null, "e": 87011, "s": 86928, "text": "The Load script for the crosstable transformations shows the commands given below." }, { "code": null, "e": 87132, "s": 87011, "text": "On creating a Table Box sheet object using the menu Layout → New Sheet Objects → Table Box, we get the following output." }, { "code": null, "e": 87327, "s": 87132, "text": "Straight Tables are most widely used sheet object to display data in QlikView. They are very simple yet powerful with features like column rearrangement, sorting and coloring the background etc." }, { "code": null, "e": 87454, "s": 87327, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 88138, "s": 87454, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 88420, "s": 88138, "text": "The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data. The following screen appears." }, { "code": null, "e": 88497, "s": 88420, "text": "Click \"OK\" and press \"Control+R\" to load the data into the QlikView's memory" }, { "code": null, "e": 88586, "s": 88497, "text": "Next, we create a new sheet Object of type Table Box. We follow the menu as shown below." }, { "code": null, "e": 88776, "s": 88586, "text": "QlikView prompts for the columns to be chosen which will be displayed in the final Table Box. We choose all the columns and use the Promote or Demote option to set the order of the columns." }, { "code": null, "e": 88966, "s": 88776, "text": "Next, we choose the style tab to give specific background colors to the display data. The\ncurrent style option lists many pre-built styles. We choose Pyjama Red with Stripes\nevery two rows." }, { "code": null, "e": 89119, "s": 88966, "text": "We can reorder the positions of the columns by pressing and holding the mouse button at the column headers and then dragging it to the desired position." }, { "code": null, "e": 89340, "s": 89119, "text": "Pivot Tables are widely used in data analysis to present sum of values across many dimensions available in the data. QlikView's Chart option has the feature to create a Pivot Table by choosing the appropriate chart type." }, { "code": null, "e": 89467, "s": 89340, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 90151, "s": 89467, "text": "Product_Line,Product_category,Value\nSporting Goods,Outdoor Recreation,5642\nFood, Beverages & Tobacco,2514\nApparel & Accessories,Clothing,2365\nApparel & Accessories,Costumes & Accessories,4487\nSporting Goods,Athletics,812\nHealth & Beauty,Personal Care,6912\nArts & Entertainment,Hobbies & Creative Arts,5201\nArts & Entertainment,Paintings,8451\nArts & Entertainment,Musical Instruments,1245\nHardware,Tool Accessories,456\nHome & Garden,Bathroom Accessories,241\nFood,Drinks,1247\nHome & Garden,Lawn & Garden,5462\nOffice Supplies,Presentation Supplies,577\nHardware,Blocks,548\nBaby & Toddler,Diapering,1247\nBaby & Toddler,Toys,257\nHome & Garden,Pipes,1241\nOffice Supplies,Display Board,2177\n" }, { "code": null, "e": 90435, "s": 90151, "text": "The above data is loaded to the QlikView’s memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data. The following screen appears." }, { "code": null, "e": 90509, "s": 90435, "text": "Click \"OK\" and press \"Control+R\" to load the data into QlikView's memory." }, { "code": null, "e": 90585, "s": 90509, "text": "Next, we use the chart wizard to select the Pivot Table option. Click Next." }, { "code": null, "e": 90666, "s": 90585, "text": "In the next screen, we choose Product_Line as the first dimension for the chart." }, { "code": null, "e": 90762, "s": 90666, "text": "The next screen prompts us for selecting the chart expression where we choose the sum of value." }, { "code": null, "e": 90888, "s": 90762, "text": "On clicking next, we get the screen to choose chart format in which we select Pyjama Green as the style and the default mode." }, { "code": null, "e": 90950, "s": 90888, "text": "Completing the above steps gives us the final chart as below." }, { "code": null, "e": 91458, "s": 90950, "text": "QlikView's Set Analysis feature is used to segregate the data in different sheet objects into\nmany sets and keeps the values unchanged in some of them. In simpler terms, it creates an option to not associate some sheet objects with others while the default behavior is all sheet objects get associated with each other. This helps in filtering the data in one sheet object and seeing the corresponding result in others, while the sheet object chosen as a different set displays values as per its own filters." }, { "code": null, "e": 91585, "s": 91458, "text": "Let us consider the following input data, which represents the sales figure of different product lines and product categories." }, { "code": null, "e": 92284, "s": 91585, "text": "Product_Line,Product_category,Month,Value\nArts & Entertainment,Hobbies & Creative Arts,Jan,5201\nArts & Entertainment,Paintings,Feb,8451\nArts & Entertainment,Musical Instruments,Jan,1245\nBaby & Toddler,Diapering,Mar,1247\nBaby & Toddler,Toys,Dec,257\nApparel & Accessories,Clothing,Feb,574\nApparel & Accessories,Costumes & Accessories,Apr,1204\nArts & Entertainment,Musical Instruments,Apr,3625\nBaby & Toddler,Diapering,Apr,1281\nApparel & Accessories,Clothing,Jul,2594\nArts & Entertainment,Paintings,Sep,6531\nBaby & Toddler,Toys,May,7421\nApparel & Accessories,Clothing,Aug,2541\nArts & Entertainment,Paintings,Oct,2658\nArts & Entertainment,Musical Instruments,Mar,1185\nBaby & Toddler,Diapering,Jun,1209\n" }, { "code": null, "e": 92565, "s": 92284, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data. A screen appears as shown below." }, { "code": null, "e": 92874, "s": 92565, "text": "Choose all the fields available to create a table box using the menu option Layout → New\nSheet Objects → Table Box and a list box containing the month’s field using the menu option Layout → New Sheet Objects → List Box. Also, create a straight table chart showing the total sales under each product category." }, { "code": null, "e": 93132, "s": 92874, "text": "Now we can observe the association between these three sheet objects by selecting some values in one of them. Let us select the month Apr and Jan from the Month list Box. We can see the change in values in the Table Box and chart showing the related values." }, { "code": null, "e": 93383, "s": 93132, "text": "Next, we clone the sales sum chart to produce a new set of data not associated with other sheet objects. Right click on the chart Sales Sum and click on the option Clone as shown below. Another copy of the same chart appears in the QlikView document." }, { "code": null, "e": 93591, "s": 93383, "text": "Next, we choose the second copy of the chart Sales Sum and right click it to get the chart properties. We create an expression called Sales values writing the formula under the Definition tab as shown below." }, { "code": null, "e": 93831, "s": 93591, "text": "On completing the above given steps, we find that when we select the month June we get the associated values in the Table Box and Sales Sum chart. However, the April sales does not change as it is based on the data from the set expression." }, { "code": null, "e": 94128, "s": 93831, "text": "Joins in QlikView are used to combine data from two data sets into one. Joins in QlikView mean the same as in joins in SQL. Only the column and row values that match the join conditions are shown in the output. In case you are completely new to joins, you may like\nto first learn about them here." }, { "code": null, "e": 94229, "s": 94128, "text": "Let us consider the following two CSV data files, which are used as input for further illustrations." }, { "code": null, "e": 94575, "s": 94229, "text": "Product List:\nProductID,ProductCategory\n1,Outdoor Recreation\n2,Clothing\n3,Costumes & Accessories\n4,Athletics\n5,Personal Care\n6,Hobbies & Creative Arts\n\nProductSales:\nProductID,ProductCategory,SaleAmount\n4,Athletics,1212\n5,Personal Care,5211\n6,Hobbies & Creative Arts,1021\n7,Display Board,2177\n8,Game,1145\n9,soap,1012\n10,Beverages & Tobacco,2514\n" }, { "code": null, "e": 94814, "s": 94575, "text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Then we edit the commands in the script to create an inner join between the tables." }, { "code": null, "e": 95153, "s": 94814, "text": "Inner join fetches only those rows, which are present in both the tables. In this case, the\nrows available in both Product List and Product Sales table are fetched. We create a Table Box using the menu Layout → New Sheet Objects → Table Box where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed." }, { "code": null, "e": 95272, "s": 95153, "text": "Left join involves fetching all the rows from the table in the left and the matching rows from the table in the right." }, { "code": null, "e": 95605, "s": 95272, "text": "Sales:\nLOAD ProductID, \n ProductCategory, \n SaleAmount\nFROM\n[C:\\Qlikview\\data\\product_lists.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLEFT JOIN(Sales)\n\nLOAD ProductID, \n ProductCategory\nFROM\n[C:\\Qlikview\\data\\Productsales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 95780, "s": 95605, "text": "We create a Table Box using the menu Layout → New Sheet Objects → Table\nBox, where we choose all the three fields − ProductID, ProductCategory and SaleAmount to be displayed." }, { "code": null, "e": 95900, "s": 95780, "text": "Right join involves fetching all the rows from the table in the right and the matching rows from the table in the left." }, { "code": null, "e": 96234, "s": 95900, "text": "Sales:\nLOAD ProductID, \n ProductCategory, \n SaleAmount\nFROM\n[C:\\Qlikview\\data\\product_lists.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nRIGHT JOIN(Sales)\n\nLOAD ProductID, \n ProductCategory\nFROM\n[C:\\Qlikview\\data\\Productsales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 96409, "s": 96234, "text": "We create a Table Box using the menu Layout → New Sheet Objects → Table Box, where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed." }, { "code": null, "e": 96518, "s": 96409, "text": "Outer join involves fetching all the rows from the table in the right as well as from the table in the left." }, { "code": null, "e": 96852, "s": 96518, "text": "Sales:\nLOAD ProductID, \n ProductCategory, \n SaleAmount\nFROM\n[C:\\Qlikview\\data\\product_lists.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nOUTER JOIN(Sales)\n\nLOAD ProductID, \n ProductCategory\nFROM\n[C:\\Qlikview\\data\\Productsales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 97026, "s": 96852, "text": "We create a Table Box using the menu Layout → New Sheet Objects → Table Box where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed." }, { "code": null, "e": 97558, "s": 97026, "text": "The keep command in QlikView is used to combine data from two data sets keeping both the data sets available in memory. It is very similar to joins we covered in the previous chapter except for two major differences. First difference is − in case of keep; both the datasets are available in QlikView's memory while in join the load statements produce only one data set from which you have to choose the columns. The second difference being − there is no concept of outer keep where as we have outer join available in case of joins." }, { "code": null, "e": 97659, "s": 97558, "text": "Let us consider the following two CSV data files, which are used as input for further illustrations." }, { "code": null, "e": 98006, "s": 97659, "text": "Product List:\nProductID,ProductCategory\n1,Outdoor Recreation\n2,Clothing\n3,Costumes & Accessories\n4,Athletics\n5,Personal Care\n6,Hobbies & Creative Arts\n\nProduct Sales:\nProductID,ProductCategory,SaleAmount\n4,Athletics,1212\n5,Personal Care,5211\n6,Hobbies & Creative Arts,1021\n7,Display Board,2177\n8,Game,1145\n9,soap,1012\n10,Beverages & Tobacco,2514\n" }, { "code": null, "e": 98245, "s": 98006, "text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Then we edit the commands in the script to create an inner keep between the tables." }, { "code": null, "e": 98489, "s": 98245, "text": "Inner keep fetches only those rows, which are present in both the tables. In this case, the rows available in both Product List and Product Sales table are fetched. We create a Table Boxes using the menu Layout → New Sheet Objects → Table Box." }, { "code": null, "e": 98622, "s": 98489, "text": "First, we choose only the productSales table, which gives us the fields - ProductID, ProductCategory and SaleAmount to be displayed." }, { "code": null, "e": 98721, "s": 98622, "text": "Next, we choose the ProductList data set, which gives us the fields ProductID and ProductCategory." }, { "code": null, "e": 98816, "s": 98721, "text": "Finally, we choose the All Tables option and get all the available fields from all the tables." }, { "code": null, "e": 98892, "s": 98816, "text": "The following report shows all the Tables Boxes from the above given steps." }, { "code": null, "e": 99046, "s": 98892, "text": "Left keep is similar to left join, which keeps all the rows from the table in the left along with both the data set being available in QlikView's memory." }, { "code": null, "e": 99133, "s": 99046, "text": "The following script is used to create the resulting data sets with left keep command." }, { "code": null, "e": 99493, "s": 99133, "text": "productsales:\nLOAD ProductID, \n ProductCategory, \n SaleAmount\nFROM\n[C:\\Qlikview\\data\\product_lists.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nleft keep(productsales)\nproductlists:\nLOAD ProductID, \n ProductCategory\nFROM\n[C:\\Qlikview\\data\\Productsales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 99628, "s": 99493, "text": "When we change the script as above and refresh the data in the report using Control+R, we get the following data in the sheet objects." }, { "code": null, "e": 99784, "s": 99628, "text": "Right keep is similar to left join, which keeps all the rows from the table in the right along with both the data set being available in QlikView's memory." }, { "code": null, "e": 99871, "s": 99784, "text": "The following script is used to create the resulting data sets with left keep command." }, { "code": null, "e": 100232, "s": 99871, "text": "productsales:\nLOAD ProductID, \n ProductCategory, \n SaleAmount\nFROM\n[C:\\Qlikview\\data\\product_lists.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nright keep(productsales)\nproductlists:\nLOAD ProductID, \n ProductCategory\nFROM\n[C:\\Qlikview\\data\\Productsales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);" }, { "code": null, "e": 100367, "s": 100232, "text": "When we change the script as above and refresh the data in the report using Control+R, we get the following data in the sheet objects." }, { "code": null, "e": 100634, "s": 100367, "text": "Concatenation feature in QlikView is used to append the rows from one table to another. It happens even when the tables have different number of columns. It differs from both Join and Keep command, as it does not merge the matching rows from two tables into one row." }, { "code": null, "e": 100807, "s": 100634, "text": "Let us consider the following two CSV data files, which are used as input for further illustrations. Please note the second data set has an additional column named Country." }, { "code": null, "e": 101408, "s": 100807, "text": "SalesRegionOld.csv\nProductID,ProductCategory,Region,SaleAmount\n1,Outdoor Recreation,Europe,4579\n2,Clothing,Europe,4125\n3,Costumes & Accessories,South Asia,6521\n4,Athletics,South Asia,4125\n5,Personal Care,Australia,5124\n6,Arts & Entertainment,North AMerica,1245\n7,Hardware,South America,456\n\nSalesRegionNew.csv\nProductID,ProductCategory,Region,Country,SaleAmount\n6,Arts & Entertainment,North AMerica,USA,1245\n7,Hardware,South America,Brazil,456\n8,Home & Garden,South America,Brazil,241\n9,Food,South Asia,Singapore,1247\n10,Home & Garden,South Asia,China,5462\n11,Office Supplies,Australia,Australia,577\n" }, { "code": null, "e": 101650, "s": 101408, "text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Then we edit the commands in the script to apply the concatenation between the tables." }, { "code": null, "e": 101853, "s": 101650, "text": "Next, we load the above data to QlikView's memory and create a Table Box by using the menu Layout → New Sheet Objects → Table Box where we choose all the available fields to be displayed as shown below." }, { "code": null, "e": 102029, "s": 101853, "text": "Completing above steps we get the Table box displayed as shown below. Please note the duplicate rows for the product ID 6 and 7. Concatenate does not eliminate the duplicates." }, { "code": null, "e": 102462, "s": 102029, "text": "In QlikView, many times we need to create a calendar reference object, which can be linked to any data set present in QlikView's memory. For example, you have a table that captures the sales amount and sales date but does not store the weekday or quarter, which corresponds to that date. In such a scenario, we create a Master Calendar which will supply the additional date fields like Quarter, Day etc. as required by any data set." }, { "code": null, "e": 102559, "s": 102462, "text": "Let us consider the following CSV data files, which are used as input for further illustrations." }, { "code": null, "e": 102671, "s": 102559, "text": "SalesDate,SalesVolume\n3/28/2012,3152\n3/30/2012,2458\n3/31/2012,4105\n4/8/2012,6245\n4/10/2012,5816\n4/11/2012,3522\n" }, { "code": null, "e": 102826, "s": 102671, "text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file." }, { "code": null, "e": 103029, "s": 102826, "text": "Next, we load the above data to QlikView's memory and create a Table Box by using the menu Layout → New Sheet Objects → Table Box where we choose all the available fields to be displayed as shown below." }, { "code": null, "e": 103439, "s": 103029, "text": "Next, we create the Master Calendar by writing the following script in the script editor. Here we use the table DailySales as a resident table from which we capture the Maximum and Minimum dates. We load each of the dates within this range using the second load statement above the resident load. Finally, we have a third load statement, which extracts the year, quarter, month etc. from the SalesDate values." }, { "code": null, "e": 103607, "s": 103439, "text": "After creation of the complete load script along with the master calendar, we create a table box to view the data using the menu Layout → New Sheet Objects → Table Box" }, { "code": null, "e": 103738, "s": 103607, "text": "The final output shows the table showing the Quarter and Month values, which are created using the Sales data and Master Calendar." }, { "code": null, "e": 103930, "s": 103738, "text": "Mapping table is a table, which is created to map the column values between two tables. It is also called a Lookup table, which is only used to look for a related value from some other table." }, { "code": null, "e": 104033, "s": 103930, "text": "Let us consider the following input data file, which represents the sales values in different regions." }, { "code": null, "e": 104428, "s": 104033, "text": "ProductID,ProductCategory,Region,SaleAmount\n1,Outdoor Recreation,Europe,4579\n2,Clothing,Europe,4125\n3,Costumes & Accessories,South Asia,6521\n4,Athletics,South Asia,4125\n5,Personal Care,Australia,5124\n6,Arts & Entertainment,North AMerica,1245\n7,Hardware,South America,456\n8,Home & Garden,South America,241\n9,Food,South Asia,1247\n10,Home & Garden,South Asia,5462\n11,Office Supplies,Australia,577\n" }, { "code": null, "e": 104491, "s": 104428, "text": "The following data represents the countries and their regions." }, { "code": null, "e": 104669, "s": 104491, "text": "Region,Country\nEurope,Germany\nEurope,Italy\nSouth Asia,Singapore\nSouth Asia,Korea\nNorth AMerica,USA\nSouth America,Brazil\nSouth America,Peru\nSouth Asia,China\nSouth Asia,Sri Lanka\n" }, { "code": null, "e": 104985, "s": 104669, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and ess Control+R to load the data into the QlikView's memory." }, { "code": null, "e": 105127, "s": 104985, "text": "Let us create two table boxes for each of the above table as shown below. Here we cannot get the value of country in the Sales region report." }, { "code": null, "e": 105281, "s": 105127, "text": "The following script produces the mapping table, which maps the region value from the sales table with the country value from the MapCountryRegion table." }, { "code": null, "e": 105424, "s": 105281, "text": "On completing the above steps and creating a Table box to view the data, we get the country columns along with other columns from Sales table." }, { "code": null, "e": 105879, "s": 105424, "text": "Circular Reference occurs when we can traverse from one table to another using two or more different paths. This means you can join Table1 with Table2 directly using a column or you can also first join Table1 with Table3 and then table3 with Table2. This can lead to incorrect result in the output formed by a data model, which loads all these three tables. QlikView prevents the load of such data into its memory once it recognizes a circular reference." }, { "code": null, "e": 105982, "s": 105879, "text": "Let us consider the following three CSV data files, which are used as input for further illustrations." }, { "code": null, "e": 106457, "s": 105982, "text": "SalesCountries:\nProductID,ProductCategory,Country,SaleAmount\n1,Outdoor Recreation,Italy,4579\n2,Clothing,USA,4125\n3,Costumes & Accessories,South Korea,6521\n4,Athletics,Japan,4125\n5,Personal Care,Brazil,5124\n6,Arts & Entertainment,China,1245\n7,Hardware,South America,456\n8,Home & Garden,Peru,241\n9,Food,India,1247\n10,Home & Garden,Singapore,5462\n11,Office Supplies,Hungary,577\n\nProductCountry:\nProductID, Country\n3,Brazil\n3,China\n2,Korea\n1,USA\n2,Singapore\n7,Sri Lanka\n1,Italy\n" }, { "code": null, "e": 106612, "s": 106457, "text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file." }, { "code": null, "e": 106820, "s": 106612, "text": "After creating the above script, we load the data to QlikView's memory using the command Control+R. This is when we get the error prompt mentioning the presence of circular loop in the tables getting loaded." }, { "code": null, "e": 107264, "s": 106820, "text": "To find the exact cause of the above warning we can look at the data model by using the menu command for table viewer - Control+T. The following screen comes up, which clearly shows the circular reference. Here the join between RegionCountry and SalesRegion can be directly achieved using the field Region. It can also be achieved by first going to the table ProductCountry, using the field Country and then mapping ProdcutID with Salesregion." }, { "code": null, "e": 107614, "s": 107264, "text": "The above circular reference can be resolved by renaming some of the columns in the data sets so that QlikView does not form an association between the tables automatically using the column names. For this, we will rename country column in RegionCountry to SalesCountry. In the data set ProdcuCountry, we rename the Country column to ProductCountry." }, { "code": null, "e": 107790, "s": 107614, "text": "The Rectified data model after renaming the column above can be seen using the command Control+T. Now we can see that the relationship between the tables does not form a loop." }, { "code": null, "e": 107909, "s": 107790, "text": "Pressing Control+R to reload the data does not give us the warning anymore and we can use this data to create reports." }, { "code": null, "e": 107942, "s": 107909, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 107955, "s": 107942, "text": " Arthur Fong" }, { "code": null, "e": 107962, "s": 107955, "text": " Print" }, { "code": null, "e": 107973, "s": 107962, "text": " Add Notes" } ]
M-Coloring Problem
In this problem, an undirected graph is given. There is also provided m colors. The problem is to find if it is possible to assign nodes with m different colors, such that no two adjacent vertices of the graph are of the same colors. If the solution exists, then display which color is assigned on which vertex. Starting from vertex 0, we will try to assign colors one by one to different nodes. But before assigning, we have to check whether the color is safe or not. A color is not safe whether adjacent vertices are containing the same color. Input: The adjacency matrix of a graph G(V, E) and an integer m, which indicates the maximum number of colors that can be used. Let the maximum color m = 3. Output: This algorithm will return which node will be assigned with which color. If the solution is not possible, it will return false. For this input the assigned colors are: Node 0 -> color 1 Node 1 -> color 2 Node 2 -> color 3 Node 3 -> color 2 isValid(vertex, colorList, col) Input − Vertex, colorList to check, and color, which is trying to assign. Output − True if the color assigning is valid, otherwise false. Begin for all vertices v of the graph, do if there is an edge between v and i, and col = colorList[i], then return false done return true End graphColoring(colors, colorList, vertex) Input − Most possible colors, the list for which vertices are colored with which color, and the starting vertex. Output − True, when colors are assigned, otherwise false. Begin if all vertices are checked, then return true for all colors col from available colors, do if isValid(vertex, color, col), then add col to the colorList for vertex if graphColoring(colors, colorList, vertex+1) = true, then return true remove color for vertex done return false End #include<iostream> #define V 4 using namespace std; bool graph[V][V] = { {0, 1, 1, 1}, {1, 0, 1, 0}, {1, 1, 0, 1}, {1, 0, 1, 0}, }; void showColors(int color[]) { cout << "Assigned Colors are: " <<endl; for (int i = 0; i < V; i++) cout << color[i] << " "; cout << endl; } bool isValid(int v,int color[], int c) { //check whether putting a color valid for v for (int i = 0; i < V; i++) if (graph[v][i] && c == color[i]) return false; return true; } bool graphColoring(int colors, int color[], int vertex) { if (vertex == V) //when all vertices are considered return true; for (int col = 1; col <= colors; col++) { if (isValid(vertex,color, col)) { //check whether color col is valid or not color[vertex] = col; if (graphColoring (colors, color, vertex+1) == true) //go for additional vertices return true; color[vertex] = 0; } } return false; //when no colors can be assigned } bool checkSolution(int m) { int *color = new int[V]; //make color matrix for each vertex for (int i = 0; i < V; i++) color[i] = 0; //initially set to 0 if (graphColoring(m, color, 0) == false) { //for vertex 0 check graph coloring cout << "Solution does not exist."; return false; } showColors(color); return true; } int main() { int colors = 3; // Number of colors checkSolution (colors); } Assigned Colors are: 1 2 3 2
[ { "code": null, "e": 1374, "s": 1062, "text": "In this problem, an undirected graph is given. There is also provided m colors. The problem is to find if it is possible to assign nodes with m different colors, such that no two adjacent vertices of the graph are of the same colors. If the solution exists, then display which color is assigned on which vertex." }, { "code": null, "e": 1608, "s": 1374, "text": "Starting from vertex 0, we will try to assign colors one by one to different nodes. But before assigning, we have to check whether the color is safe or not. A color is not safe whether adjacent vertices are containing the same color." }, { "code": null, "e": 2017, "s": 1608, "text": "Input:\nThe adjacency matrix of a graph G(V, E) and an integer m, which indicates the maximum number of colors that can be used.\n\n\nLet the maximum color m = 3.\nOutput:\nThis algorithm will return which node will be assigned with which color. If the solution is not possible, it will return false.\nFor this input the assigned colors are:\nNode 0 -> color 1\nNode 1 -> color 2\nNode 2 -> color 3\nNode 3 -> color 2\n\n" }, { "code": null, "e": 2049, "s": 2017, "text": "isValid(vertex, colorList, col)" }, { "code": null, "e": 2123, "s": 2049, "text": "Input − Vertex, colorList to check, and color, which is trying to assign." }, { "code": null, "e": 2187, "s": 2123, "text": "Output − True if the color assigning is valid, otherwise false." }, { "code": null, "e": 2353, "s": 2187, "text": "Begin\n for all vertices v of the graph, do\n if there is an edge between v and i, and col = colorList[i], then\n return false\n done\n return true\nEnd" }, { "code": null, "e": 2394, "s": 2353, "text": "graphColoring(colors, colorList, vertex)" }, { "code": null, "e": 2507, "s": 2394, "text": "Input − Most possible colors, the list for which vertices are colored with which color, and the starting vertex." }, { "code": null, "e": 2565, "s": 2507, "text": "Output − True, when colors are assigned, otherwise false." }, { "code": null, "e": 2915, "s": 2565, "text": "Begin\n if all vertices are checked, then\n return true\n for all colors col from available colors, do\n if isValid(vertex, color, col), then\n add col to the colorList for vertex\n if graphColoring(colors, colorList, vertex+1) = true, then\n return true\n remove color for vertex\n done\n return false\nEnd" }, { "code": null, "e": 4401, "s": 2915, "text": "#include<iostream>\n#define V 4\nusing namespace std;\n\nbool graph[V][V] = {\n {0, 1, 1, 1},\n {1, 0, 1, 0},\n {1, 1, 0, 1},\n {1, 0, 1, 0},\n};\n\nvoid showColors(int color[]) {\n cout << \"Assigned Colors are: \" <<endl;\n for (int i = 0; i < V; i++)\n cout << color[i] << \" \";\n cout << endl;\n}\n\nbool isValid(int v,int color[], int c) { //check whether putting a color valid for v\n for (int i = 0; i < V; i++)\n if (graph[v][i] && c == color[i])\n return false;\n return true;\n}\n\nbool graphColoring(int colors, int color[], int vertex) {\n if (vertex == V) //when all vertices are considered\n return true;\n\n for (int col = 1; col <= colors; col++) {\n if (isValid(vertex,color, col)) { //check whether color col is valid or not\n color[vertex] = col;\n if (graphColoring (colors, color, vertex+1) == true) //go for additional vertices\n return true;\n \n color[vertex] = 0;\n }\n }\n return false; //when no colors can be assigned\n}\n\nbool checkSolution(int m) {\n int *color = new int[V]; //make color matrix for each vertex\n\n for (int i = 0; i < V; i++)\n color[i] = 0; //initially set to 0\n\n if (graphColoring(m, color, 0) == false) { //for vertex 0 check graph coloring\n cout << \"Solution does not exist.\";\n return false;\n }\n showColors(color);\n return true;\n}\n\nint main() {\n int colors = 3; // Number of colors\n checkSolution (colors);\n}" }, { "code": null, "e": 4430, "s": 4401, "text": "Assigned Colors are:\n1 2 3 2" } ]
How to select records beginning with certain numbers in MySQL?
The optimal solution to select records beginning with certain numbers, use MySQL LIKE operator. Let us first create a table − mysql> create table DemoTable ( ClientId bigint, ClientName varchar(40) ); Query OK, 0 rows affected (0.82 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(23568777,'Chris Brown'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(9085544,'John Doe'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(9178432,'John Doe'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(9078482,'David Miller'); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----------+--------------+ | ClientId | ClientName | +----------+--------------+ | 23568777 | Chris Brown | | 9085544 | John Doe | | 9178432 | John Doe | | 9078482 | David Miller | +----------+--------------+ 4 rows in set (0.00 sec) Following is the query to select records beginning with certain numbers in MySQL − mysql> select *from DemoTable where ClientId LIKE '90%'; This will produce the following output − +----------+--------------+ | ClientId | ClientName | +----------+--------------+ | 9085544 | John Doe | | 9078482 | David Miller | +----------+--------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1188, "s": 1062, "text": "The optimal solution to select records beginning with certain numbers, use MySQL LIKE operator. Let us first create a table −" }, { "code": null, "e": 1306, "s": 1188, "text": "mysql> create table DemoTable\n(\n ClientId bigint,\n ClientName varchar(40)\n);\nQuery OK, 0 rows affected (0.82 sec)" }, { "code": null, "e": 1362, "s": 1306, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1742, "s": 1362, "text": "mysql> insert into DemoTable values(23568777,'Chris Brown');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(9085544,'John Doe');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values(9178432,'John Doe');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values(9078482,'David Miller');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 1802, "s": 1742, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1833, "s": 1802, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1874, "s": 1833, "text": "This will produce the following output −" }, { "code": null, "e": 2123, "s": 1874, "text": "+----------+--------------+\n| ClientId | ClientName |\n+----------+--------------+\n| 23568777 | Chris Brown |\n| 9085544 | John Doe |\n| 9178432 | John Doe |\n| 9078482 | David Miller |\n+----------+--------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2206, "s": 2123, "text": "Following is the query to select records beginning with certain numbers in MySQL −" }, { "code": null, "e": 2263, "s": 2206, "text": "mysql> select *from DemoTable where ClientId LIKE '90%';" }, { "code": null, "e": 2304, "s": 2263, "text": "This will produce the following output −" }, { "code": null, "e": 2497, "s": 2304, "text": "+----------+--------------+\n| ClientId | ClientName |\n+----------+--------------+\n| 9085544 | John Doe |\n| 9078482 | David Miller |\n+----------+--------------+\n2 rows in set (0.00 sec)" } ]
HTML5 Canvas - Create Gradients
HTML5 canvas allows us to fill and stroke shapes using linear and radial gradients using the following methods − addColorStop(offset, color) This method adds a color stop with the given color to the gradient at the given offset. Here 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end. createLinearGradient(x0, y0, x1, y1) This method returns a CanvasGradient object that represents a linear gradient that paints along the line given by the coordinates represented by the arguments. The four arguments represent the starting point (x1,y1) and end point (x2,y2) of the gradient. createRadialGradient(x0, y0, r0, x1, y1, r1) This method returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the circles represented by the arguments. The first three arguments define a circle with coordinates (x1,y1) and radius r1 and the second a circle with coordinates (x2,y2) and radius r2. Following is a simple example which makes use of above mentioned methods to create Linear gradient. <!DOCTYPE HTML> <html> <head> <style> #test { width:100px; height:100px; margin:0px auto; } </style> <script type = "text/javascript"> function drawShape() { // get the canvas element using the DOM var canvas = document.getElementById('mycanvas'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); // Create Linear Gradients var lingrad = ctx.createLinearGradient(0,0,0,150); lingrad.addColorStop(0, '#00ABEB'); lingrad.addColorStop(0.5, '#fff'); lingrad.addColorStop(0.5, '#66CC00'); lingrad.addColorStop(1, '#fff'); var lingrad2 = ctx.createLinearGradient(0,50,0,95); lingrad2.addColorStop(0.5, '#000'); lingrad2.addColorStop(1, 'rgba(0,0,0,0)'); // assign gradients to fill and stroke styles ctx.fillStyle = lingrad; ctx.strokeStyle = lingrad2; // draw shapes ctx.fillRect(10,10,130,130); ctx.strokeRect(50,50,50,50); } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body id = "test" onload = "drawShape();"> <canvas id = "mycanvas"></canvas> </body> </html> The above example would produce the following result − Following is a simple example which makes use of the above-mentioned methods to create Radial gradient. <!DOCTYPE HTML> <html> <head> <style> #test { width:100px; height:100px; margin:0px auto; } </style> <script type = "text/javascript"> function drawShape(){ // get the canvas element using the DOM var canvas = document.getElementById('mycanvas'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext){ // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); // Create gradients var radgrad = ctx.createRadialGradient(45,45,10,52,50,30); radgrad.addColorStop(0, '#A7D30C'); radgrad.addColorStop(0.9, '#019F62'); radgrad.addColorStop(1, 'rgba(1,159,98,0)'); var radgrad2 = ctx.createRadialGradient(105,105,20,112,120,50); radgrad2.addColorStop(0, '#FF5F98'); radgrad2.addColorStop(0.75, '#FF0188'); radgrad2.addColorStop(1, 'rgba(255,1,136,0)'); var radgrad3 = ctx.createRadialGradient(95,15,15,102,20,40); radgrad3.addColorStop(0, '#00C9FF'); radgrad3.addColorStop(0.8, '#00B5E2'); radgrad3.addColorStop(1, 'rgba(0,201,255,0)'); var radgrad4 = ctx.createRadialGradient(0,150,50,0,140,90); radgrad4.addColorStop(0, '#F4F201'); radgrad4.addColorStop(0.8, '#E4C700'); radgrad4.addColorStop(1, 'rgba(228,199,0,0)'); // draw shapes ctx.fillStyle = radgrad4; ctx.fillRect(0,0,150,150); ctx.fillStyle = radgrad3; ctx.fillRect(0,0,150,150); ctx.fillStyle = radgrad2; ctx.fillRect(0,0,150,150); ctx.fillStyle = radgrad; ctx.fillRect(0,0,150,150); } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body id = "test" onload = "drawShape();"> <canvas id = "mycanvas"></canvas> </body> </html> The above example would produce the following result − 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2721, "s": 2608, "text": "HTML5 canvas allows us to fill and stroke shapes using linear and radial gradients using the following methods −" }, { "code": null, "e": 2749, "s": 2721, "text": "addColorStop(offset, color)" }, { "code": null, "e": 2924, "s": 2749, "text": "This method adds a color stop with the given color to the gradient at the given offset. Here 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end." }, { "code": null, "e": 2961, "s": 2924, "text": "createLinearGradient(x0, y0, x1, y1)" }, { "code": null, "e": 3216, "s": 2961, "text": "This method returns a CanvasGradient object that represents a linear gradient that paints along the line given by the coordinates represented by the arguments. The four arguments represent the starting point (x1,y1) and end point (x2,y2) of the gradient." }, { "code": null, "e": 3261, "s": 3216, "text": "createRadialGradient(x0, y0, r0, x1, y1, r1)" }, { "code": null, "e": 3562, "s": 3261, "text": "This method returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the circles represented by the arguments. The first three arguments define a circle with coordinates (x1,y1) and radius r1 and the second a circle with coordinates (x2,y2) and radius r2." }, { "code": null, "e": 3662, "s": 3562, "text": "Following is a simple example which makes use of above mentioned methods to create Linear gradient." }, { "code": null, "e": 5397, "s": 3662, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <style>\n #test {\n width:100px;\n height:100px;\n margin:0px auto;\n }\n </style>\n \n <script type = \"text/javascript\">\n function drawShape() {\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext) {\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n // Create Linear Gradients\n var lingrad = ctx.createLinearGradient(0,0,0,150);\n \n lingrad.addColorStop(0, '#00ABEB');\n lingrad.addColorStop(0.5, '#fff');\n \n lingrad.addColorStop(0.5, '#66CC00');\n lingrad.addColorStop(1, '#fff');\n \n var lingrad2 = ctx.createLinearGradient(0,50,0,95);\n lingrad2.addColorStop(0.5, '#000');\n lingrad2.addColorStop(1, 'rgba(0,0,0,0)');\n \n // assign gradients to fill and stroke styles\n ctx.fillStyle = lingrad;\n ctx.strokeStyle = lingrad2;\n \n // draw shapes\n ctx.fillRect(10,10,130,130);\n ctx.strokeRect(50,50,50,50);\n } else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n </script>\n </head>\n \n <body id = \"test\" onload = \"drawShape();\">\n <canvas id = \"mycanvas\"></canvas>\n </body>\n \n</html>" }, { "code": null, "e": 5452, "s": 5397, "text": "The above example would produce the following result −" }, { "code": null, "e": 5556, "s": 5452, "text": "Following is a simple example which makes use of the above-mentioned methods to create Radial gradient." }, { "code": null, "e": 7981, "s": 5556, "text": "<!DOCTYPE HTML>\n<html>\n <head>\n \n <style>\n #test {\n width:100px;\n height:100px;\n margin:0px auto;\n }\n </style>\n \n <script type = \"text/javascript\">\n function drawShape(){\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext){\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n // Create gradients\n var radgrad = ctx.createRadialGradient(45,45,10,52,50,30);\n radgrad.addColorStop(0, '#A7D30C');\n radgrad.addColorStop(0.9, '#019F62');\n radgrad.addColorStop(1, 'rgba(1,159,98,0)');\n \n var radgrad2 = ctx.createRadialGradient(105,105,20,112,120,50);\n radgrad2.addColorStop(0, '#FF5F98');\n radgrad2.addColorStop(0.75, '#FF0188');\n radgrad2.addColorStop(1, 'rgba(255,1,136,0)');\n \n var radgrad3 = ctx.createRadialGradient(95,15,15,102,20,40);\n radgrad3.addColorStop(0, '#00C9FF');\n radgrad3.addColorStop(0.8, '#00B5E2');\n radgrad3.addColorStop(1, 'rgba(0,201,255,0)');\n \n var radgrad4 = ctx.createRadialGradient(0,150,50,0,140,90);\n radgrad4.addColorStop(0, '#F4F201');\n radgrad4.addColorStop(0.8, '#E4C700');\n radgrad4.addColorStop(1, 'rgba(228,199,0,0)');\n \n // draw shapes\n ctx.fillStyle = radgrad4;\n ctx.fillRect(0,0,150,150);\n \n ctx.fillStyle = radgrad3;\n ctx.fillRect(0,0,150,150);\n \n ctx.fillStyle = radgrad2;\n ctx.fillRect(0,0,150,150);\n \n ctx.fillStyle = radgrad;\n ctx.fillRect(0,0,150,150);\n }\n \n else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n </script>\n </head>\n \n <body id = \"test\" onload = \"drawShape();\">\n <canvas id = \"mycanvas\"></canvas>\n </body>\n</html>" }, { "code": null, "e": 8036, "s": 7981, "text": "The above example would produce the following result −" }, { "code": null, "e": 8069, "s": 8036, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 8083, "s": 8069, "text": " Anadi Sharma" }, { "code": null, "e": 8118, "s": 8083, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8132, "s": 8118, "text": " Anadi Sharma" }, { "code": null, "e": 8167, "s": 8132, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8184, "s": 8167, "text": " Frahaan Hussain" }, { "code": null, "e": 8219, "s": 8184, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8250, "s": 8219, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8283, "s": 8250, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 8314, "s": 8283, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8349, "s": 8314, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8380, "s": 8349, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8387, "s": 8380, "text": " Print" }, { "code": null, "e": 8398, "s": 8387, "text": " Add Notes" } ]
Going Prescriptive — The Real Super Power of Data Science | by Martin Schmitz, PhD | Towards Data Science
At its core, Data Science relies on methods of machine learning. But Data Science is also more than just predicting who will buy, who will click or what will break. Data Science uses ML methods and combines them with other methods. In this article, we will discuss Prescriptive Analytics, a technology which combines machine learning with optimization. My favorite example of how to explain comes from Ingo Mierswa. Let's say you have a machine learning model which predicts that it will rain tomorrow. Nice — but what does it mean for you? Will you drive to work or will you bike? You could not be the only one who prefers to drive in this case. The result could be, that you are stuckin traffic for an hour. Would it be better to still take the bike, despite the rain? The solution to this is to define a custom fitness function. You would maximize this fitness for given the weather prediction, the expected traffic and your personal preferences. This is prescriptive analytics! The idea is not to merely forecast what will happen but also advice on what to do. In this easy example, we have a very small hyperspace of actionable options: Taking the bike or not. This makes our optimization easy: Evaluate both and take the best. In the upcoming real-world example, you can see that this hyperspace can be huge and the optimization problem quite tricky. You might be tempted to use direct predictive modeling for price calculation. Let's say you have a data set with the correct price. You can treat this as a regression problem and solve using your favorite ML method. The resulting model can then directly be used in production to predict prices. The big problem here is the miracle to have a label. Where do you get the price from? In practice, you use human-generated prices. How do you know that these are good? You essentially limit the maximum quality of your modeling by the quality of these labels. Of course, you can bootstrap yourself out of this problem by using A/B testing. You would sometimes offer prices which are lower or higher than the human-generated prices and measure success. But this is expensive and not always feasible. Another approach to solve this is Prescriptive Pricing. Similar to the rain-example we need to define a fitness function which reflects the business case. In a retail example, you can start off with the demand-price relationship. An easy fitness function would look like this: fitness = gain = (Price — Cost)*demand where demand is the result of a machine learning model which depends on the day, price and maybe even other factors. If you are working with an insurance provider your fitness will be something like: fitness = profitability = f(Premium,DefaultRisk,..) In this example, we want to optimize the premium to have maximum profitability. The other factors are again derived from machine learning models which depend on customer attribute. Let’s have a look at how to implement such a system. I am employed at RapidMiner and thus my go-to tool is of course RapidMiner. Of course you can build similar things in Python or R if you like. In our implementation we want to score if customers will accept a given offer. The result is a confidence for acceptance which depends on the price and the other meta data. It’s important to note here, that confidence is not equal to probability, even if it is normalized in [0,1]. In the prescriptive part we will use this model to define our price. We will vary the price in a way, that each customer has a 0.75 confidence of accepting our offer. The 0.75 might be derived from sample constraints. For example, we want to have at least 1000 accepted offers per month. The fitness function we derive from this is: fitness = price-if([confidence(accept)]<0.75,(0.75-[confidence(accept)])*1e6,0) meaning we add a penalty factor whenever our confidence drops below our threshold. The example process which is depicted above is first deriving a model to predict. Next we run into the optimization. The optimization takes the input example we want to optimize, a reference set to set default bounds and the model. Within the optimization loop we calculate the fitness above. Since the optimization is univariate we can use a grid. We could use CMA-ES, BYOBA or Evolutionary Optimization. The result is a fitness like this We can see that the fitness rises with increasing price and then drops because the confidence is below 0.75. The derived price is: 976 Euro. The process depicted here can be found on my github profile.
[ { "code": null, "e": 525, "s": 172, "text": "At its core, Data Science relies on methods of machine learning. But Data Science is also more than just predicting who will buy, who will click or what will break. Data Science uses ML methods and combines them with other methods. In this article, we will discuss Prescriptive Analytics, a technology which combines machine learning with optimization." }, { "code": null, "e": 943, "s": 525, "text": "My favorite example of how to explain comes from Ingo Mierswa. Let's say you have a machine learning model which predicts that it will rain tomorrow. Nice — but what does it mean for you? Will you drive to work or will you bike? You could not be the only one who prefers to drive in this case. The result could be, that you are stuckin traffic for an hour. Would it be better to still take the bike, despite the rain?" }, { "code": null, "e": 1237, "s": 943, "text": "The solution to this is to define a custom fitness function. You would maximize this fitness for given the weather prediction, the expected traffic and your personal preferences. This is prescriptive analytics! The idea is not to merely forecast what will happen but also advice on what to do." }, { "code": null, "e": 1529, "s": 1237, "text": "In this easy example, we have a very small hyperspace of actionable options: Taking the bike or not. This makes our optimization easy: Evaluate both and take the best. In the upcoming real-world example, you can see that this hyperspace can be huge and the optimization problem quite tricky." }, { "code": null, "e": 1824, "s": 1529, "text": "You might be tempted to use direct predictive modeling for price calculation. Let's say you have a data set with the correct price. You can treat this as a regression problem and solve using your favorite ML method. The resulting model can then directly be used in production to predict prices." }, { "code": null, "e": 2322, "s": 1824, "text": "The big problem here is the miracle to have a label. Where do you get the price from? In practice, you use human-generated prices. How do you know that these are good? You essentially limit the maximum quality of your modeling by the quality of these labels. Of course, you can bootstrap yourself out of this problem by using A/B testing. You would sometimes offer prices which are lower or higher than the human-generated prices and measure success. But this is expensive and not always feasible." }, { "code": null, "e": 2599, "s": 2322, "text": "Another approach to solve this is Prescriptive Pricing. Similar to the rain-example we need to define a fitness function which reflects the business case. In a retail example, you can start off with the demand-price relationship. An easy fitness function would look like this:" }, { "code": null, "e": 2638, "s": 2599, "text": "fitness = gain = (Price — Cost)*demand" }, { "code": null, "e": 2755, "s": 2638, "text": "where demand is the result of a machine learning model which depends on the day, price and maybe even other factors." }, { "code": null, "e": 2838, "s": 2755, "text": "If you are working with an insurance provider your fitness will be something like:" }, { "code": null, "e": 2890, "s": 2838, "text": "fitness = profitability = f(Premium,DefaultRisk,..)" }, { "code": null, "e": 3071, "s": 2890, "text": "In this example, we want to optimize the premium to have maximum profitability. The other factors are again derived from machine learning models which depend on customer attribute." }, { "code": null, "e": 3267, "s": 3071, "text": "Let’s have a look at how to implement such a system. I am employed at RapidMiner and thus my go-to tool is of course RapidMiner. Of course you can build similar things in Python or R if you like." }, { "code": null, "e": 3549, "s": 3267, "text": "In our implementation we want to score if customers will accept a given offer. The result is a confidence for acceptance which depends on the price and the other meta data. It’s important to note here, that confidence is not equal to probability, even if it is normalized in [0,1]." }, { "code": null, "e": 3882, "s": 3549, "text": "In the prescriptive part we will use this model to define our price. We will vary the price in a way, that each customer has a 0.75 confidence of accepting our offer. The 0.75 might be derived from sample constraints. For example, we want to have at least 1000 accepted offers per month. The fitness function we derive from this is:" }, { "code": null, "e": 3962, "s": 3882, "text": "fitness = price-if([confidence(accept)]<0.75,(0.75-[confidence(accept)])*1e6,0)" }, { "code": null, "e": 4045, "s": 3962, "text": "meaning we add a penalty factor whenever our confidence drops below our threshold." }, { "code": null, "e": 4485, "s": 4045, "text": "The example process which is depicted above is first deriving a model to predict. Next we run into the optimization. The optimization takes the input example we want to optimize, a reference set to set default bounds and the model. Within the optimization loop we calculate the fitness above. Since the optimization is univariate we can use a grid. We could use CMA-ES, BYOBA or Evolutionary Optimization. The result is a fitness like this" }, { "code": null, "e": 4626, "s": 4485, "text": "We can see that the fitness rises with increasing price and then drops because the confidence is below 0.75. The derived price is: 976 Euro." } ]
How to answer a coding interview question | by Tuan Nhu Dinh | Towards Data Science
This blog is a part of my “15 days cheat sheet for hacking technical interviews at big tech companies”. In this blog, we focus on a step by step approach to solve a coding interview question. The coding interview sections are designed to reveal how you think, communicate, and solve problems. Hence, giving the correct and perfect solution to a problem does not guarantee a positive outcome, you will be judged on how you come up with the answer. The below are the steps I usually take to not only give myself the best chance of answering the question correctly, but also give the interviewer a decent feel for how I handle the question. You are often asked to give a short introduction about yourself in almost every coding interview. It is a critical part of making the first impression and that is the only predictable question. Hence, do prepare yourself with a concise introduction (under a minute or two) following the format: A sentence about your name and general background. A few sentences about your professional experiences after university. If you are fresh graduates, focus on your internships and school projects. Otherwise, select one or two challenging projects or the projects required relevant skills to the position you are applying. Finish with a statement saying why you are seeking a new job opportunity and why you are interested in the role you applied for. “Hi, I’m Dinh Tuan and I’m a backend engineer with over six years of experience specialising in designing and implementing high scale and high availability backend system. I started my career in SEA Group, one of the biggest tech company in South East Asia. During 5 years in SEA, I led the backend team implementing a gaming platform which serves 3 millions concurrent users and 500 thousands request per second at the peak time. I also helped to grow a team of 30 engineers in Vietnam after they acquired a Vietnamese startup in food delivery services. In early 2019, I joined Datarobot, a unicorn in Boston, United States. I work under code and architecture team to design and implement the feature to support multiple external compute clusters (including both Kubernetes and Hadoop).I’m interested in the software engineer position in Facebook because I would like to grow my technical skills further in a large scale social platform.” You are usually given the opportunity to ask questions at the end of the interview. Skipping this part means missing out on the opportunity to learn about the nature of the work and the culture of the organisation. Moreover, a good question can also showcase your communication skills, demonstrate your interest in the role as well as make a good impression. Some of my favourite questions are: 1. What technology is the company/ your team currently using?2. What is your favourite thing about working for the company?3. How much say do developers have regarding the products?4. What qualities make a software engineer excel at this company?5. How flexible are the working hours?6. How will role performance be measured? What metric will role performance be measured with?7. How has your role changed since joining the company?8. What are the most challenging aspects of the job?9. What is the current team composition like?10. What resources does the company have for new hires to study its product and processes? Do read the question carefully. If the question is not written, do repeat what you listen from the interviewer. Do work through the given examples or come up with some examples. It does not only help to ensure your understandings, but also allow you to pick up on patterns and generalisations to answer the question. Do clarify any assumptions you made such as input format or range. Do come up with the easiest and most obvious solution. Do look for improvements and try to come up with a better solution. Do think out loud, talk with your interviewer what you’re thinking. It keeps them engaged, allows them to understand your thought process as well as gives them a chance to point you in the right direction or stop you before you waste too much time. Do ask for hints if you’re stuck. Do work through some examples with your solution if it is not so trivial. You can also use whiteboard to work through your solution if it is necessary. Do state and explain the time and space complexity of your approaches. Don’t jump straight into writing code. You should only start coding after your interviewer understand what you’re going to do and give you the green light. Don’t keep silent for too long. If you are stuck, try to speak out the points making you confused. If you need to be quiet to think, just let the interviewer know (but keep it less than a minute). Don’t ignore the information from the interviewer. Every piece is important. Don’t interrupt your interviewer when they are talking. Don’t get frustrated or discouraged. Take a deep breath and keep trying by walking through more samples, thinking about different algorithms and data structures. Don’t try to bluff it. If the interview hints something you are unfamiliar with, just admit it and move on. Do explain what you are writing or typing. Do follow the good coding style (such as using descriptive variable names) and structure your codes well (with functions and classes if they are necessary). Do speak out your understanding about the algorithm, data structures or built-in functions you use. Do ask for the permission to use the built-in functions or skip some input checking. They may allow you to get away the implementation of some trivial functions or get back later if there is enough time. Do pay attention to your hand-writing if you are required to write on the whiteboard. You need to ensure it readable and well-organised (especially space between words and lines). Don’t write pseudo code. Although you don’t need worry too much about the syntax, you are expected to deliver bug-free production-ready code. Don’t keep silent for too long. Do think about how you will test your code, list down corner test cases. Do run through your code with your interviewer for the test cases. Do fix any bugs that comes up when scanning your code with the test cases. Do look out for places where you can refactor. Do evaluate the time complexity and space complexity of your written code. Do suggest any better solution if it is existed and more time is given. Don’t argue with the interviewer. As the interviewer is familiar with the question, they are unlikely wrong. Take their feedback and think about it carefully. Do ask the questions to understand the work and company culture if the interview gives you that opportunity. Do thank the interviewer for their time. Don’t ask too many questions and try to end on time. Don’t asking about your interview performance. Don’t continue discussing about the coding problem as it is over. References: Crack the coding interviewTechnical interview handbook Crack the coding interview Technical interview handbook
[ { "code": null, "e": 364, "s": 172, "text": "This blog is a part of my “15 days cheat sheet for hacking technical interviews at big tech companies”. In this blog, we focus on a step by step approach to solve a coding interview question." }, { "code": null, "e": 810, "s": 364, "text": "The coding interview sections are designed to reveal how you think, communicate, and solve problems. Hence, giving the correct and perfect solution to a problem does not guarantee a positive outcome, you will be judged on how you come up with the answer. The below are the steps I usually take to not only give myself the best chance of answering the question correctly, but also give the interviewer a decent feel for how I handle the question." }, { "code": null, "e": 1105, "s": 810, "text": "You are often asked to give a short introduction about yourself in almost every coding interview. It is a critical part of making the first impression and that is the only predictable question. Hence, do prepare yourself with a concise introduction (under a minute or two) following the format:" }, { "code": null, "e": 1156, "s": 1105, "text": "A sentence about your name and general background." }, { "code": null, "e": 1426, "s": 1156, "text": "A few sentences about your professional experiences after university. If you are fresh graduates, focus on your internships and school projects. Otherwise, select one or two challenging projects or the projects required relevant skills to the position you are applying." }, { "code": null, "e": 1555, "s": 1426, "text": "Finish with a statement saying why you are seeking a new job opportunity and why you are interested in the role you applied for." }, { "code": null, "e": 2495, "s": 1555, "text": "“Hi, I’m Dinh Tuan and I’m a backend engineer with over six years of experience specialising in designing and implementing high scale and high availability backend system. I started my career in SEA Group, one of the biggest tech company in South East Asia. During 5 years in SEA, I led the backend team implementing a gaming platform which serves 3 millions concurrent users and 500 thousands request per second at the peak time. I also helped to grow a team of 30 engineers in Vietnam after they acquired a Vietnamese startup in food delivery services. In early 2019, I joined Datarobot, a unicorn in Boston, United States. I work under code and architecture team to design and implement the feature to support multiple external compute clusters (including both Kubernetes and Hadoop).I’m interested in the software engineer position in Facebook because I would like to grow my technical skills further in a large scale social platform.”" }, { "code": null, "e": 2890, "s": 2495, "text": "You are usually given the opportunity to ask questions at the end of the interview. Skipping this part means missing out on the opportunity to learn about the nature of the work and the culture of the organisation. Moreover, a good question can also showcase your communication skills, demonstrate your interest in the role as well as make a good impression. Some of my favourite questions are:" }, { "code": null, "e": 3510, "s": 2890, "text": "1. What technology is the company/ your team currently using?2. What is your favourite thing about working for the company?3. How much say do developers have regarding the products?4. What qualities make a software engineer excel at this company?5. How flexible are the working hours?6. How will role performance be measured? What metric will role performance be measured with?7. How has your role changed since joining the company?8. What are the most challenging aspects of the job?9. What is the current team composition like?10. What resources does the company have for new hires to study its product and processes?" }, { "code": null, "e": 3622, "s": 3510, "text": "Do read the question carefully. If the question is not written, do repeat what you listen from the interviewer." }, { "code": null, "e": 3827, "s": 3622, "text": "Do work through the given examples or come up with some examples. It does not only help to ensure your understandings, but also allow you to pick up on patterns and generalisations to answer the question." }, { "code": null, "e": 3894, "s": 3827, "text": "Do clarify any assumptions you made such as input format or range." }, { "code": null, "e": 3949, "s": 3894, "text": "Do come up with the easiest and most obvious solution." }, { "code": null, "e": 4017, "s": 3949, "text": "Do look for improvements and try to come up with a better solution." }, { "code": null, "e": 4266, "s": 4017, "text": "Do think out loud, talk with your interviewer what you’re thinking. It keeps them engaged, allows them to understand your thought process as well as gives them a chance to point you in the right direction or stop you before you waste too much time." }, { "code": null, "e": 4300, "s": 4266, "text": "Do ask for hints if you’re stuck." }, { "code": null, "e": 4452, "s": 4300, "text": "Do work through some examples with your solution if it is not so trivial. You can also use whiteboard to work through your solution if it is necessary." }, { "code": null, "e": 4523, "s": 4452, "text": "Do state and explain the time and space complexity of your approaches." }, { "code": null, "e": 4679, "s": 4523, "text": "Don’t jump straight into writing code. You should only start coding after your interviewer understand what you’re going to do and give you the green light." }, { "code": null, "e": 4876, "s": 4679, "text": "Don’t keep silent for too long. If you are stuck, try to speak out the points making you confused. If you need to be quiet to think, just let the interviewer know (but keep it less than a minute)." }, { "code": null, "e": 4953, "s": 4876, "text": "Don’t ignore the information from the interviewer. Every piece is important." }, { "code": null, "e": 5009, "s": 4953, "text": "Don’t interrupt your interviewer when they are talking." }, { "code": null, "e": 5171, "s": 5009, "text": "Don’t get frustrated or discouraged. Take a deep breath and keep trying by walking through more samples, thinking about different algorithms and data structures." }, { "code": null, "e": 5279, "s": 5171, "text": "Don’t try to bluff it. If the interview hints something you are unfamiliar with, just admit it and move on." }, { "code": null, "e": 5322, "s": 5279, "text": "Do explain what you are writing or typing." }, { "code": null, "e": 5479, "s": 5322, "text": "Do follow the good coding style (such as using descriptive variable names) and structure your codes well (with functions and classes if they are necessary)." }, { "code": null, "e": 5579, "s": 5479, "text": "Do speak out your understanding about the algorithm, data structures or built-in functions you use." }, { "code": null, "e": 5783, "s": 5579, "text": "Do ask for the permission to use the built-in functions or skip some input checking. They may allow you to get away the implementation of some trivial functions or get back later if there is enough time." }, { "code": null, "e": 5963, "s": 5783, "text": "Do pay attention to your hand-writing if you are required to write on the whiteboard. You need to ensure it readable and well-organised (especially space between words and lines)." }, { "code": null, "e": 6105, "s": 5963, "text": "Don’t write pseudo code. Although you don’t need worry too much about the syntax, you are expected to deliver bug-free production-ready code." }, { "code": null, "e": 6137, "s": 6105, "text": "Don’t keep silent for too long." }, { "code": null, "e": 6210, "s": 6137, "text": "Do think about how you will test your code, list down corner test cases." }, { "code": null, "e": 6277, "s": 6210, "text": "Do run through your code with your interviewer for the test cases." }, { "code": null, "e": 6352, "s": 6277, "text": "Do fix any bugs that comes up when scanning your code with the test cases." }, { "code": null, "e": 6399, "s": 6352, "text": "Do look out for places where you can refactor." }, { "code": null, "e": 6474, "s": 6399, "text": "Do evaluate the time complexity and space complexity of your written code." }, { "code": null, "e": 6546, "s": 6474, "text": "Do suggest any better solution if it is existed and more time is given." }, { "code": null, "e": 6705, "s": 6546, "text": "Don’t argue with the interviewer. As the interviewer is familiar with the question, they are unlikely wrong. Take their feedback and think about it carefully." }, { "code": null, "e": 6814, "s": 6705, "text": "Do ask the questions to understand the work and company culture if the interview gives you that opportunity." }, { "code": null, "e": 6855, "s": 6814, "text": "Do thank the interviewer for their time." }, { "code": null, "e": 6908, "s": 6855, "text": "Don’t ask too many questions and try to end on time." }, { "code": null, "e": 6955, "s": 6908, "text": "Don’t asking about your interview performance." }, { "code": null, "e": 7021, "s": 6955, "text": "Don’t continue discussing about the coding problem as it is over." }, { "code": null, "e": 7033, "s": 7021, "text": "References:" }, { "code": null, "e": 7088, "s": 7033, "text": "Crack the coding interviewTechnical interview handbook" }, { "code": null, "e": 7115, "s": 7088, "text": "Crack the coding interview" } ]
Bootstrap 4 .justify-content-* class
To align flex items, use the justify-content-* class. Use any of the following to align flex items at the start, end, around, and between. justify-content-start – Align Flex items at the start justify-content-end - Align Flex items at the end justify-content-around – Align flex items around on different screen sizes justify-content-between - Alex flex items in between on difference screen sizes Let us see an example to set the flex items at the start − <div class="d-flex justify-content-start bg-primary mb-5"> <div class="p-2 bg-danger">RANK 1</div> <div class="p-2 bg-secondary">RANK 2</div> <div class="p-2 bg-warning">RANK3</div> </div> The following is the example to implement the justify-content-* class − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container mt-3"> <div class="d-flex justify-content-start bg-primary mb-5"> <div class="p-2 bg-danger">RANK 1</div> <div class="p-2 bg-secondary">RANK 2</div> <div class="p-2 bg-warning">RANK3</div> </div> <div class="d-flex justify-content-end bg-info mb-5"> <div class="p-2 bg-danger">RANK 1</div> <div class="p-2 bg-primary">RANK 2</div> <div class="p-2 bg-warning">RANK 3</div> </div> <div class="d-flex justify-content-around bg-warning mb-5"> <div class="p-2 bg-danger">RANK 1</div> <div class="p-2 bg-info">RANK 2</div> <div class="p-2 bg-secondary">RANK 3</div> </div> </div> </body> </html>
[ { "code": null, "e": 1116, "s": 1062, "text": "To align flex items, use the justify-content-* class." }, { "code": null, "e": 1201, "s": 1116, "text": "Use any of the following to align flex items at the start, end, around, and between." }, { "code": null, "e": 1463, "s": 1201, "text": "justify-content-start – Align Flex items at the start\njustify-content-end - Align Flex items at the end\njustify-content-around – Align flex items around on different screen sizes\njustify-content-between - Alex flex items in between on difference screen sizes" }, { "code": null, "e": 1522, "s": 1463, "text": "Let us see an example to set the flex items at the start −" }, { "code": null, "e": 1717, "s": 1522, "text": "<div class=\"d-flex justify-content-start bg-primary mb-5\">\n <div class=\"p-2 bg-danger\">RANK 1</div>\n <div class=\"p-2 bg-secondary\">RANK 2</div>\n <div class=\"p-2 bg-warning\">RANK3</div>\n</div>" }, { "code": null, "e": 1789, "s": 1717, "text": "The following is the example to implement the justify-content-* class −" }, { "code": null, "e": 1799, "s": 1789, "text": "Live Demo" }, { "code": null, "e": 2938, "s": 1799, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n</head>\n\n<body>\n\n<div class=\"container mt-3\">\n <div class=\"d-flex justify-content-start bg-primary mb-5\">\n <div class=\"p-2 bg-danger\">RANK 1</div>\n <div class=\"p-2 bg-secondary\">RANK 2</div>\n <div class=\"p-2 bg-warning\">RANK3</div>\n </div>\n <div class=\"d-flex justify-content-end bg-info mb-5\">\n <div class=\"p-2 bg-danger\">RANK 1</div>\n <div class=\"p-2 bg-primary\">RANK 2</div>\n <div class=\"p-2 bg-warning\">RANK 3</div>\n </div>\n <div class=\"d-flex justify-content-around bg-warning mb-5\">\n <div class=\"p-2 bg-danger\">RANK 1</div>\n <div class=\"p-2 bg-info\">RANK 2</div>\n <div class=\"p-2 bg-secondary\">RANK 3</div>\n </div>\n</div>\n\n</body>\n</html>" } ]
YAML - Full Length Example
The following full-length example specifies the construct of YAML which includes symbols and various representations which will be helpful while converting or processing them in JSON format. These attributes are also called as key names in JSON documents. These notations are created for security purposes. The above YAML format represents various attributes of defaults, adapter, and host with various other attributes. YAML also keeps a log of every file generated which maintains a track of error messages generated. On converting the specified YAML file in JSON format we get a desired output as mentioned below − defaults: &defaults adapter: postgres host: localhost development: database: myapp_development <<: *defaults test: database: myapp_test <<: *defaults Let’s convert the YAML to JSON format and check on the output. { "defaults": { "adapter": "postgres", "host": "localhost" }, "development": { "database": "myapp_development", "adapter": "postgres", "host": "localhost" }, "test": { "database": "myapp_test", "adapter": "postgres", "host": "localhost" } } The defaults key with a prefix of “ <<: *” is included as and when required with no need to write the same code snippet repeatedly. 33 Lectures 44 mins Tarun Telang Print Add Notes Bookmark this page
[ { "code": null, "e": 2356, "s": 2048, "text": "The following full-length example specifies the construct of YAML which includes symbols and various representations which will be helpful while converting or processing them in JSON format. These attributes are also called as key names in JSON documents. These notations are created for security purposes. " }, { "code": null, "e": 2667, "s": 2356, "text": "The above YAML format represents various attributes of defaults, adapter, and host with various other attributes. YAML also keeps a log of every file generated which maintains a track of error messages generated. On converting the specified YAML file in JSON format we get a desired output as mentioned below −" }, { "code": null, "e": 2842, "s": 2667, "text": "defaults: &defaults\n adapter: postgres\n host: localhost\n\ndevelopment:\n database: myapp_development\n <<: *defaults\n\ntest:\n database: myapp_test\n <<: *defaults" }, { "code": null, "e": 2905, "s": 2842, "text": "Let’s convert the YAML to JSON format and check on the output." }, { "code": null, "e": 3212, "s": 2905, "text": "{\n \"defaults\": {\n \"adapter\": \"postgres\",\n \"host\": \"localhost\"\n },\n \"development\": {\n \"database\": \"myapp_development\",\n \"adapter\": \"postgres\",\n \"host\": \"localhost\"\n },\n \"test\": {\n \"database\": \"myapp_test\",\n \"adapter\": \"postgres\",\n \"host\": \"localhost\"\n }\n}" }, { "code": null, "e": 3344, "s": 3212, "text": "The defaults key with a prefix of “ <<: *” is included as and when required with no need to write the same code snippet repeatedly." }, { "code": null, "e": 3376, "s": 3344, "text": "\n 33 Lectures \n 44 mins\n" }, { "code": null, "e": 3390, "s": 3376, "text": " Tarun Telang" }, { "code": null, "e": 3397, "s": 3390, "text": " Print" }, { "code": null, "e": 3408, "s": 3397, "text": " Add Notes" } ]
Shuffle elements of ArrayList with Java Collections
In order to shuffle elements of ArrayList with Java Collections, we use the Collections.shuffle() method. The java.util.Collections.shuffle() method randomly permutes the list using a default source of randomness. Declaration −The java.util.Collections.shuffle() method is declared as follows − public static void shuffle(List <?> list) Let us see a program to shuffle elements of ArrayList with Java Collections − Live Demo import java.util.*; public class Example { public static void main (String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(7); list.add(8); list.add(3); list.add(9); System.out.println("Original list : " + list); Collections.shuffle(list); // shuffling the list System.out.println("Shuffled list : " + list); } } Original list : [1, 2, 7, 8, 3, 9] Shuffled list : [3, 8, 7, 9, 1, 2]
[ { "code": null, "e": 1276, "s": 1062, "text": "In order to shuffle elements of ArrayList with Java Collections, we use the Collections.shuffle() method. The java.util.Collections.shuffle() method randomly permutes the list using a default source of randomness." }, { "code": null, "e": 1357, "s": 1276, "text": "Declaration −The java.util.Collections.shuffle() method is declared as follows −" }, { "code": null, "e": 1399, "s": 1357, "text": "public static void shuffle(List <?> list)" }, { "code": null, "e": 1477, "s": 1399, "text": "Let us see a program to shuffle elements of ArrayList with Java Collections −" }, { "code": null, "e": 1488, "s": 1477, "text": " Live Demo" }, { "code": null, "e": 1916, "s": 1488, "text": "import java.util.*;\npublic class Example {\n public static void main (String[] args) {\n ArrayList<Integer> list = new ArrayList<Integer>();\n list.add(1);\n list.add(2);\n list.add(7);\n list.add(8);\n list.add(3);\n list.add(9);\n System.out.println(\"Original list : \" + list);\n Collections.shuffle(list); // shuffling the list\n System.out.println(\"Shuffled list : \" + list);\n }\n}" }, { "code": null, "e": 1986, "s": 1916, "text": "Original list : [1, 2, 7, 8, 3, 9]\nShuffled list : [3, 8, 7, 9, 1, 2]" } ]