title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to find the root mean square of a vector in R?
To find the root mean square of a vector we can find the mean of the squared values then take the square root of the resulting vector. This can be done in a single and very short line of code. For example, if we have a vector x and we want to find the root mean square of this vector then it can be done as sqrt(mean(x^2)). Live Demo x1<-c(1,2,3,4,5) sqrt(mean(x1^2)) [1] 3.316625 Live Demo x2<-1:100 x2 [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 [19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 [37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 [91] 91 92 93 94 95 96 97 98 99 100 sqrt(mean(x2^2)) [1] 58.16786 Live Demo x3<-sample(0:9,120,replace=TRUE) x3 [1] 4 5 9 8 6 0 9 1 8 7 8 4 6 8 7 8 1 4 8 7 5 9 9 5 8 2 5 4 6 0 8 3 2 5 3 8 2 [38] 6 5 3 1 1 0 5 4 1 5 3 4 4 5 1 8 9 7 3 5 6 5 5 3 0 6 6 8 6 0 3 0 0 0 5 1 7 [75] 0 9 2 7 6 2 7 4 8 2 4 6 6 5 5 8 9 7 8 4 8 8 3 6 2 4 7 4 8 3 1 8 1 7 1 7 6 [112] 6 7 1 4 8 6 4 0 6 sqrt(mean(x3^2)) [1] 5.640626 Live Demo x4<-sample(11:20,120,replace=TRUE) x4 [1] 18 16 17 14 13 16 18 19 11 16 14 19 12 20 16 17 11 18 14 12 16 15 20 11 13 [26] 20 19 15 19 19 11 15 13 12 18 19 16 13 17 11 18 16 16 17 16 20 14 15 16 12 [51] 18 14 15 17 18 13 17 19 19 20 11 11 18 17 20 20 15 13 16 13 16 15 16 15 16 [76] 18 14 12 18 19 19 20 20 11 15 15 17 14 16 20 13 13 12 13 13 16 11 12 18 17 [101] 20 13 19 15 19 17 13 17 19 19 18 18 18 16 13 11 16 16 11 11 sqrt(mean(x4^2)) [1] 15.93502 Live Demo x5<-sample(rnorm(5,2,1),50,replace=TRUE) x5 [1] 1.5721680 2.5216234 2.5216234 1.5721680 0.8281694 1.5721680 2.5216234 [8] 2.3785184 2.5216234 2.5216234 3.1067177 0.8281694 3.1067177 1.5721680 [15] 1.5721680 0.8281694 2.3785184 2.5216234 2.3785184 2.3785184 0.8281694 [22] 2.3785184 0.8281694 3.1067177 3.1067177 2.5216234 3.1067177 1.5721680 [29] 3.1067177 2.3785184 1.5721680 1.5721680 0.8281694 2.5216234 0.8281694 [36] 2.5216234 2.3785184 2.5216234 2.5216234 1.5721680 2.3785184 1.5721680 [43] 2.3785184 0.8281694 2.5216234 0.8281694 3.1067177 0.8281694 2.3785184 [50] 3.1067177 sqrt(mean(x5^2)) [1] 1.827244 Live Demo x6<-sample(rnorm(10,2,1),60,replace=TRUE) x6 [1] 1.982475 2.585083 1.367865 3.544445 1.583944 2.138464 2.140323 1.367865 [9] 2.138464 1.678815 1.982475 1.678815 2.138464 2.585083 1.982475 3.544445 [17] 3.544445 2.536136 1.982475 2.585083 2.138464 1.367865 3.544445 3.544445 [25] 1.719228 2.585083 1.678815 1.583944 1.719228 1.583944 1.719228 1.982475 [33] 1.982475 2.138464 1.367865 1.583944 2.140323 2.140323 3.544445 2.140323 [41] 2.585083 2.138464 1.583944 1.367865 2.585083 2.585083 2.585083 2.536136 [49] 2.585083 1.367865 1.583944 1.583944 1.583944 1.367865 2.140323 1.367865 [57] 1.719228 2.140323 2.536136 2.140323 sqrt(mean(x6^2)) [1] 1.797629 Live Demo x7<-sample(runif(10,1,5),60,replace=TRUE) x7 [1] 2.164599 3.212320 1.379224 2.737192 2.628849 3.212320 3.212320 2.265332 [9] 2.265332 3.212320 3.212320 1.379224 3.055564 2.265332 2.628849 1.229603 [17] 3.212320 1.379224 2.495832 2.737192 2.628849 2.164599 2.265332 2.628849 [25] 2.164599 2.164599 2.737192 4.357790 2.265332 2.737192 1.379224 2.164599 [33] 2.628849 3.055564 2.164599 4.357790 2.265332 1.379224 2.628849 3.212320 [41] 3.212320 2.495832 2.495832 2.164599 2.164599 2.737192 3.212320 2.495832 [49] 2.737192 2.495832 2.628849 2.737192 2.164599 3.055564 3.212320 3.055564 [57] 3.212320 3.212320 2.737192 2.265332 sqrt(mean(x7^2)) [1] 2.806502 Live Demo x8<-sample(rpois(10,5),150,replace=TRUE) x8 [1] 3 5 4 4 4 4 4 6 1 8 4 4 2 4 3 6 5 4 4 4 1 4 4 8 4 4 3 5 3 6 4 4 5 4 5 4 8 [38] 5 4 8 3 2 8 5 4 1 4 2 4 2 4 4 4 5 3 4 2 2 4 4 4 1 4 4 4 6 3 4 4 5 5 8 4 4 [75] 3 8 6 6 4 3 1 8 6 4 4 6 4 3 3 1 2 8 1 2 4 4 2 4 2 3 4 4 4 1 5 4 3 4 5 4 6 [112] 4 4 6 4 2 4 4 3 4 6 5 6 4 4 1 4 1 8 4 4 2 3 5 4 4 4 4 4 3 4 1 4 2 3 1 4 4 [149] 8 5 sqrt(mean(x8^2)) [1] 4.61158 Live Demo x9<-sample(rexp(5,0.5),50,replace=TRUE) x9 [1] 3.6783772 1.8969143 0.9681084 1.8969143 0.9681084 0.9956425 3.6783772 [8] 0.9681084 0.6168324 1.8969143 3.6783772 1.8969143 0.6168324 0.9956425 [15] 0.6168324 0.9681084 0.9956425 1.8969143 0.6168324 0.9681084 0.6168324 [22] 1.8969143 0.6168324 0.9681084 0.6168324 1.8969143 0.6168324 1.8969143 [29] 3.6783772 0.9681084 0.9956425 3.6783772 0.9956425 0.9956425 0.9956425 [36] 3.6783772 0.6168324 3.6783772 3.6783772 0.6168324 0.9681084 0.9681084 [43] 0.9681084 0.6168324 0.9681084 1.8969143 1.8969143 0.6168324 0.6168324 [50] 0.9681084 sqrt(mean(x9^2)) [1] 2.17257 Live Demo x10<-sample(round(runif(5,1,3),0),125,replace=TRUE) x10 [1] 3 3 3 2 2 3 3 3 2 3 2 3 3 2 2 3 2 2 3 2 2 2 3 3 3 2 3 3 2 2 2 3 3 2 2 3 3 [38] 3 3 3 2 2 3 3 3 2 3 3 3 3 2 3 2 3 3 3 3 2 3 2 3 3 2 2 3 3 3 3 2 2 3 3 3 2 [75] 3 2 2 2 3 2 3 3 3 3 3 2 2 2 2 2 2 3 2 3 3 3 3 3 2 3 2 2 3 3 2 2 2 2 3 3 3 [112] 3 3 2 2 3 3 2 3 3 3 3 2 3 3 sqrt(mean(x10^2)) [1] 2.275082
[ { "code": null, "e": 1386, "s": 1062, "text": "To find the root mean square of a vector we can find the mean of the squared values then take the square root of the resulting vector. This can be done in a single and very short line of code. For example, if we have a vector x and we want to find the root mean square of this vector then it can be done as sqrt(mean(x^2))." }, { "code": null, "e": 1397, "s": 1386, "text": " Live Demo" }, { "code": null, "e": 1431, "s": 1397, "text": "x1<-c(1,2,3,4,5)\nsqrt(mean(x1^2))" }, { "code": null, "e": 1444, "s": 1431, "text": "[1] 3.316625" }, { "code": null, "e": 1455, "s": 1444, "text": " Live Demo" }, { "code": null, "e": 1468, "s": 1455, "text": "x2<-1:100\nx2" }, { "code": null, "e": 1789, "s": 1468, "text": "[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18\n[19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36\n[37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54\n[55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72\n[73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90\n[91] 91 92 93 94 95 96 97 98 99 100" }, { "code": null, "e": 1806, "s": 1789, "text": "sqrt(mean(x2^2))" }, { "code": null, "e": 1819, "s": 1806, "text": "[1] 58.16786" }, { "code": null, "e": 1830, "s": 1819, "text": " Live Demo" }, { "code": null, "e": 1866, "s": 1830, "text": "x3<-sample(0:9,120,replace=TRUE)\nx3" }, { "code": null, "e": 2126, "s": 1866, "text": "[1] 4 5 9 8 6 0 9 1 8 7 8 4 6 8 7 8 1 4 8 7 5 9 9 5 8 2 5 4 6 0 8 3 2 5 3 8 2\n[38] 6 5 3 1 1 0 5 4 1 5 3 4 4 5 1 8 9 7 3 5 6 5 5 3 0 6 6 8 6 0 3 0 0 0 5 1 7\n[75] 0 9 2 7 6 2 7 4 8 2 4 6 6 5 5 8 9 7 8 4 8 8 3 6 2 4 7 4 8 3 1 8 1 7 1 7 6\n[112] 6 7 1 4 8 6 4 0 6" }, { "code": null, "e": 2143, "s": 2126, "text": "sqrt(mean(x3^2))" }, { "code": null, "e": 2156, "s": 2143, "text": "[1] 5.640626" }, { "code": null, "e": 2167, "s": 2156, "text": " Live Demo" }, { "code": null, "e": 2205, "s": 2167, "text": "x4<-sample(11:20,120,replace=TRUE)\nx4" }, { "code": null, "e": 2590, "s": 2205, "text": "[1] 18 16 17 14 13 16 18 19 11 16 14 19 12 20 16 17 11 18 14 12 16 15 20 11 13\n[26] 20 19 15 19 19 11 15 13 12 18 19 16 13 17 11 18 16 16 17 16 20 14 15 16 12\n[51] 18 14 15 17 18 13 17 19 19 20 11 11 18 17 20 20 15 13 16 13 16 15 16 15 16\n[76] 18 14 12 18 19 19 20 20 11 15 15 17 14 16 20 13 13 12 13 13 16 11 12 18 17\n[101] 20 13 19 15 19 17 13 17 19 19 18 18 18 16 13 11 16 16 11 11" }, { "code": null, "e": 2607, "s": 2590, "text": "sqrt(mean(x4^2))" }, { "code": null, "e": 2620, "s": 2607, "text": "[1] 15.93502" }, { "code": null, "e": 2631, "s": 2620, "text": " Live Demo" }, { "code": null, "e": 2675, "s": 2631, "text": "x5<-sample(rnorm(5,2,1),50,replace=TRUE) x5" }, { "code": null, "e": 3213, "s": 2675, "text": "[1] 1.5721680 2.5216234 2.5216234 1.5721680 0.8281694 1.5721680 2.5216234\n[8] 2.3785184 2.5216234 2.5216234 3.1067177 0.8281694 3.1067177 1.5721680\n[15] 1.5721680 0.8281694 2.3785184 2.5216234 2.3785184 2.3785184 0.8281694\n[22] 2.3785184 0.8281694 3.1067177 3.1067177 2.5216234 3.1067177 1.5721680\n[29] 3.1067177 2.3785184 1.5721680 1.5721680 0.8281694 2.5216234 0.8281694\n[36] 2.5216234 2.3785184 2.5216234 2.5216234 1.5721680 2.3785184 1.5721680\n[43] 2.3785184 0.8281694 2.5216234 0.8281694 3.1067177 0.8281694 2.3785184\n[50] 3.1067177" }, { "code": null, "e": 3230, "s": 3213, "text": "sqrt(mean(x5^2))" }, { "code": null, "e": 3243, "s": 3230, "text": "[1] 1.827244" }, { "code": null, "e": 3254, "s": 3243, "text": " Live Demo" }, { "code": null, "e": 3299, "s": 3254, "text": "x6<-sample(rnorm(10,2,1),60,replace=TRUE) x6" }, { "code": null, "e": 3877, "s": 3299, "text": "[1] 1.982475 2.585083 1.367865 3.544445 1.583944 2.138464 2.140323 1.367865\n[9] 2.138464 1.678815 1.982475 1.678815 2.138464 2.585083 1.982475 3.544445\n[17] 3.544445 2.536136 1.982475 2.585083 2.138464 1.367865 3.544445 3.544445\n[25] 1.719228 2.585083 1.678815 1.583944 1.719228 1.583944 1.719228 1.982475\n[33] 1.982475 2.138464 1.367865 1.583944 2.140323 2.140323 3.544445 2.140323\n[41] 2.585083 2.138464 1.583944 1.367865 2.585083 2.585083 2.585083 2.536136\n[49] 2.585083 1.367865 1.583944 1.583944 1.583944 1.367865 2.140323 1.367865\n[57] 1.719228 2.140323 2.536136 2.140323" }, { "code": null, "e": 3894, "s": 3877, "text": "sqrt(mean(x6^2))" }, { "code": null, "e": 3907, "s": 3894, "text": "[1] 1.797629" }, { "code": null, "e": 3918, "s": 3907, "text": " Live Demo" }, { "code": null, "e": 3963, "s": 3918, "text": "x7<-sample(runif(10,1,5),60,replace=TRUE) x7" }, { "code": null, "e": 4541, "s": 3963, "text": "[1] 2.164599 3.212320 1.379224 2.737192 2.628849 3.212320 3.212320 2.265332\n[9] 2.265332 3.212320 3.212320 1.379224 3.055564 2.265332 2.628849 1.229603\n[17] 3.212320 1.379224 2.495832 2.737192 2.628849 2.164599 2.265332 2.628849\n[25] 2.164599 2.164599 2.737192 4.357790 2.265332 2.737192 1.379224 2.164599\n[33] 2.628849 3.055564 2.164599 4.357790 2.265332 1.379224 2.628849 3.212320\n[41] 3.212320 2.495832 2.495832 2.164599 2.164599 2.737192 3.212320 2.495832\n[49] 2.737192 2.495832 2.628849 2.737192 2.164599 3.055564 3.212320 3.055564\n[57] 3.212320 3.212320 2.737192 2.265332" }, { "code": null, "e": 4558, "s": 4541, "text": "sqrt(mean(x7^2))" }, { "code": null, "e": 4571, "s": 4558, "text": "[1] 2.806502" }, { "code": null, "e": 4582, "s": 4571, "text": " Live Demo" }, { "code": null, "e": 4626, "s": 4582, "text": "x8<-sample(rpois(10,5),150,replace=TRUE)\nx8" }, { "code": null, "e": 4952, "s": 4626, "text": "[1] 3 5 4 4 4 4 4 6 1 8 4 4 2 4 3 6 5 4 4 4 1 4 4 8 4 4 3 5 3 6 4 4 5 4 5 4 8\n[38] 5 4 8 3 2 8 5 4 1 4 2 4 2 4 4 4 5 3 4 2 2 4 4 4 1 4 4 4 6 3 4 4 5 5 8 4 4\n[75] 3 8 6 6 4 3 1 8 6 4 4 6 4 3 3 1 2 8 1 2 4 4 2 4 2 3 4 4 4 1 5 4 3 4 5 4 6\n[112] 4 4 6 4 2 4 4 3 4 6 5 6 4 4 1 4 1 8 4 4 2 3 5 4 4 4 4 4 3 4 1 4 2 3 1 4 4\n[149] 8 5" }, { "code": null, "e": 4969, "s": 4952, "text": "sqrt(mean(x8^2))" }, { "code": null, "e": 4981, "s": 4969, "text": "[1] 4.61158" }, { "code": null, "e": 4992, "s": 4981, "text": " Live Demo" }, { "code": null, "e": 5035, "s": 4992, "text": "x9<-sample(rexp(5,0.5),50,replace=TRUE) x9" }, { "code": null, "e": 5573, "s": 5035, "text": "[1] 3.6783772 1.8969143 0.9681084 1.8969143 0.9681084 0.9956425 3.6783772\n[8] 0.9681084 0.6168324 1.8969143 3.6783772 1.8969143 0.6168324 0.9956425\n[15] 0.6168324 0.9681084 0.9956425 1.8969143 0.6168324 0.9681084 0.6168324\n[22] 1.8969143 0.6168324 0.9681084 0.6168324 1.8969143 0.6168324 1.8969143\n[29] 3.6783772 0.9681084 0.9956425 3.6783772 0.9956425 0.9956425 0.9956425\n[36] 3.6783772 0.6168324 3.6783772 3.6783772 0.6168324 0.9681084 0.9681084\n[43] 0.9681084 0.6168324 0.9681084 1.8969143 1.8969143 0.6168324 0.6168324\n[50] 0.9681084" }, { "code": null, "e": 5590, "s": 5573, "text": "sqrt(mean(x9^2))" }, { "code": null, "e": 5602, "s": 5590, "text": "[1] 2.17257" }, { "code": null, "e": 5613, "s": 5602, "text": " Live Demo" }, { "code": null, "e": 5669, "s": 5613, "text": "x10<-sample(round(runif(5,1,3),0),125,replace=TRUE)\nx10" }, { "code": null, "e": 5939, "s": 5669, "text": "[1] 3 3 3 2 2 3 3 3 2 3 2 3 3 2 2 3 2 2 3 2 2 2 3 3 3 2 3 3 2 2 2 3 3 2 2 3 3\n[38] 3 3 3 2 2 3 3 3 2 3 3 3 3 2 3 2 3 3 3 3 2 3 2 3 3 2 2 3 3 3 3 2 2 3 3 3 2\n[75] 3 2 2 2 3 2 3 3 3 3 3 2 2 2 2 2 2 3 2 3 3 3 3 3 2 3 2 2 3 3 2 2 2 2 3 3 3\n[112] 3 3 2 2 3 3 2 3 3 3 3 2 3 3" }, { "code": null, "e": 5957, "s": 5939, "text": "sqrt(mean(x10^2))" }, { "code": null, "e": 5970, "s": 5957, "text": "[1] 2.275082" } ]
Check if reversing a sub array make the array sorted - GeeksforGeeks
13 Apr, 2021 Given an array of distinct n integers. The task is to check whether reversing one sub-array make the array sorted or not. If the array is already sorted or by reversing a subarray once make it sorted, print β€œYes”, else print β€œNo”.Examples: Input : arr [] = {1, 2, 5, 4, 3} Output : Yes By reversing the subarray {5, 4, 3}, the array will be sorted. Input : arr [] = { 1, 2, 4, 5, 3 } Output : No Method 1 (Simple : O(n2) A simple solution is to consider every subarray one by one. Try reversing every subarray and check if reversing the subarray makes the whole array sorted. If yes, return true. If reversing any subarray doesn’t make the array sorted, then return false. Method 2 (Sorting : O(nlogn)): The idea is to compare the given array with the sorted array. Make a copy of the given array and sort it. Now, find the first index and last index which do not match with sorted array. If no such indices are found, print β€œYes”. Else check if the elements between the indices are in decreasing order.Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to check whether reversing a// sub array make the array sorted or not#include<bits/stdc++.h>using namespace std; // Return true, if reversing the subarray will// sort the array, else return false.bool checkReverse(int arr[], int n){ // Copying the array. int temp[n]; for (int i = 0; i < n; i++) temp[i] = arr[i]; // Sort the copied array. sort(temp, temp + n); // Finding the first mismatch. int front; for (front = 0; front < n; front++) if (temp[front] != arr[front]) break; // Finding the last mismatch. int back; for (back = n - 1; back >= 0; back--) if (temp[back] != arr[back]) break; // If whole array is sorted if (front >= back) return true; // Checking subarray is decreasing or not. do { front++; if (arr[front - 1] < arr[front]) return false; } while (front != back); return true;} // Driven Programint main(){ int arr[] = { 1, 2, 5, 4, 3 }; int n = sizeof(arr)/sizeof(arr[0]); checkReverse(arr, n)? (cout << "Yes" << endl): (cout << "No" << endl); return 0;} // Java program to check whether reversing a// sub array make the array sorted or not import java.util.Arrays; class GFG { // Return true, if reversing the subarray will// sort the array, else return false. static boolean checkReverse(int arr[], int n) { // Copying the array. int temp[] = new int[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } // Sort the copied array. Arrays.sort(temp); // Finding the first mismatch. int front; for (front = 0; front < n; front++) { if (temp[front] != arr[front]) { break; } } // Finding the last mismatch. int back; for (back = n - 1; back >= 0; back--) { if (temp[back] != arr[back]) { break; } } // If whole array is sorted if (front >= back) { return true; } // Checking subarray is decreasing or not. do { front++; if (arr[front - 1] < arr[front]) { return false; } } while (front != back); return true; } // Driven Program public static void main(String[] args) { int arr[] = {1, 2, 5, 4, 3}; int n = arr.length; if (checkReverse(arr, n)) { System.out.print("Yes"); } else { System.out.print("No"); } } }//This code contributed by 29AjayKumar # Python3 program to check whether# reversing a sub array make the# array sorted or not # Return true, if reversing the# subarray will sort the array,# else return false.def checkReverse(arr, n): # Copying the array temp = [0] * n for i in range(n): temp[i] = arr[i] # Sort the copied array. temp.sort() # Finding the first mismatch. for front in range(n): if temp[front] != arr[front]: break # Finding the last mismatch. for back in range(n - 1, -1, -1): if temp[back] != arr[back]: break #If whole array is sorted if front >= back: return True while front != back: front += 1 if arr[front - 1] < arr[front]: return False return True # Driver codearr = [1, 2, 5, 4, 3]n = len(arr)if checkReverse(arr, n) == True: print("Yes")else: print("No") # This code is contributed# by Shrikant13 // C# program to check whether reversing a// sub array make the array sorted or notusing System; class GFG{ // Return true, if reversing the// subarray will sort the array,// else return false.static bool checkReverse(int []arr, int n){ // Copying the array. int []temp = new int[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } // Sort the copied array. Array.Sort(temp); // Finding the first mismatch. int front; for (front = 0; front < n; front++) { if (temp[front] != arr[front]) { break; } } // Finding the last mismatch. int back; for (back = n - 1; back >= 0; back--) { if (temp[back] != arr[back]) { break; } } // If whole array is sorted if (front >= back) { return true; } // Checking subarray is decreasing // or not. do { front++; if (arr[front - 1] < arr[front]) { return false; } } while (front != back); return true;} // Driven Programpublic static void Main(){ int []arr = {1, 2, 5, 4, 3}; int n = arr.Length; if (checkReverse(arr, n)) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed// by PrinciRaj <?php// PHP program to check whether reversing a// sub array make the array sorted or not // Return true, if reversing the subarray// will sort the array, else return false.function checkReverse($arr, $n){ // Copying the array. $temp[$n] = array(); for ($i = 0; $i < $n; $i++) $temp[$i] = $arr[$i]; // Sort the copied array. sort($temp, 0); // Finding the first mismatch. $front; for ($front = 0; $front < $n; $front++) if ($temp[$front] != $arr[$front]) break; // Finding the last mismatch. $back; for ($back = $n - 1; $back >= 0; $back--) if ($temp[$back] != $arr[$back]) break; // If whole array is sorted if ($front >= $back) return true; // Checking subarray is decreasing or not. do { $front++; if ($arr[$front - 1] < $arr[$front]) return false; } while ($front != $back); return true;} // Driver Code$arr = array( 1, 2, 5, 4, 3 );$n = sizeof($arr); if(checkReverse($arr, $n)) echo "Yes" . "\n";else echo "No" . "\n"; // This code is contributed// by Akanksha Rai?> <script> // Javascript program to check whether reversing a// sub array make the array sorted or not // Return true, if reversing the subarray will// sort the array, else return false. function checkReverse(arr, n) { // Copying the array. let temp = []; for (let i = 0; i < n; i++) { temp[i] = arr[i]; } // Sort the copied array. temp.sort(); // Finding the first mismatch. let front; for (front = 0; front < n; front++) { if (temp[front] != arr[front]) { break; } } // Finding the last mismatch. let back; for (back = n - 1; back >= 0; back--) { if (temp[back] != arr[back]) { break; } } // If whole array is sorted if (front >= back) { return true; } // Checking subarray is decreasing or not. do { front++; if (arr[front - 1] < arr[front]) { return false; } } while (front != back); return true; } // Driver Code let arr = [1, 2, 5, 4, 3]; let n = arr.length; if (checkReverse(arr, n)) { document.write("Yes"); } else { document.write("No"); } </script> Output: Yes Time Complexity: O(nlogn). Method 3 (Linear : O(n)): Observe, answer will be β€œYes” when the array is sorted or when the array consist of three parts. First part is increasing subarray, then decreasing subarray and then again increasing subarray. So, we need to check that array contain increasing elements then some decreasing elements and then increasing elements. In all other case, answer will be β€œNo”.Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to check whether reversing a sub array// make the array sorted or not#include<bits/stdc++.h>using namespace std; // Return true, if reversing the subarray will sort t// he array, else return false.bool checkReverse(int arr[], int n){ if (n == 1) return true; // Find first increasing part int i; for (i=1; i < n && arr[i-1] < arr[i]; i++); if (i == n) return true; // Find reversed part int j = i; while (j < n && arr[j] < arr[j-1]) { if (i > 1 && arr[j] < arr[i-2]) return false; j++; } if (j == n) return true; // Find last increasing part int k = j; // To handle cases like {1,2,3,4,20,9,16,17} if (arr[k] < arr[i-1]) return false; while (k > 1 && k < n) { if (arr[k] < arr[k-1]) return false; k++; } return true;} // Driven Programint main(){ int arr[] = {1, 3, 4, 10, 9, 8}; int n = sizeof(arr)/sizeof(arr[0]); checkReverse(arr, n)? cout << "Yes" : cout << "No"; return 0;} // Java program to check whether reversing a sub array// make the array sorted or not class GFG { // Return true, if reversing the subarray will sort t// he array, else return false. static boolean checkReverse(int arr[], int n) { if (n == 1) { return true; } // Find first increasing part int i; for (i = 1; arr[i - 1] < arr[i] && i < n; i++); if (i == n) { return true; } // Find reversed part int j = i; while (j < n && arr[j] < arr[j - 1]) { if (i > 1 && arr[j] < arr[i - 2]) { return false; } j++; } if (j == n) { return true; } // Find last increasing part int k = j; // To handle cases like {1,2,3,4,20,9,16,17} if (arr[k] < arr[i - 1]) { return false; } while (k > 1 && k < n) { if (arr[k] < arr[k - 1]) { return false; } k++; } return true; } // Driven Program public static void main(String[] args) { int arr[] = {1, 3, 4, 10, 9, 8}; int n = arr.length; if (checkReverse(arr, n)) { System.out.print("Yes"); } else { System.out.print("No"); } } } // This code is contributed// by Rajput-Ji # Python3 program to check whether reversing# a sub array make the array sorted or notimport math as mt # Return True, if reversing the subarray# will sort the array, else return False.def checkReverse(arr, n): if (n == 1): return True # Find first increasing part i = 1 for i in range(1, n): if arr[i - 1] < arr[i] : if (i == n): return True else: break # Find reversed part j = i while (j < n and arr[j] < arr[j - 1]): if (i > 1 and arr[j] < arr[i - 2]): return False j += 1 if (j == n): return True # Find last increasing part k = j # To handle cases like 1,2,3,4,20,9,16,17 if (arr[k] < arr[i - 1]): return False while (k > 1 and k < n): if (arr[k] < arr[k - 1]): return False k += 1 return True # Driver Codearr = [ 1, 3, 4, 10, 9, 8]n = len(arr)if checkReverse(arr, n): print("Yes")else: print("No") # This code is contributed by# Mohit kumar 29 // C# program to check whether reversing a// sub array make the array sorted or not using System;public class GFG{ // Return true, if reversing the subarray will sort t// he array, else return false. static bool checkReverse(int []arr, int n) { if (n == 1) { return true; } // Find first increasing part int i; for (i = 1; arr[i - 1] < arr[i] && i < n; i++); if (i == n) { return true; } // Find reversed part int j = i; while (j < n && arr[j] < arr[j - 1]) { if (i > 1 && arr[j] < arr[i - 2]) { return false; } j++; } if (j == n) { return true; } // Find last increasing part int k = j; // To handle cases like {1,2,3,4,20,9,16,17} if (arr[k] < arr[i - 1]) { return false; } while (k > 1 && k < n) { if (arr[k] < arr[k - 1]) { return false; } k++; } return true; } // Driven Program public static void Main() { int []arr = {1, 3, 4, 10, 9, 8}; int n = arr.Length; if (checkReverse(arr, n)) { Console.Write("Yes"); } else { Console.Write("No"); } }}// This code is contributed// by 29AjayKumar <?php// PHP program to check whether reversing// a sub array make the array sorted or not // Return true, if reversing the subarray// will sort the array, else return false.function checkReverse($arr, $n){ if ($n == 1) return true; // Find first increasing part for ($i = 1; $i < $n && $arr[$i - 1] < $arr[$i]; $i++); if ($i == $n) return true; // Find reversed part $j = $i; while ($arr[$j] < $arr[$j - 1]) { if ($i > 1 && $arr[$j] < $arr[$i - 2]) return false; $j++; } if ($j == $n) return true; // Find last increasing part $k = $j; // To handle cases like {1,2,3,4,20,9,16,17} if ($arr[$k] < $arr[$i - 1]) return false; while ($k > 1 && $k < $n) { if ($arr[$k] < $arr[$k - 1]) return false; $k++; } return true;} // Driver Code$arr = array(1, 3, 4, 10, 9, 8);$n = sizeof($arr);if(checkReverse($arr, $n)) echo "Yes";else echo "No"; // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // Javascript program to check whether reversing a sub array// make the array sorted or not // Return true, if reversing the subarray will sort t// he array, else return false.function checkReverse( arr, n){ if (n == 1) return true; // Find first increasing part let i; for (i=1; i < n && arr[i-1] < arr[i]; i++); if (i == n) return true; // Find reversed part let j = i; while (j < n && arr[j] < arr[j-1]) { if (i > 1 && arr[j] < arr[i-2]) return false; j++; } if (j == n) return true; // Find last increasing part let k = j; // To handle cases like {1,2,3,4,20,9,16,17} if (arr[k] < arr[i-1]) return false; while (k > 1 && k < n) { if (arr[k] < arr[k-1]) return false; k++; } return true;} // Driver program let arr = [1, 3, 4, 10, 9, 8]; let n = arr.length; if (checkReverse(arr, n)) { document.write("Yes"); } else { document.write("No"); } </script> Output: Yes Time Complexity: O(n).This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 Akanksha_Rai 29AjayKumar princiraj1992 Rajput-Ji mohit kumar 29 nikhilaggarwal3 code_hunt jana_sayantan Searching Sorting Searching Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Given an array of size n and a number k, find all elements that appear more than n/k times Program to find largest element in an array k largest(or smallest) elements in an array Search an element in a sorted and rotated array Median of two sorted arrays of different sizes
[ { "code": null, "e": 24891, "s": 24863, "text": "\n13 Apr, 2021" }, { "code": null, "e": 25133, "s": 24891, "text": "Given an array of distinct n integers. The task is to check whether reversing one sub-array make the array sorted or not. If the array is already sorted or by reversing a subarray once make it sorted, print β€œYes”, else print β€œNo”.Examples: " }, { "code": null, "e": 25291, "s": 25133, "text": "Input : arr [] = {1, 2, 5, 4, 3}\nOutput : Yes\nBy reversing the subarray {5, 4, 3}, \nthe array will be sorted.\n\nInput : arr [] = { 1, 2, 4, 5, 3 }\nOutput : No" }, { "code": null, "e": 25949, "s": 25293, "text": "Method 1 (Simple : O(n2) A simple solution is to consider every subarray one by one. Try reversing every subarray and check if reversing the subarray makes the whole array sorted. If yes, return true. If reversing any subarray doesn’t make the array sorted, then return false. Method 2 (Sorting : O(nlogn)): The idea is to compare the given array with the sorted array. Make a copy of the given array and sort it. Now, find the first index and last index which do not match with sorted array. If no such indices are found, print β€œYes”. Else check if the elements between the indices are in decreasing order.Below is the implementation of above approach: " }, { "code": null, "e": 25953, "s": 25949, "text": "C++" }, { "code": null, "e": 25958, "s": 25953, "text": "Java" }, { "code": null, "e": 25966, "s": 25958, "text": "Python3" }, { "code": null, "e": 25969, "s": 25966, "text": "C#" }, { "code": null, "e": 25973, "s": 25969, "text": "PHP" }, { "code": null, "e": 25984, "s": 25973, "text": "Javascript" }, { "code": "// C++ program to check whether reversing a// sub array make the array sorted or not#include<bits/stdc++.h>using namespace std; // Return true, if reversing the subarray will// sort the array, else return false.bool checkReverse(int arr[], int n){ // Copying the array. int temp[n]; for (int i = 0; i < n; i++) temp[i] = arr[i]; // Sort the copied array. sort(temp, temp + n); // Finding the first mismatch. int front; for (front = 0; front < n; front++) if (temp[front] != arr[front]) break; // Finding the last mismatch. int back; for (back = n - 1; back >= 0; back--) if (temp[back] != arr[back]) break; // If whole array is sorted if (front >= back) return true; // Checking subarray is decreasing or not. do { front++; if (arr[front - 1] < arr[front]) return false; } while (front != back); return true;} // Driven Programint main(){ int arr[] = { 1, 2, 5, 4, 3 }; int n = sizeof(arr)/sizeof(arr[0]); checkReverse(arr, n)? (cout << \"Yes\" << endl): (cout << \"No\" << endl); return 0;}", "e": 27145, "s": 25984, "text": null }, { "code": "// Java program to check whether reversing a// sub array make the array sorted or not import java.util.Arrays; class GFG { // Return true, if reversing the subarray will// sort the array, else return false. static boolean checkReverse(int arr[], int n) { // Copying the array. int temp[] = new int[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } // Sort the copied array. Arrays.sort(temp); // Finding the first mismatch. int front; for (front = 0; front < n; front++) { if (temp[front] != arr[front]) { break; } } // Finding the last mismatch. int back; for (back = n - 1; back >= 0; back--) { if (temp[back] != arr[back]) { break; } } // If whole array is sorted if (front >= back) { return true; } // Checking subarray is decreasing or not. do { front++; if (arr[front - 1] < arr[front]) { return false; } } while (front != back); return true; } // Driven Program public static void main(String[] args) { int arr[] = {1, 2, 5, 4, 3}; int n = arr.length; if (checkReverse(arr, n)) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); } } }//This code contributed by 29AjayKumar", "e": 28606, "s": 27145, "text": null }, { "code": "# Python3 program to check whether# reversing a sub array make the# array sorted or not # Return true, if reversing the# subarray will sort the array,# else return false.def checkReverse(arr, n): # Copying the array temp = [0] * n for i in range(n): temp[i] = arr[i] # Sort the copied array. temp.sort() # Finding the first mismatch. for front in range(n): if temp[front] != arr[front]: break # Finding the last mismatch. for back in range(n - 1, -1, -1): if temp[back] != arr[back]: break #If whole array is sorted if front >= back: return True while front != back: front += 1 if arr[front - 1] < arr[front]: return False return True # Driver codearr = [1, 2, 5, 4, 3]n = len(arr)if checkReverse(arr, n) == True: print(\"Yes\")else: print(\"No\") # This code is contributed# by Shrikant13", "e": 29517, "s": 28606, "text": null }, { "code": "// C# program to check whether reversing a// sub array make the array sorted or notusing System; class GFG{ // Return true, if reversing the// subarray will sort the array,// else return false.static bool checkReverse(int []arr, int n){ // Copying the array. int []temp = new int[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } // Sort the copied array. Array.Sort(temp); // Finding the first mismatch. int front; for (front = 0; front < n; front++) { if (temp[front] != arr[front]) { break; } } // Finding the last mismatch. int back; for (back = n - 1; back >= 0; back--) { if (temp[back] != arr[back]) { break; } } // If whole array is sorted if (front >= back) { return true; } // Checking subarray is decreasing // or not. do { front++; if (arr[front - 1] < arr[front]) { return false; } } while (front != back); return true;} // Driven Programpublic static void Main(){ int []arr = {1, 2, 5, 4, 3}; int n = arr.Length; if (checkReverse(arr, n)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed// by PrinciRaj", "e": 30818, "s": 29517, "text": null }, { "code": "<?php// PHP program to check whether reversing a// sub array make the array sorted or not // Return true, if reversing the subarray// will sort the array, else return false.function checkReverse($arr, $n){ // Copying the array. $temp[$n] = array(); for ($i = 0; $i < $n; $i++) $temp[$i] = $arr[$i]; // Sort the copied array. sort($temp, 0); // Finding the first mismatch. $front; for ($front = 0; $front < $n; $front++) if ($temp[$front] != $arr[$front]) break; // Finding the last mismatch. $back; for ($back = $n - 1; $back >= 0; $back--) if ($temp[$back] != $arr[$back]) break; // If whole array is sorted if ($front >= $back) return true; // Checking subarray is decreasing or not. do { $front++; if ($arr[$front - 1] < $arr[$front]) return false; } while ($front != $back); return true;} // Driver Code$arr = array( 1, 2, 5, 4, 3 );$n = sizeof($arr); if(checkReverse($arr, $n)) echo \"Yes\" . \"\\n\";else echo \"No\" . \"\\n\"; // This code is contributed// by Akanksha Rai?>", "e": 31931, "s": 30818, "text": null }, { "code": "<script> // Javascript program to check whether reversing a// sub array make the array sorted or not // Return true, if reversing the subarray will// sort the array, else return false. function checkReverse(arr, n) { // Copying the array. let temp = []; for (let i = 0; i < n; i++) { temp[i] = arr[i]; } // Sort the copied array. temp.sort(); // Finding the first mismatch. let front; for (front = 0; front < n; front++) { if (temp[front] != arr[front]) { break; } } // Finding the last mismatch. let back; for (back = n - 1; back >= 0; back--) { if (temp[back] != arr[back]) { break; } } // If whole array is sorted if (front >= back) { return true; } // Checking subarray is decreasing or not. do { front++; if (arr[front - 1] < arr[front]) { return false; } } while (front != back); return true; } // Driver Code let arr = [1, 2, 5, 4, 3]; let n = arr.length; if (checkReverse(arr, n)) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script>", "e": 33222, "s": 31931, "text": null }, { "code": null, "e": 33231, "s": 33222, "text": "Output: " }, { "code": null, "e": 33235, "s": 33231, "text": "Yes" }, { "code": null, "e": 33689, "s": 33235, "text": "Time Complexity: O(nlogn). Method 3 (Linear : O(n)): Observe, answer will be β€œYes” when the array is sorted or when the array consist of three parts. First part is increasing subarray, then decreasing subarray and then again increasing subarray. So, we need to check that array contain increasing elements then some decreasing elements and then increasing elements. In all other case, answer will be β€œNo”.Below is the implementation of this approach: " }, { "code": null, "e": 33693, "s": 33689, "text": "C++" }, { "code": null, "e": 33698, "s": 33693, "text": "Java" }, { "code": null, "e": 33706, "s": 33698, "text": "Python3" }, { "code": null, "e": 33709, "s": 33706, "text": "C#" }, { "code": null, "e": 33713, "s": 33709, "text": "PHP" }, { "code": null, "e": 33724, "s": 33713, "text": "Javascript" }, { "code": "// C++ program to check whether reversing a sub array// make the array sorted or not#include<bits/stdc++.h>using namespace std; // Return true, if reversing the subarray will sort t// he array, else return false.bool checkReverse(int arr[], int n){ if (n == 1) return true; // Find first increasing part int i; for (i=1; i < n && arr[i-1] < arr[i]; i++); if (i == n) return true; // Find reversed part int j = i; while (j < n && arr[j] < arr[j-1]) { if (i > 1 && arr[j] < arr[i-2]) return false; j++; } if (j == n) return true; // Find last increasing part int k = j; // To handle cases like {1,2,3,4,20,9,16,17} if (arr[k] < arr[i-1]) return false; while (k > 1 && k < n) { if (arr[k] < arr[k-1]) return false; k++; } return true;} // Driven Programint main(){ int arr[] = {1, 3, 4, 10, 9, 8}; int n = sizeof(arr)/sizeof(arr[0]); checkReverse(arr, n)? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 34770, "s": 33724, "text": null }, { "code": "// Java program to check whether reversing a sub array// make the array sorted or not class GFG { // Return true, if reversing the subarray will sort t// he array, else return false. static boolean checkReverse(int arr[], int n) { if (n == 1) { return true; } // Find first increasing part int i; for (i = 1; arr[i - 1] < arr[i] && i < n; i++); if (i == n) { return true; } // Find reversed part int j = i; while (j < n && arr[j] < arr[j - 1]) { if (i > 1 && arr[j] < arr[i - 2]) { return false; } j++; } if (j == n) { return true; } // Find last increasing part int k = j; // To handle cases like {1,2,3,4,20,9,16,17} if (arr[k] < arr[i - 1]) { return false; } while (k > 1 && k < n) { if (arr[k] < arr[k - 1]) { return false; } k++; } return true; } // Driven Program public static void main(String[] args) { int arr[] = {1, 3, 4, 10, 9, 8}; int n = arr.length; if (checkReverse(arr, n)) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); } } } // This code is contributed// by Rajput-Ji", "e": 36133, "s": 34770, "text": null }, { "code": "# Python3 program to check whether reversing# a sub array make the array sorted or notimport math as mt # Return True, if reversing the subarray# will sort the array, else return False.def checkReverse(arr, n): if (n == 1): return True # Find first increasing part i = 1 for i in range(1, n): if arr[i - 1] < arr[i] : if (i == n): return True else: break # Find reversed part j = i while (j < n and arr[j] < arr[j - 1]): if (i > 1 and arr[j] < arr[i - 2]): return False j += 1 if (j == n): return True # Find last increasing part k = j # To handle cases like 1,2,3,4,20,9,16,17 if (arr[k] < arr[i - 1]): return False while (k > 1 and k < n): if (arr[k] < arr[k - 1]): return False k += 1 return True # Driver Codearr = [ 1, 3, 4, 10, 9, 8]n = len(arr)if checkReverse(arr, n): print(\"Yes\")else: print(\"No\") # This code is contributed by# Mohit kumar 29", "e": 37196, "s": 36133, "text": null }, { "code": "// C# program to check whether reversing a// sub array make the array sorted or not using System;public class GFG{ // Return true, if reversing the subarray will sort t// he array, else return false. static bool checkReverse(int []arr, int n) { if (n == 1) { return true; } // Find first increasing part int i; for (i = 1; arr[i - 1] < arr[i] && i < n; i++); if (i == n) { return true; } // Find reversed part int j = i; while (j < n && arr[j] < arr[j - 1]) { if (i > 1 && arr[j] < arr[i - 2]) { return false; } j++; } if (j == n) { return true; } // Find last increasing part int k = j; // To handle cases like {1,2,3,4,20,9,16,17} if (arr[k] < arr[i - 1]) { return false; } while (k > 1 && k < n) { if (arr[k] < arr[k - 1]) { return false; } k++; } return true; } // Driven Program public static void Main() { int []arr = {1, 3, 4, 10, 9, 8}; int n = arr.Length; if (checkReverse(arr, n)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); } }}// This code is contributed// by 29AjayKumar", "e": 38556, "s": 37196, "text": null }, { "code": "<?php// PHP program to check whether reversing// a sub array make the array sorted or not // Return true, if reversing the subarray// will sort the array, else return false.function checkReverse($arr, $n){ if ($n == 1) return true; // Find first increasing part for ($i = 1; $i < $n && $arr[$i - 1] < $arr[$i]; $i++); if ($i == $n) return true; // Find reversed part $j = $i; while ($arr[$j] < $arr[$j - 1]) { if ($i > 1 && $arr[$j] < $arr[$i - 2]) return false; $j++; } if ($j == $n) return true; // Find last increasing part $k = $j; // To handle cases like {1,2,3,4,20,9,16,17} if ($arr[$k] < $arr[$i - 1]) return false; while ($k > 1 && $k < $n) { if ($arr[$k] < $arr[$k - 1]) return false; $k++; } return true;} // Driver Code$arr = array(1, 3, 4, 10, 9, 8);$n = sizeof($arr);if(checkReverse($arr, $n)) echo \"Yes\";else echo \"No\"; // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 39606, "s": 38556, "text": null }, { "code": "<script> // Javascript program to check whether reversing a sub array// make the array sorted or not // Return true, if reversing the subarray will sort t// he array, else return false.function checkReverse( arr, n){ if (n == 1) return true; // Find first increasing part let i; for (i=1; i < n && arr[i-1] < arr[i]; i++); if (i == n) return true; // Find reversed part let j = i; while (j < n && arr[j] < arr[j-1]) { if (i > 1 && arr[j] < arr[i-2]) return false; j++; } if (j == n) return true; // Find last increasing part let k = j; // To handle cases like {1,2,3,4,20,9,16,17} if (arr[k] < arr[i-1]) return false; while (k > 1 && k < n) { if (arr[k] < arr[k-1]) return false; k++; } return true;} // Driver program let arr = [1, 3, 4, 10, 9, 8]; let n = arr.length; if (checkReverse(arr, n)) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script>", "e": 40689, "s": 39606, "text": null }, { "code": null, "e": 40698, "s": 40689, "text": "Output: " }, { "code": null, "e": 40702, "s": 40698, "text": "Yes" }, { "code": null, "e": 41149, "s": 40702, "text": "Time Complexity: O(n).This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41161, "s": 41149, "text": "shrikanth13" }, { "code": null, "e": 41174, "s": 41161, "text": "Akanksha_Rai" }, { "code": null, "e": 41186, "s": 41174, "text": "29AjayKumar" }, { "code": null, "e": 41200, "s": 41186, "text": "princiraj1992" }, { "code": null, "e": 41210, "s": 41200, "text": "Rajput-Ji" }, { "code": null, "e": 41225, "s": 41210, "text": "mohit kumar 29" }, { "code": null, "e": 41241, "s": 41225, "text": "nikhilaggarwal3" }, { "code": null, "e": 41251, "s": 41241, "text": "code_hunt" }, { "code": null, "e": 41265, "s": 41251, "text": "jana_sayantan" }, { "code": null, "e": 41275, "s": 41265, "text": "Searching" }, { "code": null, "e": 41283, "s": 41275, "text": "Sorting" }, { "code": null, "e": 41293, "s": 41283, "text": "Searching" }, { "code": null, "e": 41301, "s": 41293, "text": "Sorting" }, { "code": null, "e": 41399, "s": 41301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41408, "s": 41399, "text": "Comments" }, { "code": null, "e": 41421, "s": 41408, "text": "Old Comments" }, { "code": null, "e": 41512, "s": 41421, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 41556, "s": 41512, "text": "Program to find largest element in an array" }, { "code": null, "e": 41600, "s": 41556, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 41648, "s": 41600, "text": "Search an element in a sorted and rotated array" } ]
Product array puzzle | Practice | GeeksforGeeks
Given an array nums[] of size n, construct a Product Array P (of same size n) such that P[i] is equal to the product of all the elements of nums except nums[i]. Example 1: Input: n = 5 nums[] = {10, 3, 5, 6, 2} Output: 180 600 360 300 900 Explanation: For i=0, P[i] = 3*5*6*2 = 180. For i=1, P[i] = 10*5*6*2 = 600. For i=2, P[i] = 10*3*6*2 = 360. For i=3, P[i] = 10*3*5*2 = 300. For i=4, P[i] = 10*3*5*6 = 900. Example 2: Input: n = 2 nums[] = {12,0} Output: 0 12 Your Task: You do not have to read input. Your task is to complete the function productExceptSelf() that takes array nums[] and n as input parameters and returns a list of n integers denoting the product array P. If the array has only one element the returned list should should contains one value i.e {1} Note: Try to solve this problem without using the division operation. Expected Time Complexity: O(n) Expected Auxiliary Space: O(n) Constraints: 1 <= n <= 1000 0 <= numsi <= 200 Array may contain duplicates. +1 yuvrajranabtcse203 days ago c++ soln without using division operation Time Complexity: O(n)Auxiliary Space: O(n) //for n==1 if(n==1)return {1}; //for n==2 if(n==2)return {nums[1],nums[0]}; //mesure left value and right value long long int lefft=nums[0]; long long int rigght=nums[n-1]; vector<long long int> left; vector<long long int> right; for(int i=1;i<=n-1;i++){ left.push_back(lefft); lefft*=nums[i]; } for(int i=n-2;i>=0;i--){ right.push_back(rigght); rigght*=nums[i]; } vector<long long int> ans; ans.push_back(right[n-2]); for(int i=0;i<n-2;i++){ ans.push_back(left[i]*right[n-3-i]); } ans.push_back(left[n-2]); return ans; } 0 abhigyanpatek4 days ago Simple C++ Solution: I used only 1 array for right product, left product can be calculated during same traversal when ans is being stored. vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { vector<long long> right(n); right[n-1] = 1; for(int i = n-2; i >= 0; i--){ right[i] = right[i+1]*nums[i+1]; } vector<long long> res; long long left = 1; for(int i = 0; i<n; i++){ res.push_back(left * right[i]); left *= nums[i]; } return res; } 0 itsmemritu4 days ago vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { //code here vector<long long int>v; long long int sum=1; long long int sum1=1; int c=0; for(int i=0 ;i<n ;i++){ sum*=nums[i]; if(nums[i]!=0){ sum1*=nums[i]; } if(nums[i]==0) c++; } for(int i=0 ;i<n ;i++){ if(nums[i]==0){ if(c>=2){ v.push_back(0); } else v.push_back(sum1); } else v.push_back(sum/nums[i]); } return v; } 0 anmolbansal25 days ago public static long[] productExceptSelf(int nums[], int n) { // code here if(n<=1) return new long[]{1L}; long[] p=new long[n]; for(int i=0;i<n;i++){ long mul=1; for(int j=0;j<n;j++){ if(i!=j){ mul=mul*nums[j]; } } p[i]=mul; } return p;} 0 rahulgupta067896 days ago What is the issue with this approach can any body detect.... vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { //code here vector<long long int>product; long long int p=accumulate(nums.begin(),nums.end(),1,multiplies<int>()); for(int i=0;i<n;i++){ long long int a=p/nums[i]; product.push_back(a); } return product; } +1 badgujarsachin836 days ago vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { vector<long long int> v; long long int pro=1,zero=0; for(int i=0;i<n;i++){ if(nums[i]==0){ zero++; }else{ pro*=nums[i]; } } for(int i=0;i<n;i++){ if(zero==0){ v.push_back(pro/nums[i]); }else if(zero==1){ if(nums[i]==0){ v.push_back(pro); }else{ v.push_back(0); } }else{ v.push_back(0); } } return v; } -1 amarrajsmart1976 days ago vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { //code here vector<long long int> v; int count0=0; long long int pro=1; for(int i=0;i<n;i++) { if(nums[i]==0) { count0++; } else { pro=pro*nums[i]; } } for(int i=0;i<n;i++){ if(count0==0) { v.push_back(pro/nums[i]); } else if(count0==1) { if(nums[i]==0) v.push_back(pro); else { v.push_back(0); } } else { v.push_back(0); } } return v; } 0 debanshuswag1 week ago vector<long long int> v; for(int i=0;i<n;i++) { long long int a=1; for(int j=0;j<n;j++) { if(i!=j) a=a*nums[j]; } v.push_back(a); } return v; 0 anubhavjoria292 weeks ago class Solution { public static long[] productExceptSelf(int nums[], int n) { // code here long[] p=new long[n]; for(int i=0;i<n;i++){ long mul=1; for(int j=0;j<n;j++){ if(i!=j){ mul=mul*nums[j]; } } p[i]=mul; } return p; } } 0 geeky20092 weeks ago vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { //code here vector<long long int>v; for(int i=0;i<n;i++){ long long c=1; for(int j=0;j<n;j++){ if(j!=i){ c=c*nums[j]; } } v.push_back(c); } return v; } 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": 399, "s": 238, "text": "Given an array nums[] of size n, construct a Product Array P (of same size n) such that P[i] is equal to the product of all the elements of nums except nums[i]." }, { "code": null, "e": 412, "s": 401, "text": "Example 1:" }, { "code": null, "e": 653, "s": 412, "text": "Input:\nn = 5\nnums[] = {10, 3, 5, 6, 2}\nOutput:\n180 600 360 300 900\nExplanation: \nFor i=0, P[i] = 3*5*6*2 = 180.\nFor i=1, P[i] = 10*5*6*2 = 600.\nFor i=2, P[i] = 10*3*6*2 = 360.\nFor i=3, P[i] = 10*3*5*2 = 300.\nFor i=4, P[i] = 10*3*5*6 = 900.\n" }, { "code": null, "e": 664, "s": 653, "text": "Example 2:" }, { "code": null, "e": 708, "s": 664, "text": "Input:\nn = 2\nnums[] = {12,0}\nOutput:\n0 12\n\n" }, { "code": null, "e": 1086, "s": 708, "text": "Your Task:\nYou do not have to read input. Your task is to complete the function productExceptSelf() that takes array nums[] and n as input parameters and returns a list of n integers denoting the product array P. If the array has only one element the returned list should should contains one value i.e {1}\nNote: Try to solve this problem without using the division operation.\n " }, { "code": null, "e": 1150, "s": 1086, "text": "Expected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)\n " }, { "code": null, "e": 1226, "s": 1150, "text": "Constraints:\n1 <= n <= 1000\n0 <= numsi <= 200\nArray may contain duplicates." }, { "code": null, "e": 1229, "s": 1226, "text": "+1" }, { "code": null, "e": 1257, "s": 1229, "text": "yuvrajranabtcse203 days ago" }, { "code": null, "e": 1299, "s": 1257, "text": "c++ soln without using division operation" }, { "code": null, "e": 1342, "s": 1299, "text": "Time Complexity: O(n)Auxiliary Space: O(n)" }, { "code": null, "e": 1353, "s": 1342, "text": "//for n==1" }, { "code": null, "e": 1373, "s": 1353, "text": "if(n==1)return {1};" }, { "code": null, "e": 1384, "s": 1373, "text": "//for n==2" }, { "code": null, "e": 1986, "s": 1384, "text": "if(n==2)return {nums[1],nums[0]}; //mesure left value and right value long long int lefft=nums[0]; long long int rigght=nums[n-1]; vector<long long int> left; vector<long long int> right; for(int i=1;i<=n-1;i++){ left.push_back(lefft); lefft*=nums[i]; } for(int i=n-2;i>=0;i--){ right.push_back(rigght); rigght*=nums[i]; } vector<long long int> ans; ans.push_back(right[n-2]); for(int i=0;i<n-2;i++){ ans.push_back(left[i]*right[n-3-i]); } ans.push_back(left[n-2]); return ans; }" }, { "code": null, "e": 1988, "s": 1986, "text": "0" }, { "code": null, "e": 2012, "s": 1988, "text": "abhigyanpatek4 days ago" }, { "code": null, "e": 2033, "s": 2012, "text": "Simple C++ Solution:" }, { "code": null, "e": 2151, "s": 2033, "text": "I used only 1 array for right product, left product can be calculated during same traversal when ans is being stored." }, { "code": null, "e": 2561, "s": 2153, "text": "vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { vector<long long> right(n); right[n-1] = 1; for(int i = n-2; i >= 0; i--){ right[i] = right[i+1]*nums[i+1]; } vector<long long> res; long long left = 1; for(int i = 0; i<n; i++){ res.push_back(left * right[i]); left *= nums[i]; } return res; }" }, { "code": null, "e": 2563, "s": 2561, "text": "0" }, { "code": null, "e": 2584, "s": 2563, "text": "itsmemritu4 days ago" }, { "code": null, "e": 3230, "s": 2584, "text": "vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { //code here vector<long long int>v; long long int sum=1; long long int sum1=1; int c=0; for(int i=0 ;i<n ;i++){ sum*=nums[i]; if(nums[i]!=0){ sum1*=nums[i]; } if(nums[i]==0) c++; } for(int i=0 ;i<n ;i++){ if(nums[i]==0){ if(c>=2){ v.push_back(0); } else v.push_back(sum1); } else v.push_back(sum/nums[i]); } return v; }" }, { "code": null, "e": 3232, "s": 3230, "text": "0" }, { "code": null, "e": 3255, "s": 3232, "text": "anmolbansal25 days ago" }, { "code": null, "e": 3682, "s": 3255, "text": " public static long[] productExceptSelf(int nums[], int n) { // code here if(n<=1) return new long[]{1L}; long[] p=new long[n]; for(int i=0;i<n;i++){ long mul=1; for(int j=0;j<n;j++){ if(i!=j){ mul=mul*nums[j]; } } p[i]=mul; } return p;} " }, { "code": null, "e": 3684, "s": 3682, "text": "0" }, { "code": null, "e": 3710, "s": 3684, "text": "rahulgupta067896 days ago" }, { "code": null, "e": 3771, "s": 3710, "text": "What is the issue with this approach can any body detect...." }, { "code": null, "e": 4125, "s": 3773, "text": "vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { //code here vector<long long int>product; long long int p=accumulate(nums.begin(),nums.end(),1,multiplies<int>()); for(int i=0;i<n;i++){ long long int a=p/nums[i]; product.push_back(a); } return product; }" }, { "code": null, "e": 4128, "s": 4125, "text": "+1" }, { "code": null, "e": 4155, "s": 4128, "text": "badgujarsachin836 days ago" }, { "code": null, "e": 4849, "s": 4155, "text": " vector<long long int> productExceptSelf(vector<long long int>& nums, int n) {\n \n vector<long long int> v;\n long long int pro=1,zero=0;\n for(int i=0;i<n;i++){\n if(nums[i]==0){\n zero++;\n }else{\n pro*=nums[i];\n }\n }\n for(int i=0;i<n;i++){\n if(zero==0){\n v.push_back(pro/nums[i]);\n }else if(zero==1){\n if(nums[i]==0){\n v.push_back(pro);\n }else{\n v.push_back(0);\n }\n }else{\n v.push_back(0);\n }\n }\n return v;\n \n }" }, { "code": null, "e": 4852, "s": 4849, "text": "-1" }, { "code": null, "e": 4878, "s": 4852, "text": "amarrajsmart1976 days ago" }, { "code": null, "e": 5595, "s": 4878, "text": "vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { //code here vector<long long int> v; int count0=0; long long int pro=1; for(int i=0;i<n;i++) { if(nums[i]==0) { count0++; } else { pro=pro*nums[i]; } } for(int i=0;i<n;i++){ if(count0==0) { v.push_back(pro/nums[i]); } else if(count0==1) { if(nums[i]==0) v.push_back(pro); else { v.push_back(0); } } else { v.push_back(0); } } return v; }" }, { "code": null, "e": 5597, "s": 5595, "text": "0" }, { "code": null, "e": 5620, "s": 5597, "text": "debanshuswag1 week ago" }, { "code": null, "e": 5864, "s": 5620, "text": "vector<long long int> v; for(int i=0;i<n;i++) { long long int a=1; for(int j=0;j<n;j++) { if(i!=j) a=a*nums[j]; } v.push_back(a); } return v;" }, { "code": null, "e": 5866, "s": 5864, "text": "0" }, { "code": null, "e": 5892, "s": 5866, "text": "anubhavjoria292 weeks ago" }, { "code": null, "e": 6319, "s": 5892, "text": "class Solution \n{ \n\tpublic static long[] productExceptSelf(int nums[], int n) \n\t{ \n // code here\n long[] p=new long[n];\n for(int i=0;i<n;i++){\n long mul=1;\n for(int j=0;j<n;j++){\n \n if(i!=j){\n mul=mul*nums[j];\n \n \n }\n }\n p[i]=mul;\n \n }\n return p;\n\t} \n} \n" }, { "code": null, "e": 6321, "s": 6319, "text": "0" }, { "code": null, "e": 6342, "s": 6321, "text": "geeky20092 weeks ago" }, { "code": null, "e": 6711, "s": 6342, "text": "vector<long long int> productExceptSelf(vector<long long int>& nums, int n) { //code here vector<long long int>v; for(int i=0;i<n;i++){ long long c=1; for(int j=0;j<n;j++){ if(j!=i){ c=c*nums[j]; } } v.push_back(c); } return v; }" }, { "code": null, "e": 6857, "s": 6711, "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": 6893, "s": 6857, "text": " Login to access your submissions. " }, { "code": null, "e": 6903, "s": 6893, "text": "\nProblem\n" }, { "code": null, "e": 6913, "s": 6903, "text": "\nContest\n" }, { "code": null, "e": 6976, "s": 6913, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7124, "s": 6976, "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": 7332, "s": 7124, "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": 7438, "s": 7332, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Get number from user input and display in console with JavaScript
You can use # to get the value when user clicks the button using document.querySelector(β€œβ€); Following is the JavaScript code βˆ’ 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> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <div class="container container-fluid"> <p><strong> Example:</strong> choose a number between 1 to 100</p> <form> <div class="form-group"> <label for="number">Give a number:</label> <input id="inputNumber" value="" type="text" name="number" /> </form> <p id="output"></p> </div> <button class="btn btn-dark" id="choose" type="submit">Click Me</button> </body> <script> function example() { let btn = document.querySelector("#choose"); let randomNumber = Math.ceil(Math.random() * 100); btn.onclick = function() { let givenNumber = document.querySelector("#inputNumber").value; let valueInt = parseInt(givenNumber, 100); console.log(randomNumber, givenNumber); }; } example(); </script> </html> To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor. Add a value βˆ’ On clicking the button Click Me, the same is visible in Console βˆ’
[ { "code": null, "e": 1190, "s": 1062, "text": "You can use # to get the value when user clicks the button using document.querySelector(β€œβ€);\nFollowing is the JavaScript code βˆ’" }, { "code": null, "e": 1201, "s": 1190, "text": " Live Demo" }, { "code": null, "e": 2349, "s": 1201, "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<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<div class=\"container container-fluid\">\n<p><strong> Example:</strong> choose a number between 1 to 100</p>\n<form>\n<div class=\"form-group\">\n<label for=\"number\">Give a number:</label>\n<input id=\"inputNumber\" value=\"\" type=\"text\" name=\"number\" />\n</form>\n<p id=\"output\"></p>\n</div>\n<button class=\"btn btn-dark\" id=\"choose\" type=\"submit\">Click Me</button>\n</body>\n<script>\n function example() {\n let btn = document.querySelector(\"#choose\");\n let randomNumber = Math.ceil(Math.random() * 100);\n btn.onclick = function() {\n let givenNumber = document.querySelector(\"#inputNumber\").value;\n let valueInt = parseInt(givenNumber, 100);\n console.log(randomNumber, givenNumber);\n };\n }\n example();\n</script>\n</html>" }, { "code": null, "e": 2510, "s": 2349, "text": "To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor." }, { "code": null, "e": 2524, "s": 2510, "text": "Add a value βˆ’" }, { "code": null, "e": 2590, "s": 2524, "text": "On clicking the button Click Me, the same is visible in Console βˆ’" } ]
Using Random Forest to tell if you have a representative Validation Set | by Alessandro Kosciansky | Towards Data Science
When running a predictive model β€” be that during a Kaggle competition or the real world β€” you need a representative validation set to check whether the model you are training, generalises well β€” that is, the model can make good predictions on data it has never seen before. So what do I mean by β€˜representative’? Well, all it really means is that your training and validation data sets are similar, i.e. follow the same distributions or patterns. If that is not the case then you’re training your model on apples, but then try to predict on oranges. The result will be very poor predictions. You could do lots of Exploratory Data Analysis (EDA) and check that each feature behaves similar across both datasets. But that could be really time consuming. A neat and quick way of testing whether you have a representative or good validation set is to run a Random Forest Classifier. In this Kaggle kernel I did exactly that. I first prepared both training and validation data and then added an extra column β€˜train’, which takes the value of 1 when the data is training data and 0 when it is validation data. This is the target that the Random Forest Classifier is going to predict. # Create the new targettrain_set['train'] = 1validation_set['train'] = 0# Concatenate the two datasetstrain_validation = pd.concat([train_set, validation_set], axis=0) The next step is to get your indepdent (X) and dependent (y) features ready, set up the Random Forest Classifier, and run cross validation. I am using the metric ROC AUC, which is a common metric for classification tasks. If the metric is 1 then you’re predicting perfectly. If the score is 0.5 then you’re as good as the baseline, which is the score that you would get if you always predicted the most common outcome. If the score is below 0.5 then you’re doing something wrong. # Import the librariesfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import cross_val_score# Split up the dependent and independent variablesX = train_validation.drop('train', axis=1)y = train_validation['train']# Set up the modelrfc = RandomForestClassifier(n_estimators=10, random_state=1)# Run cross validationcv_results = cross_val_score(rfc, X, y, cv=5, scoring='roc_auc') Now, what do you think the ROC AUC should be if training and validation set behave the same way? ...That’s right, 0.5! If the score is 0.5 then it means that training and validation data are indistinguishable, which is what we want. Once we have run cross validation, let’s get the scores... And great news! The score is indeed 0.5. That means the Kaggle hosts have set up a representative validation set for us. Sometimes that’s not the case and this is a great quick way of checking this. In real life, however, you have to come up with a validation set yourself and this will hopefully come in handy to make sure that you set up a correct validation set. print(cv_results)print(np.mean(cv_results))[0.5000814 0.50310124 0.50416737 0.49976049 0.50078978]0.5015800562639847
[ { "code": null, "e": 446, "s": 172, "text": "When running a predictive model β€” be that during a Kaggle competition or the real world β€” you need a representative validation set to check whether the model you are training, generalises well β€” that is, the model can make good predictions on data it has never seen before." }, { "code": null, "e": 764, "s": 446, "text": "So what do I mean by β€˜representative’? Well, all it really means is that your training and validation data sets are similar, i.e. follow the same distributions or patterns. If that is not the case then you’re training your model on apples, but then try to predict on oranges. The result will be very poor predictions." }, { "code": null, "e": 1051, "s": 764, "text": "You could do lots of Exploratory Data Analysis (EDA) and check that each feature behaves similar across both datasets. But that could be really time consuming. A neat and quick way of testing whether you have a representative or good validation set is to run a Random Forest Classifier." }, { "code": null, "e": 1350, "s": 1051, "text": "In this Kaggle kernel I did exactly that. I first prepared both training and validation data and then added an extra column β€˜train’, which takes the value of 1 when the data is training data and 0 when it is validation data. This is the target that the Random Forest Classifier is going to predict." }, { "code": null, "e": 1518, "s": 1350, "text": "# Create the new targettrain_set['train'] = 1validation_set['train'] = 0# Concatenate the two datasetstrain_validation = pd.concat([train_set, validation_set], axis=0)" }, { "code": null, "e": 1658, "s": 1518, "text": "The next step is to get your indepdent (X) and dependent (y) features ready, set up the Random Forest Classifier, and run cross validation." }, { "code": null, "e": 1998, "s": 1658, "text": "I am using the metric ROC AUC, which is a common metric for classification tasks. If the metric is 1 then you’re predicting perfectly. If the score is 0.5 then you’re as good as the baseline, which is the score that you would get if you always predicted the most common outcome. If the score is below 0.5 then you’re doing something wrong." }, { "code": null, "e": 2409, "s": 1998, "text": "# Import the librariesfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import cross_val_score# Split up the dependent and independent variablesX = train_validation.drop('train', axis=1)y = train_validation['train']# Set up the modelrfc = RandomForestClassifier(n_estimators=10, random_state=1)# Run cross validationcv_results = cross_val_score(rfc, X, y, cv=5, scoring='roc_auc')" }, { "code": null, "e": 2642, "s": 2409, "text": "Now, what do you think the ROC AUC should be if training and validation set behave the same way? ...That’s right, 0.5! If the score is 0.5 then it means that training and validation data are indistinguishable, which is what we want." }, { "code": null, "e": 3067, "s": 2642, "text": "Once we have run cross validation, let’s get the scores... And great news! The score is indeed 0.5. That means the Kaggle hosts have set up a representative validation set for us. Sometimes that’s not the case and this is a great quick way of checking this. In real life, however, you have to come up with a validation set yourself and this will hopefully come in handy to make sure that you set up a correct validation set." } ]
Update data in one table from data in another table in MySQL?
For this, you can use UPDATE command along with JOIN. Let us create the first table βˆ’ mysql> create table demo54 βˆ’> ( βˆ’> firstName varchar(20), βˆ’> lastName varchar(20) βˆ’> ); Query OK, 0 rows affected (0.57 sec) Insert some records into the table with the help of insert command βˆ’ mysql> insert into demo54 values('John','Smith'); Query OK, 1 row affected (0.09 sec) mysql> insert into demo54 values('John','Smith'); Query OK, 1 row affected (0.09 sec) mysql> insert into demo54 values('David','Smith'); Query OK, 1 row affected (0.11 sec) Display records from the table using select statement βˆ’ mysql> select *from demo54; This will produce the following output βˆ’ +-----------+----------+ | firstName | lastName | +-----------+----------+ | John | Smith | | John | Smith | | David | Smith | +-----------+----------+ 3 rows in set (0.00 sec) Following is the query to create second table βˆ’ mysql> create table demo55 βˆ’> ( βˆ’> firstName varchar(20), βˆ’> lastName varchar(20) βˆ’> ); Query OK, 0 rows affected (1.93 sec) Insert some records into the table with the help of insert command βˆ’ mysql> insert into demo55 (firstName) values('John'); Query OK, 1 row affected (0.10 sec) mysql> insert into demo55 (firstName) values('David'); Query OK, 1 row affected (0.13 sec) mysql> insert into demo55 (firstName) values('Bob'); Query OK, 1 row affected (0.10 sec) Display records from the table using select statement βˆ’ mysql> select *from demo55; This will produce the following output βˆ’ +-----------+----------+ | firstName | lastName | +-----------+----------+ | John | NULL | | David | NULL | | Bob | NULL | +-----------+----------+ 3 rows in set (0.00 sec) Following is the query to update data in one table from another table. mysql> UPDATE demo55 tbl1 βˆ’> JOIN demo54 tbl2 ON tbl1.firstName = tbl2.firstName βˆ’> set tbl1.lastName = tbl2.lastName; Query OK, 2 rows affected (0.10 sec) Rows matched: 2 Changed: 2 Warnings: 0 Display records from the table using select statement βˆ’ mysql> select *from demo55; This will produce the following output βˆ’ +-----------+----------+ | firstName | lastName | +-----------+----------+ | John | Smith | | David | Smith | | Bob | NULL | +-----------+----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1116, "s": 1062, "text": "For this, you can use UPDATE command along with JOIN." }, { "code": null, "e": 1148, "s": 1116, "text": "Let us create the first table βˆ’" }, { "code": null, "e": 1273, "s": 1148, "text": "mysql> create table demo54\nβˆ’> (\nβˆ’> firstName varchar(20),\nβˆ’> lastName varchar(20)\nβˆ’> );\nQuery OK, 0 rows affected (0.57 sec)" }, { "code": null, "e": 1342, "s": 1273, "text": "Insert some records into the table with the help of insert command βˆ’" }, { "code": null, "e": 1603, "s": 1342, "text": "mysql> insert into demo54 values('John','Smith');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into demo54 values('John','Smith');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into demo54 values('David','Smith');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1659, "s": 1603, "text": "Display records from the table using select statement βˆ’" }, { "code": null, "e": 1687, "s": 1659, "text": "mysql> select *from demo54;" }, { "code": null, "e": 1728, "s": 1687, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 1928, "s": 1728, "text": "+-----------+----------+\n| firstName | lastName |\n+-----------+----------+\n| John | Smith |\n| John | Smith |\n| David | Smith |\n+-----------+----------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1976, "s": 1928, "text": "Following is the query to create second table βˆ’" }, { "code": null, "e": 2101, "s": 1976, "text": "mysql> create table demo55\nβˆ’> (\nβˆ’> firstName varchar(20),\nβˆ’> lastName varchar(20)\nβˆ’> );\nQuery OK, 0 rows affected (1.93 sec)" }, { "code": null, "e": 2170, "s": 2101, "text": "Insert some records into the table with the help of insert command βˆ’" }, { "code": null, "e": 2442, "s": 2170, "text": "mysql> insert into demo55 (firstName) values('John');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into demo55 (firstName) values('David');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into demo55 (firstName) values('Bob');\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 2498, "s": 2442, "text": "Display records from the table using select statement βˆ’" }, { "code": null, "e": 2526, "s": 2498, "text": "mysql> select *from demo55;" }, { "code": null, "e": 2567, "s": 2526, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2767, "s": 2567, "text": "+-----------+----------+\n| firstName | lastName |\n+-----------+----------+\n| John | NULL |\n| David | NULL |\n| Bob | NULL |\n+-----------+----------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2838, "s": 2767, "text": "Following is the query to update data in one table from another table." }, { "code": null, "e": 3033, "s": 2838, "text": "mysql> UPDATE demo55 tbl1\nβˆ’> JOIN demo54 tbl2 ON tbl1.firstName = tbl2.firstName\nβˆ’> set tbl1.lastName = tbl2.lastName;\nQuery OK, 2 rows affected (0.10 sec)\nRows matched: 2 Changed: 2 Warnings: 0" }, { "code": null, "e": 3089, "s": 3033, "text": "Display records from the table using select statement βˆ’" }, { "code": null, "e": 3117, "s": 3089, "text": "mysql> select *from demo55;" }, { "code": null, "e": 3158, "s": 3117, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 3358, "s": 3158, "text": "+-----------+----------+\n| firstName | lastName |\n+-----------+----------+\n| John | Smith |\n| David | Smith |\n| Bob | NULL |\n+-----------+----------+\n3 rows in set (0.00 sec)" } ]
PyQtGraph – Hide the Bar Graph - GeeksforGeeks
25 Sep, 2020 In this article we will see how we can hide the bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart. Hiding bar graph doesn’t mean that it will get deleted. It means that it will not get displayed on the plot window. We can create a plot window and bar graph with the help of commands given below # creating a pyqtgraph plot window window = pg.plot() # creating a bar graph of green color bargraph = pg.BarGraphItem(x=x, height=y1, width=0.6, brush='g') In order to do this we use hide method with the bar graph object Syntax : bargraph.hide() Argument : It takes no argument Return : It returns None Below is the implementation # importing QtGui to use QIconfrom PyQt5.QtGui import * from PyQt5.QtCore import Qt # importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np import time # creating a pyqtgraph plot windowwindow = pg.plot() # icon for plot windowicon = QIcon("logo.png") # setting icon to the plot windowwindow.setWindowIcon(icon) # setting window geometry# left = 100, top = 100# width = 600, height = 500window.setGeometry(100, 100, 600, 500) # title for the plot windowtitle = "GeeksforGeeks PyQtGraph" # setting window title to plot windowwindow.setWindowTitle(title) # create list for y-axisy1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axisx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6# with bar colors = greenbargraph = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window# adding bargraph item to the windowwindow.addItem(bargraph) # hiding the bargraphbargraph.hide() # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() Output : Python-gui Python-PyQt Python-PyQtGraph Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 24228, "s": 24200, "text": "\n25 Sep, 2020" }, { "code": null, "e": 25083, "s": 24228, "text": "In this article we will see how we can hide the bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart. Hiding bar graph doesn’t mean that it will get deleted. It means that it will not get displayed on the plot window." }, { "code": null, "e": 25163, "s": 25083, "text": "We can create a plot window and bar graph with the help of commands given below" }, { "code": null, "e": 25322, "s": 25163, "text": "# creating a pyqtgraph plot window\nwindow = pg.plot()\n\n# creating a bar graph of green color\nbargraph = pg.BarGraphItem(x=x, height=y1, width=0.6, brush='g')\n" }, { "code": null, "e": 25387, "s": 25322, "text": "In order to do this we use hide method with the bar graph object" }, { "code": null, "e": 25412, "s": 25387, "text": "Syntax : bargraph.hide()" }, { "code": null, "e": 25444, "s": 25412, "text": "Argument : It takes no argument" }, { "code": null, "e": 25469, "s": 25444, "text": "Return : It returns None" }, { "code": null, "e": 25497, "s": 25469, "text": "Below is the implementation" }, { "code": "# importing QtGui to use QIconfrom PyQt5.QtGui import * from PyQt5.QtCore import Qt # importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np import time # creating a pyqtgraph plot windowwindow = pg.plot() # icon for plot windowicon = QIcon(\"logo.png\") # setting icon to the plot windowwindow.setWindowIcon(icon) # setting window geometry# left = 100, top = 100# width = 600, height = 500window.setGeometry(100, 100, 600, 500) # title for the plot windowtitle = \"GeeksforGeeks PyQtGraph\" # setting window title to plot windowwindow.setWindowTitle(title) # create list for y-axisy1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axisx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6# with bar colors = greenbargraph = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window# adding bargraph item to the windowwindow.addItem(bargraph) # hiding the bargraphbargraph.hide() # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() ", "e": 26892, "s": 25497, "text": null }, { "code": null, "e": 26901, "s": 26892, "text": "Output :" }, { "code": null, "e": 26912, "s": 26901, "text": "Python-gui" }, { "code": null, "e": 26924, "s": 26912, "text": "Python-PyQt" }, { "code": null, "e": 26941, "s": 26924, "text": "Python-PyQtGraph" }, { "code": null, "e": 26948, "s": 26941, "text": "Python" }, { "code": null, "e": 27046, "s": 26948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27055, "s": 27046, "text": "Comments" }, { "code": null, "e": 27068, "s": 27055, "text": "Old Comments" }, { "code": null, "e": 27086, "s": 27068, "text": "Python Dictionary" }, { "code": null, "e": 27118, "s": 27086, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27153, "s": 27118, "text": "Read a file line by line in Python" }, { "code": null, "e": 27175, "s": 27153, "text": "Enumerate() in Python" }, { "code": null, "e": 27205, "s": 27175, "text": "Iterate over a list in Python" }, { "code": null, "e": 27247, "s": 27205, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27284, "s": 27247, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27310, "s": 27284, "text": "Python String | replace()" }, { "code": null, "e": 27354, "s": 27310, "text": "Reading and Writing to text files in Python" } ]
Cryptography with Python - Affine Cipher
Affine Cipher is the combination of Multiplicative Cipher and Caesar Cipher algorithm. The basic implementation of affine cipher is as shown in the image below βˆ’ In this chapter, we will implement affine cipher by creating its corresponding class that includes two basic functions for encryption and decryption. You can use the following code to implement an affine cipher βˆ’ class Affine(object): DIE = 128 KEY = (7, 3, 55) def __init__(self): pass def encryptChar(self, char): K1, K2, kI = self.KEY return chr((K1 * ord(char) + K2) % self.DIE) def encrypt(self, string): return "".join(map(self.encryptChar, string)) def decryptChar(self, char): K1, K2, KI = self.KEY return chr(KI * (ord(char) - K2) % self.DIE) def decrypt(self, string): return "".join(map(self.decryptChar, string)) affine = Affine() print affine.encrypt('Affine Cipher') print affine.decrypt('*18?FMT') You can observe the following output when you implement an affine cipher βˆ’ The output displays the encrypted message for the plain text message Affine Cipher and decrypted message for the message sent as input abcdefg. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2454, "s": 2292, "text": "Affine Cipher is the combination of Multiplicative Cipher and Caesar Cipher algorithm. The basic implementation of affine cipher is as shown in the image below βˆ’" }, { "code": null, "e": 2604, "s": 2454, "text": "In this chapter, we will implement affine cipher by creating its corresponding class that includes two basic functions for encryption and decryption." }, { "code": null, "e": 2667, "s": 2604, "text": "You can use the following code to implement an affine cipher βˆ’" }, { "code": null, "e": 3243, "s": 2667, "text": "class Affine(object):\n DIE = 128\n KEY = (7, 3, 55)\n def __init__(self):\n pass\n def encryptChar(self, char):\n K1, K2, kI = self.KEY\n return chr((K1 * ord(char) + K2) % self.DIE)\n\t\t\n def encrypt(self, string):\n return \"\".join(map(self.encryptChar, string))\n \n def decryptChar(self, char):\n K1, K2, KI = self.KEY\n return chr(KI * (ord(char) - K2) % self.DIE)\n \n def decrypt(self, string):\n return \"\".join(map(self.decryptChar, string))\n\t\taffine = Affine()\nprint affine.encrypt('Affine Cipher')\nprint affine.decrypt('*18?FMT')" }, { "code": null, "e": 3318, "s": 3243, "text": "You can observe the following output when you implement an affine cipher βˆ’" }, { "code": null, "e": 3462, "s": 3318, "text": "The output displays the encrypted message for the plain text message Affine Cipher and decrypted message for the message sent as input abcdefg." }, { "code": null, "e": 3495, "s": 3462, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 3511, "s": 3495, "text": " Total Seminars" }, { "code": null, "e": 3544, "s": 3511, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 3567, "s": 3544, "text": " Stone River ELearning" }, { "code": null, "e": 3574, "s": 3567, "text": " Print" }, { "code": null, "e": 3585, "s": 3574, "text": " Add Notes" } ]
Check if a given year is leap year in PL/SQL
Here we will see how to check given year is leap year or not, using PL/SQL. In PL/SQL code, some group of commands are arranged within a block of related declaration of statements. The leap year checking algorithm is like below. isLeapYear(year): begin if year is divisible by 4 and not divisible by 100, then it is leap year else if the number is divisible by 400, then it is leap year else it is not leap year end DECLARE year NUMBER := 2012; BEGIN IF MOD(year, 4)=0 AND MOD(year, 100)!=0 OR MOD(year, 400)=0 THEN dbms_output.Put_line(year || ' is leap year '); ELSE dbms_output.Put_line(year || ' is not leap year.'); END IF; END; 2012 is leap year
[ { "code": null, "e": 1243, "s": 1062, "text": "Here we will see how to check given year is leap year or not, using PL/SQL. In PL/SQL code, some group of commands are arranged within a block of related declaration of statements." }, { "code": null, "e": 1291, "s": 1243, "text": "The leap year checking algorithm is like below." }, { "code": null, "e": 1505, "s": 1291, "text": "isLeapYear(year):\nbegin\n if year is divisible by 4 and not divisible by 100, then\n it is leap year\n else if the number is divisible by 400, then\n it is leap year\n else\n it is not leap year\nend" }, { "code": null, "e": 1771, "s": 1505, "text": "DECLARE\n year NUMBER := 2012;\nBEGIN\n IF MOD(year, 4)=0\n AND\n MOD(year, 100)!=0\n OR\n MOD(year, 400)=0 THEN\n dbms_output.Put_line(year || ' is leap year ');\n ELSE\n dbms_output.Put_line(year || ' is not leap year.');\n END IF;\nEND;" }, { "code": null, "e": 1789, "s": 1771, "text": "2012 is leap year" } ]
Interpretable K-Means: Clusters Feature Importances | by Yousef Alghofaili | Towards Data Science
Machine learning models go through many stages for them to be considered production-ready. One critical stage is that moment of truth where the model is given a scientific green light; Model Evaluation. Many evaluation metrics are designated for different purposes and problem specifications, but none of them is flawless. Hence, data scientists have a huge burden to carry when choosing which evaluation metric to use that best fits the problem at hand and serves as a functional decision-inducing value for a machine learning project. However, some evaluation metric values could seem unintuitive and cannot be explained in laymen’s terms, especially when evaluating unsupervised clustering algorithms using internal indexes (No external information is present such as true labels). Although these measurements serve a considerable benefit for comparative benchmarking, combining them with an interpretation is crucial for independent, intuitive validation and easier results communication with stakeholders. Data scientists tend to lose a focal point in the evaluation process when it comes to internal validation indexes, which is the intuitive β€œHuman” understanding of the model’s performance and its explanation. To elaborate by a counterexample, supervised classification evaluation metrics such as Accuracy, Precision, or Recall have very intuitive explanations for both laymen and experts. For instance: Accuracy: β€œWe have correctly classified this percentage of samples out of all samples we have.” Precision: β€œWe have correctly classified this percentage of Positives out of all predicted positives.” Recall: β€œWe have correctly classified this percentage of Positives out of all actual positives.” On the other hand, internal validation indexes such as the widely used Silhouette Coefficient, Calinski-Harabasz Index, Davies-Bouldin Index, and many others are, more often than not, used comparatively rather than an inherent and independent performance evaluation. The values of these measurements can be broken down to how compact each cluster is (How similar the cluster data points are to each other), how well-separated the clusters are (How dissimilar each cluster’s data points are from other clusters’ data points), or both. But, these measurements are not as easy to explain and connect to the clustering problem you are solving. Notwithstanding how valuable these measures are, obtaining an interpretation for a model along with an internal evaluation index is crucial when trying to understand how good your model is as a data scientist or attempting to deeply communicate your results to stakeholders where most internal validation indexes do not pass the ELI5 (Explain it Like I’m 5) Test :). This article will focus on one of the most popular unsupervised clustering algorithms; The K-Means, and presents two possible techniques to extract the most important features for each cluster. The article’s outline is as follows: K-Means Business ValueHow K-Means WorksInterpretation TechniquesReal-Life Application K-Means Business Value How K-Means Works Interpretation Techniques Real-Life Application If you already know how K-Means works, jump to the Interpretation Techniques section, or would like to visit the repository for this article and use the code directly, visit kmeans-feature-importance. Say that you are running a business with thousands of customers, and you would want to know more about your customers, albeit how many you have. You cannot study each customer and cater a marketing campaign specifically for them, for example. Yet, you know that each customer will probably have different demographic (e.g., Age), Geographic (e.g., Region), Psychographic (e.g., Spending Habits), and Behavioral (e.g., Engagement) properties. Segmenting them into multiple similar groups will simplify understanding who they are from the most prevalent properties of each group. The most popular algorithm to solve this problem, I am sure you guessed it! Is K-Means; β€œK” will refer to the number of possible customer segments/groups/clusters, and β€œMeans” can be thought of as imaginary persons who are the center (Most similar to their group members) of each group in the K groups. K-Means is an unsupervised clustering algorithm that groups similar data samples in one group away from dissimilar data samples. Precisely, it aims to minimize the Within-Cluster Sum of Squares (WCSS) and consequently maximize the Between-Cluster Sum of Squares (BCSS). K-Means algorithm has different implementations and conceptual variations, but for the sake of this article, We will focus on the most common method, namely Lloyd’s algorithm (Naive K-Means), which follows an iterative approach to find a sub-optimal solution. Before starting, we will prepare a simple dataset for explanation and see how it looks like. The steps we need to do to cluster the data points above into K groups using K-Means are: A centroid represents each cluster; The mean of all data points assigned to that cluster. Choosing an initial number of groups is synonymous with choosing an initial number of centroids K. We can decide on K = 3 and choose 3 distinct data points randomly from the dataset as our initial centroids (There are better methods to choose the initial coordinates of each centroid). We have to assign each data point in our dataset to the closest centroid. We will use the most common distance metric as our definition of β€œclose” through the following steps: 1. Calculate the Euclidean distance between each centroid and all data points using the equation below for each j-th cluster centroid C_j, and one point pfor a dataset that has d-Dimensions. (My usage of C_j = u_c_j (u = average) = Cluster Centroid is only a simplification since the equations I will list are in a single cluster level). 2. To minimize the WCSS, we assign each data point to its closest centroid (Most similar / Least Distant). The reason why this will be a WCSS minimization step is from the equation for one cluster’s WCSS with p_m number of points assigned to the cluster centroid C_jwhere the shorter the distance for the points assigned to the cluster centroid, the lower its WCSS. The last step is to update the cluster centroids' positions since different data points were assigned to each cluster. We have to move each centroid to the mean of all data points assigned to it by: Calculating the mean of each cluster’s data pointsSetting the new cluster centroid to the new mean for each clusterRepeating Step 2 and Step 3 until the cluster centroids (the new means) do not change Calculating the mean of each cluster’s data points Setting the new cluster centroid to the new mean for each cluster Repeating Step 2 and Step 3 until the cluster centroids (the new means) do not change Using sklearn.cluster.KMean ; We will end up with the following where you can take, for example, Sample 0 and Sample 1features, calculate their mean and then check if it equals to Cluster Centroid D1 and Cluster Centroid D2: The plot below shows how K-Means clustered the dataset where each centroid is positioned at the mean of the points assigned to it: Disclaimer: The author has developed this method. Please do not hesitate to cite any references if found or criticize the methodology. This approach is a direct analysis of each centroid’s sub-optimal position. Since K-Means aim is to minimize the Within-Cluster Sum of Squares and assuming that the distance metric used is the euclidean distance: We can find the dimensions that were responsible for the highest amount of WCSS (The sum of squares of each data point distance to its cluster centroid) minimization for each cluster through finding the maximum absolute centroid dimensional movement. Using the same explanation example above, we can access cluster_centers_ from sklearn.cluster.KMeanfitted model; The final cluster centroids’ positions. Then show the feature names (Dimensions d): Plotting the clusters along with their positions would yield the following: Now let’s take each centroid and sort it by the dimensions axis, and remember to take the absolute value if you have features that have negative values. After that, we can get the first centroid’s dimensions with sorted weights (Centroid distance traveled on features plane) and map that to feature names which will give us the hypothetical features importances below: Since the centroid has moved with equal distances through both dimensions, the features will be of equal importance. Let’s give the last two samples (Belonging to cluster 0) a nudge on the first dimension and repeat the same process, then plot the new centroids We will now apply the same approach again and extract the feature importances. Notice that cluster 0 has moved on feature one much more than feature 2 and thus has had a higher impact on WCSS minimization. This approach is model-agnostic; Not exclusive to K-Means, in which we convert the unsupervised clustering problem into a One-vs-All supervised classification problem using an easily interpretable classifier such as tree-based models. The steps to do this are as follows: Change the cluster labels into One-vs-All binary labels for eachTrain a classifier to discriminate between each cluster and all other clustersExtract the feature importances from the model (We will be using sklearn.ensemble.RandomForestClassifier) Change the cluster labels into One-vs-All binary labels for each Train a classifier to discriminate between each cluster and all other clusters Extract the feature importances from the model (We will be using sklearn.ensemble.RandomForestClassifier) Following from step 1, let us set cluster 0 label as 1 and set all other cluster labels to 0: We have converted the problem into a binary classification problem. What is left is to train a classifier and use its feature_importances_ method implemented in scikit-learn to get the features that have the most discriminatory power between all clusters and the targeted cluster. We also need to map them to their feature names sorted by the weights. One important note is that this approach finds what discriminates between two clusters and is not at all inherent to the targeted cluster. Furthermore, there are many other sophisticated methods to extract the most important features from tree-based models and model-agnostic approaches which you can try. I have chosen to apply the interpretation technique on an NLP problem since we can easily relate to the feature importances (English words), which could be considered as a group-based keyword extraction technique where we aim to cluster similar documents together using K-Means and then apply the techniques above. The dataset I will be using can be found here Kaggle BBC-News, which presents a classification problem. We will exclude the category column at first (Sport, Business, Politics, Entertainment, and Technology News articles) and use it later as a proof-of-concept. The distribution of news categories in the dataset is: Since this article is not NLP-Specific (Natural Language Processing), I won’t intensively go through any NLP-related tasks. So, quickly moving towards preprocessing the text to prepare the features. The code below normalizes the words and filtering tokens (words and digits) that do not present a discriminatory power and are thus redundant. Then calculates the highest mentioned words in the whole dataset and plots them (You can skip the code): Using TF-IDF (Text Representation Technique), we can convert the categorical variables (Words) into numeric representations. We do not need to scale the features here as TF-IDF normalizes features within its equation, and its output should be used in its raw form. Remember to scale the features if you apply K-Means on a dataset with features of different units or ranges where this difference is not relevant to the problem. Finally, now is the step we care about the most; I have wrapped up the method above in a class that inherits from sklearn.cluster.KMean and can be used in the same way with the difference of having feature_importances_ property added. You will have to provide the features ordered in the same way as X parameter in the fit method to ordered_feature_namesparameter for the modified class when initializing. You can find the code here kmeans-feature-importance and simply clone it like this in your favorite CLI or simply follow through by accessing the Colab example in the repository: git clone https://github.com/YousefGh/kmeans-feature-importance.git And then run the modified KMeans class with k= number of news dataset categories so that we can compare the results later with the actual categories. Let’s check if K-Means has produced a cluster distribution similar to the category distribution in the news dataset. That’s a close-enough category distribution similarity to get us going. Don’t forget to ensure that K-Means has produced accurate results by using different internal validation indexes (I won’t be going through them as this will be out-of-scope), and you probably will not have true labels, so you will need to choose the best K in K-Means if K is unknown from the problem domain knowledge. Moving on to interpretation, we can access the feature_importances_for the second cluster cluster 1 like this (The example is for WCSS Minimizers): We will compare both the WCSS Minimizers method and the Unsupervised to Supervised problem conversion method using the feature_importance_methodparameter in KMeanInterp class. The flow will be as follows: Plot categories distribution for comparison with unique colors set feature_importance_methodparameter as wcss_min and plot feature importances set feature_importance_methodparameter as unsup2supand plot feature importances Infer the category of each cluster using its most important features WCSS Minimizers Unsupervised to Supervised Clustering Interpretability becomes crucial when truth labels are not available at development time. It not only prevents data scientists from a direct evaluation of clustering validity due to the nature of internal validation indexes but also obstructs a simple and intuitive explanation of cluster performance to stakeholders. We have presented two possible approaches that aim to tackle this through extracting cluster-based feature importance, which allows us to know why the K-Means algorithm has chosen each cluster to be as such. The approach extends itself to stakeholder communication, simple and intuitive evaluation, cluster-based Keyword Extraction in NLP, and a general feature selection technique. The notebook for this article, KMeansInterp class, along with a direct usage example on Colab, can be found here. Happy Interpretation! References: Y. Liu, Z. Li, H. Xiong, X. Gao and J. Wu, β€œUnderstanding of Internal Clustering Validation Measures,” 2010 IEEE International Conference on Data Mining, 2010, pp. 911–916, doi: 10.1109/ICDM.2010.35.Kriegel, HP., Schubert, E. & Zimek, A. The (black) art of runtime evaluation: Are we comparing algorithms or implementations?. Knowl Inf Syst 52, 341–378 (2017). https://doi.org/10.1007/s10115-016-1004-2Ng, A., & Piech, C. (2021). CS221. Retrieved 18 July 2021, from https://stanford.edu/~cpiech/cs221/handouts/kmeans.htmlIsmaili, Oumaima & Lemaire, Vincent & Cornuéjols, Antoine. (2014). A Supervised Methodology to Measure the Variables Contribution to a Clustering. 159–166. 10.1007/978–3–319–12637–1_20.β€œ2.3. Clustering β€” scikit-learn 0.24.2 documentation”, 2021 Y. Liu, Z. Li, H. Xiong, X. Gao and J. Wu, β€œUnderstanding of Internal Clustering Validation Measures,” 2010 IEEE International Conference on Data Mining, 2010, pp. 911–916, doi: 10.1109/ICDM.2010.35. Kriegel, HP., Schubert, E. & Zimek, A. The (black) art of runtime evaluation: Are we comparing algorithms or implementations?. Knowl Inf Syst 52, 341–378 (2017). https://doi.org/10.1007/s10115-016-1004-2 Ng, A., & Piech, C. (2021). CS221. Retrieved 18 July 2021, from https://stanford.edu/~cpiech/cs221/handouts/kmeans.html Ismaili, Oumaima & Lemaire, Vincent & Cornuéjols, Antoine. (2014). A Supervised Methodology to Measure the Variables Contribution to a Clustering. 159–166. 10.1007/978–3–319–12637–1_20. β€œ2.3. Clustering β€” scikit-learn 0.24.2 documentation”, 2021
[ { "code": null, "e": 709, "s": 172, "text": "Machine learning models go through many stages for them to be considered production-ready. One critical stage is that moment of truth where the model is given a scientific green light; Model Evaluation. Many evaluation metrics are designated for different purposes and problem specifications, but none of them is flawless. Hence, data scientists have a huge burden to carry when choosing which evaluation metric to use that best fits the problem at hand and serves as a functional decision-inducing value for a machine learning project." }, { "code": null, "e": 1183, "s": 709, "text": "However, some evaluation metric values could seem unintuitive and cannot be explained in laymen’s terms, especially when evaluating unsupervised clustering algorithms using internal indexes (No external information is present such as true labels). Although these measurements serve a considerable benefit for comparative benchmarking, combining them with an interpretation is crucial for independent, intuitive validation and easier results communication with stakeholders." }, { "code": null, "e": 1585, "s": 1183, "text": "Data scientists tend to lose a focal point in the evaluation process when it comes to internal validation indexes, which is the intuitive β€œHuman” understanding of the model’s performance and its explanation. To elaborate by a counterexample, supervised classification evaluation metrics such as Accuracy, Precision, or Recall have very intuitive explanations for both laymen and experts. For instance:" }, { "code": null, "e": 1681, "s": 1585, "text": "Accuracy: β€œWe have correctly classified this percentage of samples out of all samples we have.”" }, { "code": null, "e": 1784, "s": 1681, "text": "Precision: β€œWe have correctly classified this percentage of Positives out of all predicted positives.”" }, { "code": null, "e": 1881, "s": 1784, "text": "Recall: β€œWe have correctly classified this percentage of Positives out of all actual positives.”" }, { "code": null, "e": 2521, "s": 1881, "text": "On the other hand, internal validation indexes such as the widely used Silhouette Coefficient, Calinski-Harabasz Index, Davies-Bouldin Index, and many others are, more often than not, used comparatively rather than an inherent and independent performance evaluation. The values of these measurements can be broken down to how compact each cluster is (How similar the cluster data points are to each other), how well-separated the clusters are (How dissimilar each cluster’s data points are from other clusters’ data points), or both. But, these measurements are not as easy to explain and connect to the clustering problem you are solving." }, { "code": null, "e": 3119, "s": 2521, "text": "Notwithstanding how valuable these measures are, obtaining an interpretation for a model along with an internal evaluation index is crucial when trying to understand how good your model is as a data scientist or attempting to deeply communicate your results to stakeholders where most internal validation indexes do not pass the ELI5 (Explain it Like I’m 5) Test :). This article will focus on one of the most popular unsupervised clustering algorithms; The K-Means, and presents two possible techniques to extract the most important features for each cluster. The article’s outline is as follows:" }, { "code": null, "e": 3205, "s": 3119, "text": "K-Means Business ValueHow K-Means WorksInterpretation TechniquesReal-Life Application" }, { "code": null, "e": 3228, "s": 3205, "text": "K-Means Business Value" }, { "code": null, "e": 3246, "s": 3228, "text": "How K-Means Works" }, { "code": null, "e": 3272, "s": 3246, "text": "Interpretation Techniques" }, { "code": null, "e": 3294, "s": 3272, "text": "Real-Life Application" }, { "code": null, "e": 3495, "s": 3294, "text": "If you already know how K-Means works, jump to the Interpretation Techniques section, or would like to visit the repository for this article and use the code directly, visit kmeans-feature-importance." }, { "code": null, "e": 4376, "s": 3495, "text": "Say that you are running a business with thousands of customers, and you would want to know more about your customers, albeit how many you have. You cannot study each customer and cater a marketing campaign specifically for them, for example. Yet, you know that each customer will probably have different demographic (e.g., Age), Geographic (e.g., Region), Psychographic (e.g., Spending Habits), and Behavioral (e.g., Engagement) properties. Segmenting them into multiple similar groups will simplify understanding who they are from the most prevalent properties of each group. The most popular algorithm to solve this problem, I am sure you guessed it! Is K-Means; β€œK” will refer to the number of possible customer segments/groups/clusters, and β€œMeans” can be thought of as imaginary persons who are the center (Most similar to their group members) of each group in the K groups." }, { "code": null, "e": 4999, "s": 4376, "text": "K-Means is an unsupervised clustering algorithm that groups similar data samples in one group away from dissimilar data samples. Precisely, it aims to minimize the Within-Cluster Sum of Squares (WCSS) and consequently maximize the Between-Cluster Sum of Squares (BCSS). K-Means algorithm has different implementations and conceptual variations, but for the sake of this article, We will focus on the most common method, namely Lloyd’s algorithm (Naive K-Means), which follows an iterative approach to find a sub-optimal solution. Before starting, we will prepare a simple dataset for explanation and see how it looks like." }, { "code": null, "e": 5089, "s": 4999, "text": "The steps we need to do to cluster the data points above into K groups using K-Means are:" }, { "code": null, "e": 5465, "s": 5089, "text": "A centroid represents each cluster; The mean of all data points assigned to that cluster. Choosing an initial number of groups is synonymous with choosing an initial number of centroids K. We can decide on K = 3 and choose 3 distinct data points randomly from the dataset as our initial centroids (There are better methods to choose the initial coordinates of each centroid)." }, { "code": null, "e": 5641, "s": 5465, "text": "We have to assign each data point in our dataset to the closest centroid. We will use the most common distance metric as our definition of β€œclose” through the following steps:" }, { "code": null, "e": 5979, "s": 5641, "text": "1. Calculate the Euclidean distance between each centroid and all data points using the equation below for each j-th cluster centroid C_j, and one point pfor a dataset that has d-Dimensions. (My usage of C_j = u_c_j (u = average) = Cluster Centroid is only a simplification since the equations I will list are in a single cluster level)." }, { "code": null, "e": 6345, "s": 5979, "text": "2. To minimize the WCSS, we assign each data point to its closest centroid (Most similar / Least Distant). The reason why this will be a WCSS minimization step is from the equation for one cluster’s WCSS with p_m number of points assigned to the cluster centroid C_jwhere the shorter the distance for the points assigned to the cluster centroid, the lower its WCSS." }, { "code": null, "e": 6544, "s": 6345, "text": "The last step is to update the cluster centroids' positions since different data points were assigned to each cluster. We have to move each centroid to the mean of all data points assigned to it by:" }, { "code": null, "e": 6745, "s": 6544, "text": "Calculating the mean of each cluster’s data pointsSetting the new cluster centroid to the new mean for each clusterRepeating Step 2 and Step 3 until the cluster centroids (the new means) do not change" }, { "code": null, "e": 6796, "s": 6745, "text": "Calculating the mean of each cluster’s data points" }, { "code": null, "e": 6862, "s": 6796, "text": "Setting the new cluster centroid to the new mean for each cluster" }, { "code": null, "e": 6948, "s": 6862, "text": "Repeating Step 2 and Step 3 until the cluster centroids (the new means) do not change" }, { "code": null, "e": 7173, "s": 6948, "text": "Using sklearn.cluster.KMean ; We will end up with the following where you can take, for example, Sample 0 and Sample 1features, calculate their mean and then check if it equals to Cluster Centroid D1 and Cluster Centroid D2:" }, { "code": null, "e": 7304, "s": 7173, "text": "The plot below shows how K-Means clustered the dataset where each centroid is positioned at the mean of the points assigned to it:" }, { "code": null, "e": 7439, "s": 7304, "text": "Disclaimer: The author has developed this method. Please do not hesitate to cite any references if found or criticize the methodology." }, { "code": null, "e": 7903, "s": 7439, "text": "This approach is a direct analysis of each centroid’s sub-optimal position. Since K-Means aim is to minimize the Within-Cluster Sum of Squares and assuming that the distance metric used is the euclidean distance: We can find the dimensions that were responsible for the highest amount of WCSS (The sum of squares of each data point distance to its cluster centroid) minimization for each cluster through finding the maximum absolute centroid dimensional movement." }, { "code": null, "e": 8100, "s": 7903, "text": "Using the same explanation example above, we can access cluster_centers_ from sklearn.cluster.KMeanfitted model; The final cluster centroids’ positions. Then show the feature names (Dimensions d):" }, { "code": null, "e": 8176, "s": 8100, "text": "Plotting the clusters along with their positions would yield the following:" }, { "code": null, "e": 8329, "s": 8176, "text": "Now let’s take each centroid and sort it by the dimensions axis, and remember to take the absolute value if you have features that have negative values." }, { "code": null, "e": 8545, "s": 8329, "text": "After that, we can get the first centroid’s dimensions with sorted weights (Centroid distance traveled on features plane) and map that to feature names which will give us the hypothetical features importances below:" }, { "code": null, "e": 8807, "s": 8545, "text": "Since the centroid has moved with equal distances through both dimensions, the features will be of equal importance. Let’s give the last two samples (Belonging to cluster 0) a nudge on the first dimension and repeat the same process, then plot the new centroids" }, { "code": null, "e": 9013, "s": 8807, "text": "We will now apply the same approach again and extract the feature importances. Notice that cluster 0 has moved on feature one much more than feature 2 and thus has had a higher impact on WCSS minimization." }, { "code": null, "e": 9285, "s": 9013, "text": "This approach is model-agnostic; Not exclusive to K-Means, in which we convert the unsupervised clustering problem into a One-vs-All supervised classification problem using an easily interpretable classifier such as tree-based models. The steps to do this are as follows:" }, { "code": null, "e": 9533, "s": 9285, "text": "Change the cluster labels into One-vs-All binary labels for eachTrain a classifier to discriminate between each cluster and all other clustersExtract the feature importances from the model (We will be using sklearn.ensemble.RandomForestClassifier)" }, { "code": null, "e": 9598, "s": 9533, "text": "Change the cluster labels into One-vs-All binary labels for each" }, { "code": null, "e": 9677, "s": 9598, "text": "Train a classifier to discriminate between each cluster and all other clusters" }, { "code": null, "e": 9783, "s": 9677, "text": "Extract the feature importances from the model (We will be using sklearn.ensemble.RandomForestClassifier)" }, { "code": null, "e": 9877, "s": 9783, "text": "Following from step 1, let us set cluster 0 label as 1 and set all other cluster labels to 0:" }, { "code": null, "e": 10229, "s": 9877, "text": "We have converted the problem into a binary classification problem. What is left is to train a classifier and use its feature_importances_ method implemented in scikit-learn to get the features that have the most discriminatory power between all clusters and the targeted cluster. We also need to map them to their feature names sorted by the weights." }, { "code": null, "e": 10535, "s": 10229, "text": "One important note is that this approach finds what discriminates between two clusters and is not at all inherent to the targeted cluster. Furthermore, there are many other sophisticated methods to extract the most important features from tree-based models and model-agnostic approaches which you can try." }, { "code": null, "e": 11112, "s": 10535, "text": "I have chosen to apply the interpretation technique on an NLP problem since we can easily relate to the feature importances (English words), which could be considered as a group-based keyword extraction technique where we aim to cluster similar documents together using K-Means and then apply the techniques above. The dataset I will be using can be found here Kaggle BBC-News, which presents a classification problem. We will exclude the category column at first (Sport, Business, Politics, Entertainment, and Technology News articles) and use it later as a proof-of-concept." }, { "code": null, "e": 11167, "s": 11112, "text": "The distribution of news categories in the dataset is:" }, { "code": null, "e": 11614, "s": 11167, "text": "Since this article is not NLP-Specific (Natural Language Processing), I won’t intensively go through any NLP-related tasks. So, quickly moving towards preprocessing the text to prepare the features. The code below normalizes the words and filtering tokens (words and digits) that do not present a discriminatory power and are thus redundant. Then calculates the highest mentioned words in the whole dataset and plots them (You can skip the code):" }, { "code": null, "e": 12041, "s": 11614, "text": "Using TF-IDF (Text Representation Technique), we can convert the categorical variables (Words) into numeric representations. We do not need to scale the features here as TF-IDF normalizes features within its equation, and its output should be used in its raw form. Remember to scale the features if you apply K-Means on a dataset with features of different units or ranges where this difference is not relevant to the problem." }, { "code": null, "e": 12447, "s": 12041, "text": "Finally, now is the step we care about the most; I have wrapped up the method above in a class that inherits from sklearn.cluster.KMean and can be used in the same way with the difference of having feature_importances_ property added. You will have to provide the features ordered in the same way as X parameter in the fit method to ordered_feature_namesparameter for the modified class when initializing." }, { "code": null, "e": 12626, "s": 12447, "text": "You can find the code here kmeans-feature-importance and simply clone it like this in your favorite CLI or simply follow through by accessing the Colab example in the repository:" }, { "code": null, "e": 12694, "s": 12626, "text": "git clone https://github.com/YousefGh/kmeans-feature-importance.git" }, { "code": null, "e": 12844, "s": 12694, "text": "And then run the modified KMeans class with k= number of news dataset categories so that we can compare the results later with the actual categories." }, { "code": null, "e": 12961, "s": 12844, "text": "Let’s check if K-Means has produced a cluster distribution similar to the category distribution in the news dataset." }, { "code": null, "e": 13352, "s": 12961, "text": "That’s a close-enough category distribution similarity to get us going. Don’t forget to ensure that K-Means has produced accurate results by using different internal validation indexes (I won’t be going through them as this will be out-of-scope), and you probably will not have true labels, so you will need to choose the best K in K-Means if K is unknown from the problem domain knowledge." }, { "code": null, "e": 13500, "s": 13352, "text": "Moving on to interpretation, we can access the feature_importances_for the second cluster cluster 1 like this (The example is for WCSS Minimizers):" }, { "code": null, "e": 13705, "s": 13500, "text": "We will compare both the WCSS Minimizers method and the Unsupervised to Supervised problem conversion method using the feature_importance_methodparameter in KMeanInterp class. The flow will be as follows:" }, { "code": null, "e": 13768, "s": 13705, "text": "Plot categories distribution for comparison with unique colors" }, { "code": null, "e": 13848, "s": 13768, "text": "set feature_importance_methodparameter as wcss_min and plot feature importances" }, { "code": null, "e": 13928, "s": 13848, "text": "set feature_importance_methodparameter as unsup2supand plot feature importances" }, { "code": null, "e": 13997, "s": 13928, "text": "Infer the category of each cluster using its most important features" }, { "code": null, "e": 14013, "s": 13997, "text": "WCSS Minimizers" }, { "code": null, "e": 14040, "s": 14013, "text": "Unsupervised to Supervised" }, { "code": null, "e": 14752, "s": 14040, "text": "Clustering Interpretability becomes crucial when truth labels are not available at development time. It not only prevents data scientists from a direct evaluation of clustering validity due to the nature of internal validation indexes but also obstructs a simple and intuitive explanation of cluster performance to stakeholders. We have presented two possible approaches that aim to tackle this through extracting cluster-based feature importance, which allows us to know why the K-Means algorithm has chosen each cluster to be as such. The approach extends itself to stakeholder communication, simple and intuitive evaluation, cluster-based Keyword Extraction in NLP, and a general feature selection technique." }, { "code": null, "e": 14888, "s": 14752, "text": "The notebook for this article, KMeansInterp class, along with a direct usage example on Colab, can be found here. Happy Interpretation!" }, { "code": null, "e": 14900, "s": 14888, "text": "References:" }, { "code": null, "e": 15667, "s": 14900, "text": "Y. Liu, Z. Li, H. Xiong, X. Gao and J. Wu, β€œUnderstanding of Internal Clustering Validation Measures,” 2010 IEEE International Conference on Data Mining, 2010, pp. 911–916, doi: 10.1109/ICDM.2010.35.Kriegel, HP., Schubert, E. & Zimek, A. The (black) art of runtime evaluation: Are we comparing algorithms or implementations?. Knowl Inf Syst 52, 341–378 (2017). https://doi.org/10.1007/s10115-016-1004-2Ng, A., & Piech, C. (2021). CS221. Retrieved 18 July 2021, from https://stanford.edu/~cpiech/cs221/handouts/kmeans.htmlIsmaili, Oumaima & Lemaire, Vincent & Cornuéjols, Antoine. (2014). A Supervised Methodology to Measure the Variables Contribution to a Clustering. 159–166. 10.1007/978–3–319–12637–1_20.β€œ2.3. Clustering β€” scikit-learn 0.24.2 documentation”, 2021" }, { "code": null, "e": 15867, "s": 15667, "text": "Y. Liu, Z. Li, H. Xiong, X. Gao and J. Wu, β€œUnderstanding of Internal Clustering Validation Measures,” 2010 IEEE International Conference on Data Mining, 2010, pp. 911–916, doi: 10.1109/ICDM.2010.35." }, { "code": null, "e": 16071, "s": 15867, "text": "Kriegel, HP., Schubert, E. & Zimek, A. The (black) art of runtime evaluation: Are we comparing algorithms or implementations?. Knowl Inf Syst 52, 341–378 (2017). https://doi.org/10.1007/s10115-016-1004-2" }, { "code": null, "e": 16191, "s": 16071, "text": "Ng, A., & Piech, C. (2021). CS221. Retrieved 18 July 2021, from https://stanford.edu/~cpiech/cs221/handouts/kmeans.html" }, { "code": null, "e": 16378, "s": 16191, "text": "Ismaili, Oumaima & Lemaire, Vincent & Cornuéjols, Antoine. (2014). A Supervised Methodology to Measure the Variables Contribution to a Clustering. 159–166. 10.1007/978–3–319–12637–1_20." } ]
What is Is-a relationship in Java?
IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance. public class Animal { } public class Mammal extends Animal { } public class Reptile extends Animal { } public class Dog extends Mammal { } Now, based on the above example, in Object-Oriented terms, the following are true βˆ’ Animal is the superclass of Mammal class. Animal is the superclass of Reptile class. Mammal and Reptile are subclasses of Animal class. Dog is the subclass of both Mammal and Animal classes. Live Demo class Animal { } class Mammal extends Animal { } class Reptile extends Animal { } public class Dog extends Mammal { public static void main(String args[]) { Animal a = new Animal(); Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } } true true true
[ { "code": null, "e": 1192, "s": 1062, "text": "IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance." }, { "code": null, "e": 1331, "s": 1192, "text": "public class Animal {\n}\npublic class Mammal extends Animal {\n}\npublic class Reptile extends Animal {\n}\npublic class Dog extends Mammal {\n}" }, { "code": null, "e": 1415, "s": 1331, "text": "Now, based on the above example, in Object-Oriented terms, the following are true βˆ’" }, { "code": null, "e": 1457, "s": 1415, "text": "Animal is the superclass of Mammal class." }, { "code": null, "e": 1500, "s": 1457, "text": "Animal is the superclass of Reptile class." }, { "code": null, "e": 1551, "s": 1500, "text": "Mammal and Reptile are subclasses of Animal class." }, { "code": null, "e": 1606, "s": 1551, "text": "Dog is the subclass of both Mammal and Animal classes." }, { "code": null, "e": 1617, "s": 1606, "text": " Live Demo" }, { "code": null, "e": 1971, "s": 1617, "text": "class Animal {\n}\nclass Mammal extends Animal {\n}\nclass Reptile extends Animal {\n}\npublic class Dog extends Mammal {\npublic static void main(String args[]) {\nAnimal a = new Animal();\nMammal m = new Mammal();\nDog d = new Dog();\n\nSystem.out.println(m instanceof Animal);\nSystem.out.println(d instanceof Mammal);\nSystem.out.println(d instanceof Animal);\n}\n}" }, { "code": null, "e": 1986, "s": 1971, "text": "true\ntrue\ntrue" } ]
Pascal - Continue Statement
The continue statement in Pascal works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. For the for-do loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while-do and repeat...until loops, continue statement causes the program control to pass to the conditional tests. The syntax for a continue statement in Pascal is as follows βˆ’ continue; program exContinue; var a: integer; begin a := 10; (* repeat until loop execution *) repeat if( a = 15) then begin (* skip the iteration *) a := a + 1; continue; end; writeln('value of a: ', a); a := a+1; until ( a = 20 ); end. When the above code is compiled and executed, it produces the following result βˆ’ value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2290, "s": 2083, "text": "The continue statement in Pascal works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between." }, { "code": null, "e": 2528, "s": 2290, "text": "For the for-do loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while-do and repeat...until loops, continue statement causes the program control to pass to the conditional tests." }, { "code": null, "e": 2590, "s": 2528, "text": "The syntax for a continue statement in Pascal is as follows βˆ’" }, { "code": null, "e": 2601, "s": 2590, "text": "continue;\n" }, { "code": null, "e": 2917, "s": 2601, "text": "program exContinue; \nvar\n a: integer;\n\nbegin\n a := 10;\n (* repeat until loop execution *)\n repeat\n if( a = 15) then\n \n begin\n (* skip the iteration *)\n a := a + 1;\n continue;\n end;\n \n writeln('value of a: ', a);\n a := a+1;\n until ( a = 20 );\nend." }, { "code": null, "e": 2998, "s": 2917, "text": "When the above code is compiled and executed, it produces the following result βˆ’" }, { "code": null, "e": 3134, "s": 2998, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n" }, { "code": null, "e": 3169, "s": 3134, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3192, "s": 3169, "text": " Stone River ELearning" }, { "code": null, "e": 3199, "s": 3192, "text": " Print" }, { "code": null, "e": 3210, "s": 3199, "text": " Add Notes" } ]
stack empty() and stack size() in C++ STL - GeeksforGeeks
19 Sep, 2018 Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only. empty() function is used to check if the stack container is empty or not. Syntax : stackname.empty() Parameters : No parameters are passed. Returns : True, if stack is empty False, Otherwise Examples: Input : mystack mystack.empty(); Output : True Input : mystack = 1, 2, 3 Output : False Errors and Exceptions 1. Shows error if parameter is passed2. Shows no exception throw guarantee. // CPP program to illustrate// Implementation of empty() function#include <iostream>#include <stack>using namespace std; int main(){ stack<int> mystack; mystack.push(1); // Stack becomes 1 if (mystack.empty()) { cout << "True"; } else { cout << "False"; } return 0;} Output: False Application :Given a stack of integers, find the sum of the all the integers. Input : 1, 8, 3, 6, 2 Output: 20 Algorithm1. Check if the stack is empty, if not add the top element to a variable initialised as 0, and pop the top element.2. Repeat this step until the stack is empty.3. Print the final value of the variable. // CPP program to illustrate// Application of empty() function#include <iostream>#include <stack>using namespace std; int main(){ int sum = 0; stack<int> mystack; mystack.push(1); mystack.push(8); mystack.push(3); mystack.push(6); mystack.push(2); // Stack becomes 1, 8, 3, 6, 2 while (!mystack.empty()) { sum = sum + mystack.top(); mystack.pop(); } cout << sum; return 0;} Output: 20 size() function is used to return the size of the stack container or the number of elements in the stack container. Syntax : stackname.size() Parameters : No parameters are passed. Returns : Number of elements in the container. Examples: Input : mystack = 0, 1, 2 mystack.size(); Output : 3 Input : mystack = 0, 1, 2, 3, 4, 5 mystack.size(); Output : 6 Errors and Exceptions 1. Shows error if a parameter is passed.2. Shows no exception throw guarantee. // CPP program to illustrate// Implementation of size() function#include <iostream>#include <stack>using namespace std; int main(){ int sum = 0; stack<int> mystack; mystack.push(1); mystack.push(8); mystack.push(3); mystack.push(6); mystack.push(2); // Stack becomes 1, 8, 3, 6, 2 cout << mystack.size(); return 0;} Output: 5 Application :Given a stack of integers, find the sum of the all the integers. Input : 1, 8, 3, 6, 2 Output: 20 Algorithm1. Check if the size of the stack is zero, if not add the top element to a variable initialised as 0, and pop the top element.2. Repeat this step until the stack size becomes 0.3. Print the final value of the variable. // CPP program to illustrate// Application of size() function#include <iostream>#include <stack>using namespace std; int main(){ int sum = 0; stack<int> mystack; mystack.push(1); mystack.push(8); mystack.push(3); mystack.push(6); mystack.push(2); // Stack becomes 1, 8, 3, 6, 2 while (mystack.size() > 0) { sum = sum + mystack.top(); mystack.pop(); } cout << sum; return 0;} Output: 20 cpp-containers-library CPP-Library cpp-stack cpp-stack-functions STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ List in C++ Standard Template Library (STL) Convert string to char array in C++ Pair in C++ Standard Template Library (STL) Destructors in C++ new and delete operators in C++ for dynamic memory Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 23732, "s": 23704, "text": "\n19 Sep, 2018" }, { "code": null, "e": 23910, "s": 23732, "text": "Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only." }, { "code": null, "e": 23984, "s": 23910, "text": "empty() function is used to check if the stack container is empty or not." }, { "code": null, "e": 23993, "s": 23984, "text": "Syntax :" }, { "code": null, "e": 24102, "s": 23993, "text": "stackname.empty()\nParameters :\nNo parameters are passed.\nReturns :\nTrue, if stack is empty\nFalse, Otherwise\n" }, { "code": null, "e": 24112, "s": 24102, "text": "Examples:" }, { "code": null, "e": 24219, "s": 24112, "text": "Input : mystack\n mystack.empty();\nOutput : True\n \nInput : mystack = 1, 2, 3\nOutput : False\n" }, { "code": null, "e": 24241, "s": 24219, "text": "Errors and Exceptions" }, { "code": null, "e": 24317, "s": 24241, "text": "1. Shows error if parameter is passed2. Shows no exception throw guarantee." }, { "code": "// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <stack>using namespace std; int main(){ stack<int> mystack; mystack.push(1); // Stack becomes 1 if (mystack.empty()) { cout << \"True\"; } else { cout << \"False\"; } return 0;}", "e": 24627, "s": 24317, "text": null }, { "code": null, "e": 24635, "s": 24627, "text": "Output:" }, { "code": null, "e": 24642, "s": 24635, "text": "False\n" }, { "code": null, "e": 24720, "s": 24642, "text": "Application :Given a stack of integers, find the sum of the all the integers." }, { "code": null, "e": 24754, "s": 24720, "text": "Input : 1, 8, 3, 6, 2\nOutput: 20\n" }, { "code": null, "e": 24965, "s": 24754, "text": "Algorithm1. Check if the stack is empty, if not add the top element to a variable initialised as 0, and pop the top element.2. Repeat this step until the stack is empty.3. Print the final value of the variable." }, { "code": "// CPP program to illustrate// Application of empty() function#include <iostream>#include <stack>using namespace std; int main(){ int sum = 0; stack<int> mystack; mystack.push(1); mystack.push(8); mystack.push(3); mystack.push(6); mystack.push(2); // Stack becomes 1, 8, 3, 6, 2 while (!mystack.empty()) { sum = sum + mystack.top(); mystack.pop(); } cout << sum; return 0;}", "e": 25394, "s": 24965, "text": null }, { "code": null, "e": 25402, "s": 25394, "text": "Output:" }, { "code": null, "e": 25406, "s": 25402, "text": "20\n" }, { "code": null, "e": 25522, "s": 25406, "text": "size() function is used to return the size of the stack container or the number of elements in the stack container." }, { "code": null, "e": 25531, "s": 25522, "text": "Syntax :" }, { "code": null, "e": 25635, "s": 25531, "text": "stackname.size()\nParameters :\nNo parameters are passed.\nReturns :\nNumber of elements in the container.\n" }, { "code": null, "e": 25645, "s": 25635, "text": "Examples:" }, { "code": null, "e": 25789, "s": 25645, "text": "Input : mystack = 0, 1, 2\n mystack.size();\nOutput : 3\n \nInput : mystack = 0, 1, 2, 3, 4, 5\n mystack.size();\nOutput : 6\n" }, { "code": null, "e": 25811, "s": 25789, "text": "Errors and Exceptions" }, { "code": null, "e": 25890, "s": 25811, "text": "1. Shows error if a parameter is passed.2. Shows no exception throw guarantee." }, { "code": "// CPP program to illustrate// Implementation of size() function#include <iostream>#include <stack>using namespace std; int main(){ int sum = 0; stack<int> mystack; mystack.push(1); mystack.push(8); mystack.push(3); mystack.push(6); mystack.push(2); // Stack becomes 1, 8, 3, 6, 2 cout << mystack.size(); return 0;}", "e": 26243, "s": 25890, "text": null }, { "code": null, "e": 26251, "s": 26243, "text": "Output:" }, { "code": null, "e": 26254, "s": 26251, "text": "5\n" }, { "code": null, "e": 26332, "s": 26254, "text": "Application :Given a stack of integers, find the sum of the all the integers." }, { "code": null, "e": 26366, "s": 26332, "text": "Input : 1, 8, 3, 6, 2\nOutput: 20\n" }, { "code": null, "e": 26594, "s": 26366, "text": "Algorithm1. Check if the size of the stack is zero, if not add the top element to a variable initialised as 0, and pop the top element.2. Repeat this step until the stack size becomes 0.3. Print the final value of the variable." }, { "code": "// CPP program to illustrate// Application of size() function#include <iostream>#include <stack>using namespace std; int main(){ int sum = 0; stack<int> mystack; mystack.push(1); mystack.push(8); mystack.push(3); mystack.push(6); mystack.push(2); // Stack becomes 1, 8, 3, 6, 2 while (mystack.size() > 0) { sum = sum + mystack.top(); mystack.pop(); } cout << sum; return 0;}", "e": 27024, "s": 26594, "text": null }, { "code": null, "e": 27032, "s": 27024, "text": "Output:" }, { "code": null, "e": 27036, "s": 27032, "text": "20\n" }, { "code": null, "e": 27059, "s": 27036, "text": "cpp-containers-library" }, { "code": null, "e": 27071, "s": 27059, "text": "CPP-Library" }, { "code": null, "e": 27081, "s": 27071, "text": "cpp-stack" }, { "code": null, "e": 27101, "s": 27081, "text": "cpp-stack-functions" }, { "code": null, "e": 27105, "s": 27101, "text": "STL" }, { "code": null, "e": 27109, "s": 27105, "text": "C++" }, { "code": null, "e": 27113, "s": 27109, "text": "STL" }, { "code": null, "e": 27117, "s": 27113, "text": "CPP" }, { "code": null, "e": 27215, "s": 27117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27224, "s": 27215, "text": "Comments" }, { "code": null, "e": 27237, "s": 27224, "text": "Old Comments" }, { "code": null, "e": 27265, "s": 27237, "text": "Operator Overloading in C++" }, { "code": null, "e": 27289, "s": 27265, "text": "Sorting a vector in C++" }, { "code": null, "e": 27309, "s": 27289, "text": "Polymorphism in C++" }, { "code": null, "e": 27342, "s": 27309, "text": "Friend class and function in C++" }, { "code": null, "e": 27386, "s": 27342, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 27422, "s": 27386, "text": "Convert string to char array in C++" }, { "code": null, "e": 27466, "s": 27422, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 27485, "s": 27466, "text": "Destructors in C++" }, { "code": null, "e": 27536, "s": 27485, "text": "new and delete operators in C++ for dynamic memory" } ]
Finding the only unique string in an array using JavaScript
We are required to write a JavaScript function that takes in an array of strings. All the strings in the array contain the same characters, or the repetition of characters, and just one string contains a different set of characters. Our function should find and return that string. For example If the array is βˆ’ [β€˜ba’, 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ] Then the required string is β€˜foo’. Strings may contain spaces. Spaces are not significant, only non-spaces symbols matter. Example, a string that contains only spaces is like an empty string. It’s guaranteed that the array contains more than 3 strings. Following is the code βˆ’ Live Demo const arr = ['ba', 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]; const findOnlyUnique = (arr = []) => { const first = []; for(i = 0; i < arr.length; i++){ first.push(arr[i].toLowerCase().replace(/\s/g, '').split('')); for (j = 0; j < arr[i].length; j++){ first[i].sort(); } } const second = []; for (k = 0; k < arr.length; k++){ second.push(first[k].join()); } second.sort(); const third = []; if (second[1] !== second[second.length - 1]) { third.push(second[second.length - 1]); }else{ third.push(second[0]); } const last = []; for(let n = 0; n < first.length; n++){ last.push(first[n].join(',')); } return (arr[last.indexOf(third[0])]); }; console.log(findOnlyUnique(arr)); foo
[ { "code": null, "e": 1344, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of strings.\nAll the strings in the array contain the same characters, or the repetition of characters, and just one string contains a different set of characters. Our function should find and return that string." }, { "code": null, "e": 1356, "s": 1344, "text": "For example" }, { "code": null, "e": 1374, "s": 1356, "text": "If the array is βˆ’" }, { "code": null, "e": 1431, "s": 1374, "text": "[β€˜ba’, 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]" }, { "code": null, "e": 1466, "s": 1431, "text": "Then the required string is β€˜foo’." }, { "code": null, "e": 1684, "s": 1466, "text": "Strings may contain spaces. Spaces are not significant, only non-spaces symbols matter. Example, a string that contains only spaces is like an empty string. It’s guaranteed that the array contains more than 3 strings." }, { "code": null, "e": 1708, "s": 1684, "text": "Following is the code βˆ’" }, { "code": null, "e": 1719, "s": 1708, "text": " Live Demo" }, { "code": null, "e": 2496, "s": 1719, "text": "const arr = ['ba', 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ];\nconst findOnlyUnique = (arr = []) => {\n const first = [];\n for(i = 0; i < arr.length; i++){\n first.push(arr[i].toLowerCase().replace(/\\s/g, '').split(''));\n for (j = 0; j < arr[i].length; j++){\n first[i].sort();\n }\n }\n const second = [];\n for (k = 0; k < arr.length; k++){\n second.push(first[k].join());\n }\n second.sort();\n const third = [];\n if (second[1] !== second[second.length - 1]) {\n third.push(second[second.length - 1]);\n }else{\n third.push(second[0]);\n }\n const last = [];\n for(let n = 0; n < first.length; n++){\n last.push(first[n].join(','));\n }\n return (arr[last.indexOf(third[0])]);\n};\nconsole.log(findOnlyUnique(arr));" }, { "code": null, "e": 2500, "s": 2496, "text": "foo" } ]
Assembly - Loops
The JMP instruction can be used for implementing loops. For example, the following code snippet can be used for executing the loop-body 10 times. MOV CL, 10 L1: <LOOP-BODY> DEC CL JNZ L1 The processor instruction set, however, includes a group of loop instructions for implementing iteration. The basic LOOP instruction has the following syntax βˆ’ LOOP label Where, label is the target label that identifies the target instruction as in the jump instructions. The LOOP instruction assumes that the ECX register contains the loop count. When the loop instruction is executed, the ECX register is decremented and the control jumps to the target label, until the ECX register value, i.e., the counter reaches the value zero. The above code snippet could be written as βˆ’ mov ECX,10 l1: <loop body> loop l1 The following program prints the number 1 to 9 on the screen βˆ’ section .text global _start ;must be declared for using gcc _start: ;tell linker entry point mov ecx,10 mov eax, '1' l1: mov [num], eax mov eax, 4 mov ebx, 1 push ecx mov ecx, num mov edx, 1 int 0x80 mov eax, [num] sub eax, '0' inc eax add eax, '0' pop ecx loop l1 mov eax,1 ;system call number (sys_exit) int 0x80 ;call kernel section .bss num resb 1 When the above code is compiled and executed, it produces the following result βˆ’ 123456789: 46 Lectures 2 hours Frahaan Hussain 23 Lectures 12 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2231, "s": 2085, "text": "The JMP instruction can be used for implementing loops. For example, the following code snippet can be used for executing the loop-body 10 times." }, { "code": null, "e": 2272, "s": 2231, "text": "MOV\tCL, 10\nL1:\n<LOOP-BODY>\nDEC\tCL\nJNZ\tL1" }, { "code": null, "e": 2432, "s": 2272, "text": "The processor instruction set, however, includes a group of loop instructions for implementing iteration. The basic LOOP instruction has the following syntax βˆ’" }, { "code": null, "e": 2445, "s": 2432, "text": "LOOP \tlabel\n" }, { "code": null, "e": 2808, "s": 2445, "text": "Where, label is the target label that identifies the target instruction as in the jump instructions. The LOOP instruction assumes that the ECX register contains the loop count. When the loop instruction is executed, the ECX register is decremented and the control jumps to the target label, until the ECX register value, i.e., the counter reaches the value zero." }, { "code": null, "e": 2853, "s": 2808, "text": "The above code snippet could be written as βˆ’" }, { "code": null, "e": 2888, "s": 2853, "text": "mov ECX,10\nl1:\n<loop body>\nloop l1" }, { "code": null, "e": 2951, "s": 2888, "text": "The following program prints the number 1 to 9 on the screen βˆ’" }, { "code": null, "e": 3431, "s": 2951, "text": "section\t.text\n global _start ;must be declared for using gcc\n\t\n_start:\t ;tell linker entry point\n mov ecx,10\n mov eax, '1'\n\t\nl1:\n mov [num], eax\n mov eax, 4\n mov ebx, 1\n push ecx\n\t\n mov ecx, num \n mov edx, 1 \n int 0x80\n\t\n mov eax, [num]\n sub eax, '0'\n inc eax\n add eax, '0'\n pop ecx\n loop l1\n\t\n mov eax,1 ;system call number (sys_exit)\n int 0x80 ;call kernel\nsection\t.bss\nnum resb 1" }, { "code": null, "e": 3512, "s": 3431, "text": "When the above code is compiled and executed, it produces the following result βˆ’" }, { "code": null, "e": 3524, "s": 3512, "text": "123456789:\n" }, { "code": null, "e": 3557, "s": 3524, "text": "\n 46 Lectures \n 2 hours \n" }, { "code": null, "e": 3574, "s": 3557, "text": " Frahaan Hussain" }, { "code": null, "e": 3608, "s": 3574, "text": "\n 23 Lectures \n 12 hours \n" }, { "code": null, "e": 3616, "s": 3608, "text": " Uplatz" }, { "code": null, "e": 3623, "s": 3616, "text": " Print" }, { "code": null, "e": 3634, "s": 3623, "text": " Add Notes" } ]
Train a Custom Object Detection Model using Mask RCNN | by Samden Lepcha | Towards Data Science
A complete guide from installation and training to deploying a custom trained object detection model in a webapp. According to Wikipedia β€œA pothole is a depression in a road surface, usually asphalt pavement, where traffic has removed broken pieces of the pavement”. Edmonton the β€œself proclaimed pothole capital” in Alberta, Canada reportedly spends $4.8 million on 450,000 potholes annually, as of 2015. In India every year approximately 1100 lives are lost to accidents caused by potholes source. Ordinary citizens do not have the means of communicating or reporting the bad roads to the concerned authorities while the authorities lay unaware of the situation. Therefore, several organizations have been trying to develop tools (like web apps) where the citizens can report the potholes to the concerned authorities. There are several hackathons that have taken place with this project in mind as one of the objectives. Seeing this as a growing concern, in this project to address this problem the aim is to develop a simple interface that uses the state of the art object detection technology to detect potholes in real time and report them using Google Maps. This article will take you through the steps required to build your very own pothole detection system. The deployment medium for this project will be on smartphones which are used by 500 million+ people in India according to Newzoo’s 2019 Global Mobile Market Report. Tools Used: Python 3.6+ Tensorflow Object Detection API Pixel Annotation Tool Anaconda Package Manager Flask The workflow of the Project will be as follows: Environment Setup Dataset Gathering Model Training Deployment with Flask Results In the beginning, we will set up a new Anaconda environment and install all the necessary packages required for this project. Anaconda is a popular python package manager alongside β€œpip”. If you have not installed prior to this project please install it using the below links. It is a fairly straight forward installation and should not take long. You can install the Miniconda if you have some experience using the command line but if you want the GUI you can install the Anaconda Navigator with all the additional packages (this will take longer to install). After this open β€œAnaconda Prompt” from your start menu and follow the rest of the installation instructions: Create the conda environment. Create the conda environment. (base) C:\Users>conda create --name pothole python=3.6 2. Activate the environment and upgrade pip. (base) C:\Users>activate pothole(pothole) C:\Users>python -m pip install --upgrade pip 3. Install the other necessary packages by issuing the following commands: (pothole) C:\Users>conda install -c anaconda protobuf(pothole) C:\Users>pip install pillow(pothole) C:\Users>pip install lxml(pothole) C:\Users>pip install Cython(pothole) C:\Users>pip install contextlib2(pothole) C:\Users>pip install jupyter(pothole) C:\Users>pip install matplotlib(pothole) C:\Users>pip install opencv-python(pothole) C:\Users>pip install labelme(pothole) C:\Users>pip install tensorflow-gpu==1.15.2 4. Clone or download the tensorflow object detection api repository from Github. For the purpose of this project, we are using tensorflow version 1.15.2. Note Always make sure the tensorflow version installed and the tensorflow object detection api repository version is the same. Run the following command or download this repository manually. (pothole) C:\Users>git clone https://github.com/tensorflow/models.git Place these folders in a folder called β€œmodels”. You can place this β€œmodels” folder in a directory of your choice. 5. Configure the PYTHONPATH environment variable and install the COCO api: (pothole) C:\Users>set PYTHONPATH=C:\models;C:\models\research;C:\models\research\slim(pothole) C:\Users>pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI 6. Compile Protobufs and run setup.py In the Anaconda Prompt change directories to \models\research directory (pothole) C:\Users>cd C:\models\research Run the following lines of code: protoc --python_out=. .\object_detection\protos\anchor_generator.proto .\object_detection\protos\argmax_matcher.proto .\object_detection\protos\bipartite_matcher.proto .\object_detection\protos\box_coder.proto .\object_detection\protos\box_predictor.proto .\object_detection\protos\eval.proto .\object_detection\protos\faster_rcnn.proto .\object_detection\protos\faster_rcnn_box_coder.proto .\object_detection\protos\grid_anchor_generator.proto .\object_detection\protos\hyperparams.proto .\object_detection\protos\image_resizer.proto .\object_detection\protos\input_reader.proto .\object_detection\protos\losses.proto .\object_detection\protos\matcher.proto .\object_detection\protos\mean_stddev_box_coder.proto .\object_detection\protos\model.proto .\object_detection\protos\optimizer.proto .\object_detection\protos\pipeline.proto .\object_detection\protos\post_processing.proto .\object_detection\protos\preprocessor.proto .\object_detection\protos\region_similarity_calculator.proto .\object_detection\protos\square_box_coder.proto .\object_detection\protos\ssd.proto .\object_detection\protos\ssd_anchor_generator.proto .\object_detection\protos\string_int_label_map.proto .\object_detection\protos\train.proto .\object_detection\protos\keypoint_box_coder.proto .\object_detection\protos\multiscale_anchor_generator.proto .\object_detection\protos\graph_rewriter.proto .\object_detection\protos\calibration.proto .\object_detection\protos\flexible_grid_anchor_generator.proto If it gives an error that the protobuf file could not be found run this after: protoc object_detection/protos/*.proto --python_out=. Finally, we need to run the following commands: (pothole) C:\models\research> python setup.py build(pothole) C:\models\research> python setup.py install 8. You can test if everything is working out by running the IPython Notebook present in the object_detection folder called β€œobject_detection_tutorial.ipynb”. (pothole) C:\models\research>cd object_detection(pothole) C:\models\research\object_detection>jupyter notebook object_detection_tutorial.ipynb You can use my repository for supporting material for this article. github.com As always, at the beginning of any Data Science or AI Project after the problem statement has been identified we move on to gathering the data or in this case images for training. To train a robust model we need to use a lot of pictures but with variation as well. That means the potholes must be present at various angles or shapes so that our model does not lean on to one variation or in other words overfits and does not generalize for other images. You can use the images that you have taken personally or download them from the Internet like me. For this project, the idea is to detect potholes so we would not be segmenting them out based on severity but that does leave something for the future scope as well. The following data sources were used for building this project: Kaggle Research Gate We need to resize the images so that the model can be trained using these resized images like 800 x 600 in this project (Unless you have unlimited GPU compute power). Use either the command prompt or anaconda prompt or any other IDE to run this script. For example in Anaconda Prompt: (pothole) C:\Users> python DatasetCreation.py Now that we have gathered the dataset we need to label the images so that the model understands what is a pothole. To label the images we need a labeling software. For the purpose of the project, I have used labelme as it is fairly simple to use. In your anaconda environment type β€œlabelme” and the software should open up like below. (pothole) C:\Users>labelme Open your image from your directory and click on Create Polygon and start labeling your images. Labelme saves your labels as json files with the same name as the image name. Place the json in the same directory as your images. An example of Labelme(right) along with Pixel Annotation Tool(left) is shown below. For this project I have labeled 400 images. Create TFRecords: Create TFRecords: After labeling our entire dataset we now have to generate TFRecords which serves as input for our model training. But before that we need to convert the json labelme labels into COCO format. I have taken the script provided by Gilber Tanner in his tutorial to perform this. You can also find this in my Github Repository labeled β€œlabelme2coco.py”. Download this and place it onto the directory where your Train/ Test images are located. Now run the following commands: (pothole) C:\Users\models\research\object_detection\images>python labelme2coco.py train --output train.json(pothole) C:\Users\models\research\object_detection\images>python labelme2coco.py test --output test.json Now that the train/test data is in the COCO format we can now create the TFRecords using the create_coco_tf_record.py also created by Gilber Tanner. This script also needs to be placed and run from the object_detection folder. python create_coco_tf_record.py --logtostderr --train_image_dir=images/train --test_image_dir=images/test --train_annotations_file=images/train.json --test_annotations_file=images/test.json --include_masks=True --output_dir=./ You should find train.record and test.record in your object_detection folder. 2. Creating Label Map The label map links class names to ID numbers. Use a text editor like Sublime Text to create a β€œlabelmap.pbtxt” and store it inside object_detection/training folder. Inside the folder write the following: item { id: 1 name: 'Pothole'} You can define as much as you want depending on the classes you want to detect but for the purpose of this project we are only interested in detecting potholes. This id should match with the id mentioned in your train.json and test.json files. Notice how it one number greater i.e here it is id: 0 but we mention id:1 in the labelmap file. "categories": [ { "supercategory": "Pothole", "id": 0, "name": "Pothole" },], 3. Creating Training Configuration File: Now we need to create a training configuration file. From the tensorflow model zoo there are a variety of tensorflow models available for Mask RCNN but for the purpose of this project we are gonna use the mask_rcnn_inception_v2_coco because of it’s speed. Download this and place it onto the object_detection folder. You can find the mask_rcnn_inception_v2_coco.config file inside the samples/config folder. Copy this folder and place it into object_detection/training folder. Now we have to make the following changes to this config file: Line 10: Change num_classes to the number of different objects you want the classifier to detect.(1 in this project’s case) Line 126: Change fine_tune_checkpoint to: fine_tune_checkpoint: "<path>/models/research/object_detection/mask_rcnn_inception_v2_coco_2018_01_28/model.ckpt" Line 142: Change input_path to the path of the train.records file: input_path: "<path>/models/research/object_detection/train.record" Line 158: Change input_path to the path of the test.records file: input_path: "<path>/models/research/object_detection/test.record" Line 144 and 160: Change label_map_path to the path of the label map: label_map_path: "<path>/models/research/object_detection/training/labelmap.pbtxt" Line 150: change num_example to the number of images in your test folder. 4. Training the Model: Run the following command to start the training of the model from the object_detection folder: python legacy/train.py --train_dir=training --pipeline_config_path=training/mask_rcnn_inception_v2_coco.config After every interval the model saves the checkpoints in the training folder. It is a good idea to let it train till the loss is below 0.05. The time taken will depend on how powerful your GPU is. You can view the progress of your model by opening another Anaconda Prompt Window and changing the directory to the object_detection folder and typing the following command: (pothole) C:\models\research\object_detection>tensorboard --logdir=training This will create a webpage on your local machine YourPCName:6006, which can be viewed through a web browser. The TensorBoard page provides information and graphs that show how the training is progressing. You can stop the training by pressing Ctrl+C while in the command prompt window. I recommend stopping after it has created the checkpoint in your folder this usually is done every 5–10 mins depending on your compute power. The checkpoint at the highest number of steps will be used to generate the frozen inference graph. 5. Exporting Inference Graph Create a folder called β€œinference_graph” inside object_detection folder. Now we can create the frozen inference graph(.pb file) inside this folder. To do this issue the following command: python export_inference_graph.py --input_type=image_tensor --pipeline_config_path=training/mask_rcnn_inception_v2_coco.config --trained_checkpoint_prefix=training/model.ckpt-2194 --output_directory=inference_graph This frozen inference graph is the object detection classifier. 6. Testing the newly trained classifier To test the newly trained classifer you can make changes to the already existing object_detection.ipynb file present in my Github Repo. Change the directory location for the labelmap, inference_graph, .config file and the test_images directory based on your location. You should get the follwing output: Flask is a micro web framework written in Python developed by Armin Ronacher. We are going to use Flask to deploy our custom trained object detection model. You can find the beginner tutorial on their official documentation. We are going to be using the code present in the object_detection.ipynb file in our Flask app. The code is called β€œapp.py” which is also present in my Github repository. In the beginning our app.py file we import our libraries and append our Python Path where the object detection api is located. Change this according to the location you have placed this file. The simple architecture of the Flask App can be described using the image below. We take the image as input to the Custom Trained Mask RCNN model which based on the accuracy score then decides whether to give the coordinates or not. You can run the β€œapp.py” by running the below command. python app.py After running the above command we should get the below output. Copy this onto your browser for the web application to render the HTML pages. I have made a terrible job of this. You guys can create better interfaces or a better UI for this project by messing around with the HTML and CSS files. You can find all the output images below in the results section. This section just contains the various output images of the project. This is the first page after copying the URL from Anaconda Prompt onto your browser of your choice. )This is the page after selecting and uploading an image of your choice. This is the page after clicking on the submit button. Notice how the button below appears only when the score is above is 50%. After clicking on the button below the output result that states to get the current position. I have zoomed out the map quite a bit to not reveal my location but you can get really precise and zoomed in coordinates. You can try to set up an architecture where you maintain a location database online so that the page can display those coordinates but for the purpose of this project we are just displaying the current location where the image was uploaded. So the image has to be taken and uploaded at the same spot. Thank you for reading to the end of this article. That is it for this tutorial. I hope you liked this article and that it helps in your Data Science journey. You can find more such articles on the blog section of my website. www.samdenlepcha.com Over 9300 deaths, 25000 injured in 3 years due to potholes β€” India TodayNienaber, S & Booysen, M.J. (Thinus) & Kroon, RS. (2015). Dataset of images used for pothole detection. 10.13140/RG.2.1.3646.1520How To Train an Object Detection Classifier for Multiple Objects Using TensorFlow (GPU) on Windows 10 β€” GithubCustom Mask RCNN using Tensorflow Object Detection API β€” MediumTrain a Mask R-CNN model with the Tensorflow Object Detection API β€” Gilbert TannerHTML Geolocation API β€” w3schools Over 9300 deaths, 25000 injured in 3 years due to potholes β€” India Today Nienaber, S & Booysen, M.J. (Thinus) & Kroon, RS. (2015). Dataset of images used for pothole detection. 10.13140/RG.2.1.3646.1520 How To Train an Object Detection Classifier for Multiple Objects Using TensorFlow (GPU) on Windows 10 β€” Github Custom Mask RCNN using Tensorflow Object Detection API β€” Medium Train a Mask R-CNN model with the Tensorflow Object Detection API β€” Gilbert Tanner HTML Geolocation API β€” w3schools
[ { "code": null, "e": 286, "s": 172, "text": "A complete guide from installation and training to deploying a custom trained object detection model in a webapp." }, { "code": null, "e": 837, "s": 286, "text": "According to Wikipedia β€œA pothole is a depression in a road surface, usually asphalt pavement, where traffic has removed broken pieces of the pavement”. Edmonton the β€œself proclaimed pothole capital” in Alberta, Canada reportedly spends $4.8 million on 450,000 potholes annually, as of 2015. In India every year approximately 1100 lives are lost to accidents caused by potholes source. Ordinary citizens do not have the means of communicating or reporting the bad roads to the concerned authorities while the authorities lay unaware of the situation." }, { "code": null, "e": 1605, "s": 837, "text": "Therefore, several organizations have been trying to develop tools (like web apps) where the citizens can report the potholes to the concerned authorities. There are several hackathons that have taken place with this project in mind as one of the objectives. Seeing this as a growing concern, in this project to address this problem the aim is to develop a simple interface that uses the state of the art object detection technology to detect potholes in real time and report them using Google Maps. This article will take you through the steps required to build your very own pothole detection system. The deployment medium for this project will be on smartphones which are used by 500 million+ people in India according to Newzoo’s 2019 Global Mobile Market Report." }, { "code": null, "e": 1617, "s": 1605, "text": "Tools Used:" }, { "code": null, "e": 1629, "s": 1617, "text": "Python 3.6+" }, { "code": null, "e": 1661, "s": 1629, "text": "Tensorflow Object Detection API" }, { "code": null, "e": 1683, "s": 1661, "text": "Pixel Annotation Tool" }, { "code": null, "e": 1708, "s": 1683, "text": "Anaconda Package Manager" }, { "code": null, "e": 1714, "s": 1708, "text": "Flask" }, { "code": null, "e": 1762, "s": 1714, "text": "The workflow of the Project will be as follows:" }, { "code": null, "e": 1780, "s": 1762, "text": "Environment Setup" }, { "code": null, "e": 1798, "s": 1780, "text": "Dataset Gathering" }, { "code": null, "e": 1813, "s": 1798, "text": "Model Training" }, { "code": null, "e": 1835, "s": 1813, "text": "Deployment with Flask" }, { "code": null, "e": 1843, "s": 1835, "text": "Results" }, { "code": null, "e": 2120, "s": 1843, "text": "In the beginning, we will set up a new Anaconda environment and install all the necessary packages required for this project. Anaconda is a popular python package manager alongside β€œpip”. If you have not installed prior to this project please install it using the below links." }, { "code": null, "e": 2404, "s": 2120, "text": "It is a fairly straight forward installation and should not take long. You can install the Miniconda if you have some experience using the command line but if you want the GUI you can install the Anaconda Navigator with all the additional packages (this will take longer to install)." }, { "code": null, "e": 2513, "s": 2404, "text": "After this open β€œAnaconda Prompt” from your start menu and follow the rest of the installation instructions:" }, { "code": null, "e": 2543, "s": 2513, "text": "Create the conda environment." }, { "code": null, "e": 2573, "s": 2543, "text": "Create the conda environment." }, { "code": null, "e": 2628, "s": 2573, "text": "(base) C:\\Users>conda create --name pothole python=3.6" }, { "code": null, "e": 2673, "s": 2628, "text": "2. Activate the environment and upgrade pip." }, { "code": null, "e": 2760, "s": 2673, "text": "(base) C:\\Users>activate pothole(pothole) C:\\Users>python -m pip install --upgrade pip" }, { "code": null, "e": 2835, "s": 2760, "text": "3. Install the other necessary packages by issuing the following commands:" }, { "code": null, "e": 3254, "s": 2835, "text": "(pothole) C:\\Users>conda install -c anaconda protobuf(pothole) C:\\Users>pip install pillow(pothole) C:\\Users>pip install lxml(pothole) C:\\Users>pip install Cython(pothole) C:\\Users>pip install contextlib2(pothole) C:\\Users>pip install jupyter(pothole) C:\\Users>pip install matplotlib(pothole) C:\\Users>pip install opencv-python(pothole) C:\\Users>pip install labelme(pothole) C:\\Users>pip install tensorflow-gpu==1.15.2" }, { "code": null, "e": 3599, "s": 3254, "text": "4. Clone or download the tensorflow object detection api repository from Github. For the purpose of this project, we are using tensorflow version 1.15.2. Note Always make sure the tensorflow version installed and the tensorflow object detection api repository version is the same. Run the following command or download this repository manually." }, { "code": null, "e": 3669, "s": 3599, "text": "(pothole) C:\\Users>git clone https://github.com/tensorflow/models.git" }, { "code": null, "e": 3784, "s": 3669, "text": "Place these folders in a folder called β€œmodels”. You can place this β€œmodels” folder in a directory of your choice." }, { "code": null, "e": 3859, "s": 3784, "text": "5. Configure the PYTHONPATH environment variable and install the COCO api:" }, { "code": null, "e": 4047, "s": 3859, "text": "(pothole) C:\\Users>set PYTHONPATH=C:\\models;C:\\models\\research;C:\\models\\research\\slim(pothole) C:\\Users>pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI" }, { "code": null, "e": 4085, "s": 4047, "text": "6. Compile Protobufs and run setup.py" }, { "code": null, "e": 4157, "s": 4085, "text": "In the Anaconda Prompt change directories to \\models\\research directory" }, { "code": null, "e": 4198, "s": 4157, "text": "(pothole) C:\\Users>cd C:\\models\\research" }, { "code": null, "e": 4231, "s": 4198, "text": "Run the following lines of code:" }, { "code": null, "e": 5713, "s": 4231, "text": "protoc --python_out=. .\\object_detection\\protos\\anchor_generator.proto .\\object_detection\\protos\\argmax_matcher.proto .\\object_detection\\protos\\bipartite_matcher.proto .\\object_detection\\protos\\box_coder.proto .\\object_detection\\protos\\box_predictor.proto .\\object_detection\\protos\\eval.proto .\\object_detection\\protos\\faster_rcnn.proto .\\object_detection\\protos\\faster_rcnn_box_coder.proto .\\object_detection\\protos\\grid_anchor_generator.proto .\\object_detection\\protos\\hyperparams.proto .\\object_detection\\protos\\image_resizer.proto .\\object_detection\\protos\\input_reader.proto .\\object_detection\\protos\\losses.proto .\\object_detection\\protos\\matcher.proto .\\object_detection\\protos\\mean_stddev_box_coder.proto .\\object_detection\\protos\\model.proto .\\object_detection\\protos\\optimizer.proto .\\object_detection\\protos\\pipeline.proto .\\object_detection\\protos\\post_processing.proto .\\object_detection\\protos\\preprocessor.proto .\\object_detection\\protos\\region_similarity_calculator.proto .\\object_detection\\protos\\square_box_coder.proto .\\object_detection\\protos\\ssd.proto .\\object_detection\\protos\\ssd_anchor_generator.proto .\\object_detection\\protos\\string_int_label_map.proto .\\object_detection\\protos\\train.proto .\\object_detection\\protos\\keypoint_box_coder.proto .\\object_detection\\protos\\multiscale_anchor_generator.proto .\\object_detection\\protos\\graph_rewriter.proto .\\object_detection\\protos\\calibration.proto .\\object_detection\\protos\\flexible_grid_anchor_generator.proto" }, { "code": null, "e": 5792, "s": 5713, "text": "If it gives an error that the protobuf file could not be found run this after:" }, { "code": null, "e": 5846, "s": 5792, "text": "protoc object_detection/protos/*.proto --python_out=." }, { "code": null, "e": 5894, "s": 5846, "text": "Finally, we need to run the following commands:" }, { "code": null, "e": 5999, "s": 5894, "text": "(pothole) C:\\models\\research> python setup.py build(pothole) C:\\models\\research> python setup.py install" }, { "code": null, "e": 6157, "s": 5999, "text": "8. You can test if everything is working out by running the IPython Notebook present in the object_detection folder called β€œobject_detection_tutorial.ipynb”." }, { "code": null, "e": 6300, "s": 6157, "text": "(pothole) C:\\models\\research>cd object_detection(pothole) C:\\models\\research\\object_detection>jupyter notebook object_detection_tutorial.ipynb" }, { "code": null, "e": 6368, "s": 6300, "text": "You can use my repository for supporting material for this article." }, { "code": null, "e": 6379, "s": 6368, "text": "github.com" }, { "code": null, "e": 6559, "s": 6379, "text": "As always, at the beginning of any Data Science or AI Project after the problem statement has been identified we move on to gathering the data or in this case images for training." }, { "code": null, "e": 6833, "s": 6559, "text": "To train a robust model we need to use a lot of pictures but with variation as well. That means the potholes must be present at various angles or shapes so that our model does not lean on to one variation or in other words overfits and does not generalize for other images." }, { "code": null, "e": 7161, "s": 6833, "text": "You can use the images that you have taken personally or download them from the Internet like me. For this project, the idea is to detect potholes so we would not be segmenting them out based on severity but that does leave something for the future scope as well. The following data sources were used for building this project:" }, { "code": null, "e": 7168, "s": 7161, "text": "Kaggle" }, { "code": null, "e": 7182, "s": 7168, "text": "Research Gate" }, { "code": null, "e": 7467, "s": 7182, "text": "We need to resize the images so that the model can be trained using these resized images like 800 x 600 in this project (Unless you have unlimited GPU compute power). Use either the command prompt or anaconda prompt or any other IDE to run this script. For example in Anaconda Prompt:" }, { "code": null, "e": 7513, "s": 7467, "text": "(pothole) C:\\Users> python DatasetCreation.py" }, { "code": null, "e": 7677, "s": 7513, "text": "Now that we have gathered the dataset we need to label the images so that the model understands what is a pothole. To label the images we need a labeling software." }, { "code": null, "e": 7848, "s": 7677, "text": "For the purpose of the project, I have used labelme as it is fairly simple to use. In your anaconda environment type β€œlabelme” and the software should open up like below." }, { "code": null, "e": 7875, "s": 7848, "text": "(pothole) C:\\Users>labelme" }, { "code": null, "e": 8230, "s": 7875, "text": "Open your image from your directory and click on Create Polygon and start labeling your images. Labelme saves your labels as json files with the same name as the image name. Place the json in the same directory as your images. An example of Labelme(right) along with Pixel Annotation Tool(left) is shown below. For this project I have labeled 400 images." }, { "code": null, "e": 8248, "s": 8230, "text": "Create TFRecords:" }, { "code": null, "e": 8266, "s": 8248, "text": "Create TFRecords:" }, { "code": null, "e": 8735, "s": 8266, "text": "After labeling our entire dataset we now have to generate TFRecords which serves as input for our model training. But before that we need to convert the json labelme labels into COCO format. I have taken the script provided by Gilber Tanner in his tutorial to perform this. You can also find this in my Github Repository labeled β€œlabelme2coco.py”. Download this and place it onto the directory where your Train/ Test images are located. Now run the following commands:" }, { "code": null, "e": 8948, "s": 8735, "text": "(pothole) C:\\Users\\models\\research\\object_detection\\images>python labelme2coco.py train --output train.json(pothole) C:\\Users\\models\\research\\object_detection\\images>python labelme2coco.py test --output test.json" }, { "code": null, "e": 9175, "s": 8948, "text": "Now that the train/test data is in the COCO format we can now create the TFRecords using the create_coco_tf_record.py also created by Gilber Tanner. This script also needs to be placed and run from the object_detection folder." }, { "code": null, "e": 9402, "s": 9175, "text": "python create_coco_tf_record.py --logtostderr --train_image_dir=images/train --test_image_dir=images/test --train_annotations_file=images/train.json --test_annotations_file=images/test.json --include_masks=True --output_dir=./" }, { "code": null, "e": 9480, "s": 9402, "text": "You should find train.record and test.record in your object_detection folder." }, { "code": null, "e": 9502, "s": 9480, "text": "2. Creating Label Map" }, { "code": null, "e": 9707, "s": 9502, "text": "The label map links class names to ID numbers. Use a text editor like Sublime Text to create a β€œlabelmap.pbtxt” and store it inside object_detection/training folder. Inside the folder write the following:" }, { "code": null, "e": 9739, "s": 9707, "text": "item { id: 1 name: 'Pothole'}" }, { "code": null, "e": 9900, "s": 9739, "text": "You can define as much as you want depending on the classes you want to detect but for the purpose of this project we are only interested in detecting potholes." }, { "code": null, "e": 10079, "s": 9900, "text": "This id should match with the id mentioned in your train.json and test.json files. Notice how it one number greater i.e here it is id: 0 but we mention id:1 in the labelmap file." }, { "code": null, "e": 10184, "s": 10079, "text": "\"categories\": [ { \"supercategory\": \"Pothole\", \"id\": 0, \"name\": \"Pothole\" },]," }, { "code": null, "e": 10225, "s": 10184, "text": "3. Creating Training Configuration File:" }, { "code": null, "e": 10765, "s": 10225, "text": "Now we need to create a training configuration file. From the tensorflow model zoo there are a variety of tensorflow models available for Mask RCNN but for the purpose of this project we are gonna use the mask_rcnn_inception_v2_coco because of it’s speed. Download this and place it onto the object_detection folder. You can find the mask_rcnn_inception_v2_coco.config file inside the samples/config folder. Copy this folder and place it into object_detection/training folder. Now we have to make the following changes to this config file:" }, { "code": null, "e": 10889, "s": 10765, "text": "Line 10: Change num_classes to the number of different objects you want the classifier to detect.(1 in this project’s case)" }, { "code": null, "e": 10931, "s": 10889, "text": "Line 126: Change fine_tune_checkpoint to:" }, { "code": null, "e": 11045, "s": 10931, "text": "fine_tune_checkpoint: \"<path>/models/research/object_detection/mask_rcnn_inception_v2_coco_2018_01_28/model.ckpt\"" }, { "code": null, "e": 11112, "s": 11045, "text": "Line 142: Change input_path to the path of the train.records file:" }, { "code": null, "e": 11179, "s": 11112, "text": "input_path: \"<path>/models/research/object_detection/train.record\"" }, { "code": null, "e": 11245, "s": 11179, "text": "Line 158: Change input_path to the path of the test.records file:" }, { "code": null, "e": 11311, "s": 11245, "text": "input_path: \"<path>/models/research/object_detection/test.record\"" }, { "code": null, "e": 11381, "s": 11311, "text": "Line 144 and 160: Change label_map_path to the path of the label map:" }, { "code": null, "e": 11463, "s": 11381, "text": "label_map_path: \"<path>/models/research/object_detection/training/labelmap.pbtxt\"" }, { "code": null, "e": 11537, "s": 11463, "text": "Line 150: change num_example to the number of images in your test folder." }, { "code": null, "e": 11560, "s": 11537, "text": "4. Training the Model:" }, { "code": null, "e": 11655, "s": 11560, "text": "Run the following command to start the training of the model from the object_detection folder:" }, { "code": null, "e": 11766, "s": 11655, "text": "python legacy/train.py --train_dir=training --pipeline_config_path=training/mask_rcnn_inception_v2_coco.config" }, { "code": null, "e": 11962, "s": 11766, "text": "After every interval the model saves the checkpoints in the training folder. It is a good idea to let it train till the loss is below 0.05. The time taken will depend on how powerful your GPU is." }, { "code": null, "e": 12136, "s": 11962, "text": "You can view the progress of your model by opening another Anaconda Prompt Window and changing the directory to the object_detection folder and typing the following command:" }, { "code": null, "e": 12212, "s": 12136, "text": "(pothole) C:\\models\\research\\object_detection>tensorboard --logdir=training" }, { "code": null, "e": 12417, "s": 12212, "text": "This will create a webpage on your local machine YourPCName:6006, which can be viewed through a web browser. The TensorBoard page provides information and graphs that show how the training is progressing." }, { "code": null, "e": 12739, "s": 12417, "text": "You can stop the training by pressing Ctrl+C while in the command prompt window. I recommend stopping after it has created the checkpoint in your folder this usually is done every 5–10 mins depending on your compute power. The checkpoint at the highest number of steps will be used to generate the frozen inference graph." }, { "code": null, "e": 12768, "s": 12739, "text": "5. Exporting Inference Graph" }, { "code": null, "e": 12956, "s": 12768, "text": "Create a folder called β€œinference_graph” inside object_detection folder. Now we can create the frozen inference graph(.pb file) inside this folder. To do this issue the following command:" }, { "code": null, "e": 13170, "s": 12956, "text": "python export_inference_graph.py --input_type=image_tensor --pipeline_config_path=training/mask_rcnn_inception_v2_coco.config --trained_checkpoint_prefix=training/model.ckpt-2194 --output_directory=inference_graph" }, { "code": null, "e": 13234, "s": 13170, "text": "This frozen inference graph is the object detection classifier." }, { "code": null, "e": 13274, "s": 13234, "text": "6. Testing the newly trained classifier" }, { "code": null, "e": 13410, "s": 13274, "text": "To test the newly trained classifer you can make changes to the already existing object_detection.ipynb file present in my Github Repo." }, { "code": null, "e": 13578, "s": 13410, "text": "Change the directory location for the labelmap, inference_graph, .config file and the test_images directory based on your location. You should get the follwing output:" }, { "code": null, "e": 13803, "s": 13578, "text": "Flask is a micro web framework written in Python developed by Armin Ronacher. We are going to use Flask to deploy our custom trained object detection model. You can find the beginner tutorial on their official documentation." }, { "code": null, "e": 14165, "s": 13803, "text": "We are going to be using the code present in the object_detection.ipynb file in our Flask app. The code is called β€œapp.py” which is also present in my Github repository. In the beginning our app.py file we import our libraries and append our Python Path where the object detection api is located. Change this according to the location you have placed this file." }, { "code": null, "e": 14246, "s": 14165, "text": "The simple architecture of the Flask App can be described using the image below." }, { "code": null, "e": 14453, "s": 14246, "text": "We take the image as input to the Custom Trained Mask RCNN model which based on the accuracy score then decides whether to give the coordinates or not. You can run the β€œapp.py” by running the below command." }, { "code": null, "e": 14467, "s": 14453, "text": "python app.py" }, { "code": null, "e": 14827, "s": 14467, "text": "After running the above command we should get the below output. Copy this onto your browser for the web application to render the HTML pages. I have made a terrible job of this. You guys can create better interfaces or a better UI for this project by messing around with the HTML and CSS files. You can find all the output images below in the results section." }, { "code": null, "e": 14896, "s": 14827, "text": "This section just contains the various output images of the project." }, { "code": null, "e": 14996, "s": 14896, "text": "This is the first page after copying the URL from Anaconda Prompt onto your browser of your choice." }, { "code": null, "e": 15069, "s": 14996, "text": ")This is the page after selecting and uploading an image of your choice." }, { "code": null, "e": 15196, "s": 15069, "text": "This is the page after clicking on the submit button. Notice how the button below appears only when the score is above is 50%." }, { "code": null, "e": 15713, "s": 15196, "text": "After clicking on the button below the output result that states to get the current position. I have zoomed out the map quite a bit to not reveal my location but you can get really precise and zoomed in coordinates. You can try to set up an architecture where you maintain a location database online so that the page can display those coordinates but for the purpose of this project we are just displaying the current location where the image was uploaded. So the image has to be taken and uploaded at the same spot." }, { "code": null, "e": 15938, "s": 15713, "text": "Thank you for reading to the end of this article. That is it for this tutorial. I hope you liked this article and that it helps in your Data Science journey. You can find more such articles on the blog section of my website." }, { "code": null, "e": 15959, "s": 15938, "text": "www.samdenlepcha.com" }, { "code": null, "e": 16448, "s": 15959, "text": "Over 9300 deaths, 25000 injured in 3 years due to potholes β€” India TodayNienaber, S & Booysen, M.J. (Thinus) & Kroon, RS. (2015). Dataset of images used for pothole detection. 10.13140/RG.2.1.3646.1520How To Train an Object Detection Classifier for Multiple Objects Using TensorFlow (GPU) on Windows 10 β€” GithubCustom Mask RCNN using Tensorflow Object Detection API β€” MediumTrain a Mask R-CNN model with the Tensorflow Object Detection API β€” Gilbert TannerHTML Geolocation API β€” w3schools" }, { "code": null, "e": 16521, "s": 16448, "text": "Over 9300 deaths, 25000 injured in 3 years due to potholes β€” India Today" }, { "code": null, "e": 16651, "s": 16521, "text": "Nienaber, S & Booysen, M.J. (Thinus) & Kroon, RS. (2015). Dataset of images used for pothole detection. 10.13140/RG.2.1.3646.1520" }, { "code": null, "e": 16762, "s": 16651, "text": "How To Train an Object Detection Classifier for Multiple Objects Using TensorFlow (GPU) on Windows 10 β€” Github" }, { "code": null, "e": 16826, "s": 16762, "text": "Custom Mask RCNN using Tensorflow Object Detection API β€” Medium" }, { "code": null, "e": 16909, "s": 16826, "text": "Train a Mask R-CNN model with the Tensorflow Object Detection API β€” Gilbert Tanner" } ]
Scraping 1000’s of News Articles using 10 simple steps | by Kajal Yadav | Towards Data Science
Web Scraping Series: Using Python and Software Part-1: Scraping web pages without using Software: Python Part-2: Scraping web Pages using Software: Octoparse Table Of Content 1.Introduction 1.1 Why This article? 1.2 Who should read this article? 2. Overview 2.1 A brief introduction to webpage design and HTML 2.2 Web-scraping using BeautifulSoup in PYTHON 3. Suggestion & conclusion 3.1Full Code Aim of this article is to scrape news articles from different websites using Python. Generally, web scraping involves accessing numerous websites and collecting data from them. However, we can limit ourselves to collect large amounts of information from a single source and use it as a dataset. Web Scraping is a technique employed to extract large amounts of data from websites whereby the data is extracted and saved to a local file in your computer or to a database in table (spreadsheet) format. So, I get motivated to do web scraping while working on my Machine-Learning project on Fake News Detection System. Whenever we begin a machine learning project, the first thing that we need is a dataset. While there are many datasets that you can find online with varied information, sometimes you wish to extract data on your own and begin your own investigation. I was needed with a dataset that I couldn’t able to find anywhere according to my need. So this motivated me to make my own Dataset for my project accordingly. And that’s how I did my project from the scratch. My Project was basically based on classifying different news articles into two main categories FAKE & REAL. For this project, The first task was to get a dataset which is already labeled with β€œFAKE”, so this can be achieved by scraping data from some verified & certified news websites, on which we can rely on for fact of news articles and it is really a very difficult task to get genuine β€œFAKE NEWS”.I go through these news websites to get my FAKE-NEWS Dataset Boom Live Snopes Politifact AllSides But honestly speaking, I end up scraping data from one website i.e., Politifact.And there is a strong reason to do so, As you go through the listed links up there, you will conclude that we needed a dataset with already labeled category i.e., β€œFAKE” but also we don’t want our news articles to be in a modified form as such. We want to extract a raw news article without any keywords specifying whether the given news article in a dataset is β€œFAKE” or not.So for example, If you go through the link β€œBoomLive.in”, you will find that the news articles specifying β€œFAKE” are not in its actual form and altered on basis of some analysis of the fact-checking team. So this altered text on model training in ML will give us a biased result every time and the model that we made using this kind of dataset will result into a dumb one which can only predict news articles having keywords like β€œFAKE”, β€œDID?”, β€œIS?” in it and will not be going to perform well on a new testing set of data.That’s why we use Politifact to scrape our β€œFAKE-NEWS DATASET”. The second task was to create a β€œREAL-NEWS” dataset, So that was easy if you are scraping news-articles from trusted or verified news websites like β€œTOI”, β€œIndiaToday”, β€œTheHindu” & so many...So we can trust these websites that they are listing the factual/actual data and even if not, then we are assuming the same to be true and will train our model accordingly.But for my project, I scrape data for real and fake from one website only (i.e., Politifact.com), since I am getting what I needed from it, and also it is advisable when we are scraping data using python to use only one website at a time. Although you can scrape multiple pages of that particular website altogether in one module by just running an outer for loop. Whoever is working on some projects where you need to scrape data in thousands, this article is definitely for you πŸ˜ƒ. It doesn’t matter if you are from a programming background or not, because there are many times when people other than programmers from different backgrounds needed data as per their project, survey, or whatsoever purpose. But non-programmers find it difficult to understand any programming language, So I will make scrapping easy for them too by introducing some software from which they can scrape any kind of data in a huge amount easily. Although Scraping using python is not that difficult if you follow along with me while reading this blog 😎, the only thing that you need to focus on is the HTML source code of a webpage. Once, you able to understand how webpages are written in HTML and able to identify attributes and elements of your interest, you can scrape any website. For non-programmers, if you want to do web-scraping using python, just focus on HTML code mainly, python syntax is not that difficult to understand, It’s just some libraries, some functions, and keywords that you needed to remember and understand. So I tried to explain every step with transparency, I hope at the end of this series, you will be able to scrape different types of the layout of webpages. This post covers the first part: News articles web scraping using PYTHON. We’ll create a script that scrapes the latest news articles from different newspapers and stores the text, which will be fed into the model afterward to get a prediction of its category. If we want to be able to extract news articles (or, in fact, any other kind of text) from a website, the first step is to know how a website works. We will follow an example to understand this: When we insert an URL into the web browser (i.e. Google Chrome, Firefox, etc...) and access to it, what we see is the combination of three technologies: HTML (HyperText Markup Language): it is the standard language for adding content to a website. It allows us to insert text, images, and other things to our site. In one word, HTML defines the content of every webpage on the internet. CSS (Cascading Style Sheets): this language allows us to set the visual design of a website. This means it determines the style/presentation of a webpage including colors, layouts, and fonts. JavaScript: JavaScript is a dynamic computer programming language. It allows us to make the content and the style interactive & provides a dynamic interface between client-side script and user. Note that these three are programming languages. They will allow us to create and manipulate every aspect of the design of a webpage. Let’s illustrate these concepts with an example. When we visit the Politifact page, we see the following: If we disabled JavaScript, we would not be able to use this pop-up anymore, as you can see, we are not able to see a video pop up window now: If we delete CSS element from our web-page after finding it using ctrl+F on inspect window, we will see something like this: So, At this point, I will be going to ask you a question. β€œIf you want to extract the content of a webpage via web-scraping, where do you need to look up?” So, At this point, I hope you guys are clear about what kind of source code do we need to scrape. Yeah, you are absolutely right, If you are thinking about HTML 😎 So, the last step before performing web scraping methods is to understand the bit of the HTML language. HTML HTML language is a β€œhypertext markup language” that defines the content of a webpage and constitute of elements and attributes, for scraping data, you should be familiar with inspecting those elements. An element could be a heading, paragraph, division, anchor tag & so many... An attribute could be that the heading is in bold letters.These tags are represented with an opening symbol <tag> and closing symbol</tag>e.g., <p>This is paragraph.</p><h1><b>This is heading one in bold letters</b></h1> Enough talk, show me the code. We will first begin with installing necessary packages: 1. beautifulsoup4To install it, Please type the following code into your python distribution. ! pip install beautifulsoup4 BeautifulSoup under bs4 package is a library used to parse HTML & XML docs into python in a very easy & convenient way and access its elements by identifying them with their tags and attributes. It is very easy to use, yet very powerful package to extract any kind of data from the internet in just 5–6 lines. 2. requests To install it, use the following command in your IDE or use this command without an exclamation mark in a command shell. ! pip install requests So as to provide BeautifulSoup with the HTML code of any page, we will need with the requests module. 3. urllibTo install it, use the following command: ! pip install urllib urllib module is the URL handling module for python. It is used to fetch URLs(Uniform Resource Locator) Although, here we are using this module for a different purpose, to call libraries like: time(using which we can call sleep() function to delay or suspends execution for the given number of seconds. sys(It is used here to get exception info like type of error, error object, info about the error. Now we will import all the required libraries:1. BeautifulSoupTo import it, use the following command onto your IDE from bs4 import BeautifulSoup This library helps us with getting HTML structure of any page that we want to work with and provides functions to access specific elements and extract relevant info. 2. urllibTo import it, type following command import urllib.request,sys,time urllib.request: It helps in defining functions & classes which help in opening URLs urllib.sys: Its functions & classes helps us with retrieving exception info. urllib.time : Python has a module named time which provides several useful functions to handle time-related tasks. One of the popular functions among them is sleep(). 3. requestsTo import it, just type import before this library keyword. import requests This module allows us to send the HTTP requests to web-server using python. (HTTP messages consist of requests from client to server and responses from server to client.) 4. pandas import pandas as pd It is a high-level data-manipulation tool that we needed to visualize our structured scraped data. will use this library to make DataFrame(Key data structure of this library). DataFrames allow us to store and manipulate tabular data in rows of observations and columns of variables. import urllib.request,sys,timefrom bs4 import BeautifulSoupimport requestsimport pandas as pd with the request module, we can get the HTML content and store into the page variable.Make a simple get request(just fetching a page) #url of the page that we want to Scarpe#+str() is used to convert int datatype of the page no. and concatenate that to a URL for pagination purposes.URL = 'https://www.politifact.com/factchecks/list/?page='+str(page)#Use the browser to get the URL. This is a suspicious command that might blow up.page = requests.get(url) Since, requests.get(url) is a suspicious command and might throw an exception, we will call it in a try-except block try: # this might throw an exception if something goes wrong. page=requests.get(url) # this describes what to do if an exception is thrown except Exception as e: # get the exception information error_type, error_obj, error_info = sys.exc_info() #print the link that cause the problem print ('ERROR FOR LINK:',url) #print error info and line that threw the exception print (error_type, 'Line:', error_info.tb_lineno) continue We will also use an outer for loop for pagination purposes. I. See what response code the server sent back (useful fordetecting 4XX or 5XX errors. page.status_code Output: The HTTP 200 OK success status response code indicates that the request has succeeded. II. Access the full response as text(get the HTML of the page in a big string) page.text Output: It will return the HTML content of a response object in Unicode.Alternative: page.content Output: Output: whereas, It will return the content of response in bytes. III. Look for a specific substring of text within the response. if "Politifact" in page.text: print("Yes, Scarpe it") IV. Check the response’s Content-Type (see if you got back HTML,JSON, XML, etc) print (page.headers.get("content-type", "unknown")) Output: Next with the time module, we can call sleep(2) function with a value of 2 seconds. Here it delayed sending requests to a web-server by 2 seconds. time.sleep(2) The sleep() function suspends execution of the current thread for a given number of seconds. Now that you’ve made your HTTP request and gotten some HTML content, it’s time to parse it so that you can extract the values you’re looking for. A)Using Regular ExpressionsUsing Regular Expressions for looking up HTML content is strongly not recommended at all. However, regular expressions are still useful for finding specific string patterns like prices, email addresses, or phone numbers. Run a regular expression on the response text to look for specific string patterns: import re # put this at the top of the file...print(re.findall(r'\$[0-9,.]+', page.text)) Output: B)Using BeautifulSoup's object SoupBeautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It commonly saves programmers hours or days of work soup = BeautifulSoup(page.text, "html.parser") The below-listed command will Look for all the tags e.g.,<li> with specific attribute 'o-listicle__item' links=soup.find_all('li',attrs={'class':'o-listicle__item'}) INSPECTING WEBPAGEFor being able to understand above code, you need to inspect the webpage & please do follow along:1)Go to listed URL above2)press ctrl+shift+I to inspect it.3)This is how your 'Inspect window' will look like: press ctrl+shift+C to select an element in the page to inspect it or go to the leftmost arrow in the header of the Inspect window. 4)For getting above specific element & attribute in inspect window First, tries to go to every section of the webpage, & see changes on your inspect window, you will easily grasp the idea behind how webpages are working and which element is what and what particular attribute is contributing to the webpage. When done with the above step, now I am assuming that you can understand the working of the above element<li> and it's attribute. Since I needed the news section of a particular article, I go to that article section by selecting the inspect element option in the inspect window, It will highlight that article section on the web-page and its HTML source on Inspect Window. Voila!✨ Did you able to locate the same tag on your machine? If yes, You are all set to understand every bit of HTML tags whatsoever I have used in my code. Continuing with my code: πŸ˜… print(len(links)) This command will help you to inspect how many news articles are there on a given page.Help you understand accordingly, up to what level you need to paginate your loop for extracting huge data. Look for all anchor tags on the page (useful if you’re building a crawler and need to find the next pages to visit) links = soup.find_all("a") It will find a division tag under <li> tag where div tag should contain listed or specific attribute value. Here 'j' is an iterable variable that is iterating over response object 'Links' for all news articles listed on a given page. Statement = j.find("div",attrs={'class':'m-statement__quote'}) text.strip() function will return text contained within this tag and strip any kind of extra spaces, '\n','\t' from the text string object. Statement = j.find("div",attrs={'class':'m- statement__quote'}).text.strip() Bravo! 🌟 We have scraped the first attribute i.e., Statement of our dataset In the same division section, It will look for anchor tag and return with the value of the hypertext link. Again, strip() function is used to get our values organized so that our CSV file looks good. Link=j.find("div",attrs={'class':'m-statement__quote'}).find('a')['href'].strip() For getting Date attribute, you need to inspect web-page first, As there is a string contained with it. So calling text function without specifying indexing, you will get something like this But we don't need text other than the date, So I use indexing. Although you can clean your attribute later using some regex combinations. 'footer' is an element that contained the required text. Date = j.find('div',attrs={'class':'m-statement__body'}).find('footer').text[-14:-1].strip() Here also, I have done everything same as before except get(), which is extracting the content of an attribute passed(i.e., title) Source = j.find('div', attrs={'class':'m-statement__author'}).find('a').get('title').strip() Since, For my project, I needed a dataset that is not already altered and also, I need to know already about thousands of articles that which article lies in what category for my training data. and No-one can do that manually. So, On this website, I do find articles attached already with labels but the text is not retrievable because it is contained in an image. For this kind of specific task, you can use get() to retrieve particular text effectively. Here, I am passing 'alt' as an attribute to get(), which contains our Label text. Label = j.find('div', attrs ={'class':'m-statement__content'}).find('img',attrs={'class':'c-image__original'}).get('alt').strip() In the below lines of code, I have put all concepts together & tried to fetch details for five different attributes of my Dataset. for j in links: Statement = j.find("div",attrs={'class':'m-statement__quote'}).text.strip() Link=st.find('a')['href'].strip() Date = j.find('div',attrs={'class':'m-statement__body'}).find('footer').text[-14:-1].strip() Source = j.find('div', attrs={'class':'m-statement__author'}).find('a').get('title').strip() Label = j.find('div', attrs ={'class':'m-statement__content'}).find('img',attrs={'class':'c-image__original'}).get('alt').strip() frame.append([Statement,Link,Date,Source,Label])upperframe.extend(frame) Append each attribute value to an empty list 'frame' for each article frame.append([Statement,Link,Date,Source,Label]) Then, extend this list to an empty list 'upperframe' for each page. upperframe.extend(frame) If you wanted to visualize your data on Jupiter, you can use pandas DataFrame to do so. data=pd.DataFrame(upperframe, columns=['Statement','Link','Date','Source','Label'])data.head() A) Opening & writing to fileThe below command will help you to write CSV file and save it to your machine in the same directory as where your python file has been saved in filename="NEWS.csv" f=open(filename,"w") headers="Statement,Link,Date, Source, Label\n" f.write(headers) .... f.write(Statement.replace(",","^")+","+Link+","+Date.replace(",","^")+","+Source.replace(",","^")+","+Label.replace(",","^")+"\n") This line will write each attribute to a file with replacing any ',' with '^'. f.write(Statement.replace(",","^")+","+Link+","+Date.replace(",","^")+","+Source.replace(",","^")+","+Label.replace(",","^")+"\n") So, when you run this file on command shell, It will make a CSV file in your .py file directory.On opening it, you might see weird data if you don't use strip() while scraping. So do check it without applying strip() and if you don't replace '^' with ',', It will also look weird.So replace it using these simple steps: open your excel file (.csv file) Press ctrl+H (a pop-up window will come asking about find what & replace with) give '^' value to 'find what' field and give ',' value in 'replace with' field. Press Replace All Click Close & Woohoo!😍 You are all done with having your dataset in perfect form. and don't forget to close your file with the following command after done with both the for loops, f.close() and running the same code again and again might throw an error if it has already created a dataset using the file writing method. B) converting dataframe into csv file using to_csv()So, instead of this lengthy method, you can opt for another method: to_csv() is also used to convert the data frame into a CSV file and also provide an attribute to specify the path. path = 'C:\\Users\\Kajal\\Desktop\\KAJAL\\Project\\Datasets\\'data.to_csv(path+'NEWS.csv') To avoid the ambiguity and allow portability of your code you can use this: import osdata.to_csv(os.path.join(path,r'NEWS.csv')) this will append your CSV name to your destination path correctly. Although I will suggest using the first method using open file and writing to it and then close it, I know it is a bit lengthy & tacky to implement but at least it will not provide you with ambiguous data as to_csv method mostly does. See in the above image, how it extracts ambiguous data for the Statement attribute.So, instead of spending hours cleaning your data manually, I would suggest writing a few extra lines of code specified in the first method.Now, you are done with it.✌️ IMPORTANT NOTE: If you tried to copy-paste my source code for scraping different websites & run it, It might possible that it will throw an error. In fact, It will definitely throw an error because each webpage's layout is different & for that, you need to make changes accordingly. The Dataset: This article is the first part of the series of web-scraping and for those who come from non-technical backgrounds, read the second part of this series here. I hope you will find it useful and liked my article.πŸ˜‡ Please feel free to share your thoughts and hit me up with any queries you might have. You can reach me via the following : Subscribe to my YouTube channel for video content coming soon hereFollow me on MediumConnect and reach me on LinkedInFollow me on my blogging journey:- https://kajalyadav.com/Become a member:- https://techykajal.medium.com/membership Subscribe to my YouTube channel for video content coming soon here Follow me on Medium Connect and reach me on LinkedIn Follow me on my blogging journey:- https://kajalyadav.com/ Become a member:- https://techykajal.medium.com/membership Check out my other Blogs:
[ { "code": null, "e": 219, "s": 172, "text": "Web Scraping Series: Using Python and Software" }, { "code": null, "e": 277, "s": 219, "text": "Part-1: Scraping web pages without using Software: Python" }, { "code": null, "e": 330, "s": 277, "text": "Part-2: Scraping web Pages using Software: Octoparse" }, { "code": null, "e": 347, "s": 330, "text": "Table Of Content" }, { "code": null, "e": 362, "s": 347, "text": "1.Introduction" }, { "code": null, "e": 384, "s": 362, "text": "1.1 Why This article?" }, { "code": null, "e": 418, "s": 384, "text": "1.2 Who should read this article?" }, { "code": null, "e": 430, "s": 418, "text": "2. Overview" }, { "code": null, "e": 482, "s": 430, "text": "2.1 A brief introduction to webpage design and HTML" }, { "code": null, "e": 529, "s": 482, "text": "2.2 Web-scraping using BeautifulSoup in PYTHON" }, { "code": null, "e": 556, "s": 529, "text": "3. Suggestion & conclusion" }, { "code": null, "e": 569, "s": 556, "text": "3.1Full Code" }, { "code": null, "e": 864, "s": 569, "text": "Aim of this article is to scrape news articles from different websites using Python. Generally, web scraping involves accessing numerous websites and collecting data from them. However, we can limit ourselves to collect large amounts of information from a single source and use it as a dataset." }, { "code": null, "e": 1069, "s": 864, "text": "Web Scraping is a technique employed to extract large amounts of data from websites whereby the data is extracted and saved to a local file in your computer or to a database in table (spreadsheet) format." }, { "code": null, "e": 1522, "s": 1069, "text": "So, I get motivated to do web scraping while working on my Machine-Learning project on Fake News Detection System. Whenever we begin a machine learning project, the first thing that we need is a dataset. While there are many datasets that you can find online with varied information, sometimes you wish to extract data on your own and begin your own investigation. I was needed with a dataset that I couldn’t able to find anywhere according to my need." }, { "code": null, "e": 1752, "s": 1522, "text": "So this motivated me to make my own Dataset for my project accordingly. And that’s how I did my project from the scratch. My Project was basically based on classifying different news articles into two main categories FAKE & REAL." }, { "code": null, "e": 2108, "s": 1752, "text": "For this project, The first task was to get a dataset which is already labeled with β€œFAKE”, so this can be achieved by scraping data from some verified & certified news websites, on which we can rely on for fact of news articles and it is really a very difficult task to get genuine β€œFAKE NEWS”.I go through these news websites to get my FAKE-NEWS Dataset" }, { "code": null, "e": 2118, "s": 2108, "text": "Boom Live" }, { "code": null, "e": 2125, "s": 2118, "text": "Snopes" }, { "code": null, "e": 2136, "s": 2125, "text": "Politifact" }, { "code": null, "e": 2145, "s": 2136, "text": "AllSides" }, { "code": null, "e": 3190, "s": 2145, "text": "But honestly speaking, I end up scraping data from one website i.e., Politifact.And there is a strong reason to do so, As you go through the listed links up there, you will conclude that we needed a dataset with already labeled category i.e., β€œFAKE” but also we don’t want our news articles to be in a modified form as such. We want to extract a raw news article without any keywords specifying whether the given news article in a dataset is β€œFAKE” or not.So for example, If you go through the link β€œBoomLive.in”, you will find that the news articles specifying β€œFAKE” are not in its actual form and altered on basis of some analysis of the fact-checking team. So this altered text on model training in ML will give us a biased result every time and the model that we made using this kind of dataset will result into a dumb one which can only predict news articles having keywords like β€œFAKE”, β€œDID?”, β€œIS?” in it and will not be going to perform well on a new testing set of data.That’s why we use Politifact to scrape our β€œFAKE-NEWS DATASET”." }, { "code": null, "e": 3919, "s": 3190, "text": "The second task was to create a β€œREAL-NEWS” dataset, So that was easy if you are scraping news-articles from trusted or verified news websites like β€œTOI”, β€œIndiaToday”, β€œTheHindu” & so many...So we can trust these websites that they are listing the factual/actual data and even if not, then we are assuming the same to be true and will train our model accordingly.But for my project, I scrape data for real and fake from one website only (i.e., Politifact.com), since I am getting what I needed from it, and also it is advisable when we are scraping data using python to use only one website at a time. Although you can scrape multiple pages of that particular website altogether in one module by just running an outer for loop." }, { "code": null, "e": 4260, "s": 3919, "text": "Whoever is working on some projects where you need to scrape data in thousands, this article is definitely for you πŸ˜ƒ. It doesn’t matter if you are from a programming background or not, because there are many times when people other than programmers from different backgrounds needed data as per their project, survey, or whatsoever purpose." }, { "code": null, "e": 4479, "s": 4260, "text": "But non-programmers find it difficult to understand any programming language, So I will make scrapping easy for them too by introducing some software from which they can scrape any kind of data in a huge amount easily." }, { "code": null, "e": 4819, "s": 4479, "text": "Although Scraping using python is not that difficult if you follow along with me while reading this blog 😎, the only thing that you need to focus on is the HTML source code of a webpage. Once, you able to understand how webpages are written in HTML and able to identify attributes and elements of your interest, you can scrape any website." }, { "code": null, "e": 5223, "s": 4819, "text": "For non-programmers, if you want to do web-scraping using python, just focus on HTML code mainly, python syntax is not that difficult to understand, It’s just some libraries, some functions, and keywords that you needed to remember and understand. So I tried to explain every step with transparency, I hope at the end of this series, you will be able to scrape different types of the layout of webpages." }, { "code": null, "e": 5484, "s": 5223, "text": "This post covers the first part: News articles web scraping using PYTHON. We’ll create a script that scrapes the latest news articles from different newspapers and stores the text, which will be fed into the model afterward to get a prediction of its category." }, { "code": null, "e": 5632, "s": 5484, "text": "If we want to be able to extract news articles (or, in fact, any other kind of text) from a website, the first step is to know how a website works." }, { "code": null, "e": 5678, "s": 5632, "text": "We will follow an example to understand this:" }, { "code": null, "e": 5831, "s": 5678, "text": "When we insert an URL into the web browser (i.e. Google Chrome, Firefox, etc...) and access to it, what we see is the combination of three technologies:" }, { "code": null, "e": 6065, "s": 5831, "text": "HTML (HyperText Markup Language): it is the standard language for adding content to a website. It allows us to insert text, images, and other things to our site. In one word, HTML defines the content of every webpage on the internet." }, { "code": null, "e": 6257, "s": 6065, "text": "CSS (Cascading Style Sheets): this language allows us to set the visual design of a website. This means it determines the style/presentation of a webpage including colors, layouts, and fonts." }, { "code": null, "e": 6451, "s": 6257, "text": "JavaScript: JavaScript is a dynamic computer programming language. It allows us to make the content and the style interactive & provides a dynamic interface between client-side script and user." }, { "code": null, "e": 6585, "s": 6451, "text": "Note that these three are programming languages. They will allow us to create and manipulate every aspect of the design of a webpage." }, { "code": null, "e": 6691, "s": 6585, "text": "Let’s illustrate these concepts with an example. When we visit the Politifact page, we see the following:" }, { "code": null, "e": 6833, "s": 6691, "text": "If we disabled JavaScript, we would not be able to use this pop-up anymore, as you can see, we are not able to see a video pop up window now:" }, { "code": null, "e": 6958, "s": 6833, "text": "If we delete CSS element from our web-page after finding it using ctrl+F on inspect window, we will see something like this:" }, { "code": null, "e": 7016, "s": 6958, "text": "So, At this point, I will be going to ask you a question." }, { "code": null, "e": 7114, "s": 7016, "text": "β€œIf you want to extract the content of a webpage via web-scraping, where do you need to look up?”" }, { "code": null, "e": 7277, "s": 7114, "text": "So, At this point, I hope you guys are clear about what kind of source code do we need to scrape. Yeah, you are absolutely right, If you are thinking about HTML 😎" }, { "code": null, "e": 7381, "s": 7277, "text": "So, the last step before performing web scraping methods is to understand the bit of the HTML language." }, { "code": null, "e": 7386, "s": 7381, "text": "HTML" }, { "code": null, "e": 7588, "s": 7386, "text": "HTML language is a β€œhypertext markup language” that defines the content of a webpage and constitute of elements and attributes, for scraping data, you should be familiar with inspecting those elements." }, { "code": null, "e": 7664, "s": 7588, "text": "An element could be a heading, paragraph, division, anchor tag & so many..." }, { "code": null, "e": 7808, "s": 7664, "text": "An attribute could be that the heading is in bold letters.These tags are represented with an opening symbol <tag> and closing symbol</tag>e.g.," }, { "code": null, "e": 7885, "s": 7808, "text": "<p>This is paragraph.</p><h1><b>This is heading one in bold letters</b></h1>" }, { "code": null, "e": 7916, "s": 7885, "text": "Enough talk, show me the code." }, { "code": null, "e": 7972, "s": 7916, "text": "We will first begin with installing necessary packages:" }, { "code": null, "e": 8066, "s": 7972, "text": "1. beautifulsoup4To install it, Please type the following code into your python distribution." }, { "code": null, "e": 8095, "s": 8066, "text": "! pip install beautifulsoup4" }, { "code": null, "e": 8290, "s": 8095, "text": "BeautifulSoup under bs4 package is a library used to parse HTML & XML docs into python in a very easy & convenient way and access its elements by identifying them with their tags and attributes." }, { "code": null, "e": 8405, "s": 8290, "text": "It is very easy to use, yet very powerful package to extract any kind of data from the internet in just 5–6 lines." }, { "code": null, "e": 8417, "s": 8405, "text": "2. requests" }, { "code": null, "e": 8538, "s": 8417, "text": "To install it, use the following command in your IDE or use this command without an exclamation mark in a command shell." }, { "code": null, "e": 8561, "s": 8538, "text": "! pip install requests" }, { "code": null, "e": 8663, "s": 8561, "text": "So as to provide BeautifulSoup with the HTML code of any page, we will need with the requests module." }, { "code": null, "e": 8714, "s": 8663, "text": "3. urllibTo install it, use the following command:" }, { "code": null, "e": 8735, "s": 8714, "text": "! pip install urllib" }, { "code": null, "e": 8839, "s": 8735, "text": "urllib module is the URL handling module for python. It is used to fetch URLs(Uniform Resource Locator)" }, { "code": null, "e": 8928, "s": 8839, "text": "Although, here we are using this module for a different purpose, to call libraries like:" }, { "code": null, "e": 9038, "s": 8928, "text": "time(using which we can call sleep() function to delay or suspends execution for the given number of seconds." }, { "code": null, "e": 9136, "s": 9038, "text": "sys(It is used here to get exception info like type of error, error object, info about the error." }, { "code": null, "e": 9252, "s": 9136, "text": "Now we will import all the required libraries:1. BeautifulSoupTo import it, use the following command onto your IDE" }, { "code": null, "e": 9282, "s": 9252, "text": "from bs4 import BeautifulSoup" }, { "code": null, "e": 9448, "s": 9282, "text": "This library helps us with getting HTML structure of any page that we want to work with and provides functions to access specific elements and extract relevant info." }, { "code": null, "e": 9494, "s": 9448, "text": "2. urllibTo import it, type following command" }, { "code": null, "e": 9525, "s": 9494, "text": "import urllib.request,sys,time" }, { "code": null, "e": 9609, "s": 9525, "text": "urllib.request: It helps in defining functions & classes which help in opening URLs" }, { "code": null, "e": 9686, "s": 9609, "text": "urllib.sys: Its functions & classes helps us with retrieving exception info." }, { "code": null, "e": 9853, "s": 9686, "text": "urllib.time : Python has a module named time which provides several useful functions to handle time-related tasks. One of the popular functions among them is sleep()." }, { "code": null, "e": 9924, "s": 9853, "text": "3. requestsTo import it, just type import before this library keyword." }, { "code": null, "e": 9940, "s": 9924, "text": "import requests" }, { "code": null, "e": 10111, "s": 9940, "text": "This module allows us to send the HTTP requests to web-server using python. (HTTP messages consist of requests from client to server and responses from server to client.)" }, { "code": null, "e": 10121, "s": 10111, "text": "4. pandas" }, { "code": null, "e": 10141, "s": 10121, "text": "import pandas as pd" }, { "code": null, "e": 10240, "s": 10141, "text": "It is a high-level data-manipulation tool that we needed to visualize our structured scraped data." }, { "code": null, "e": 10424, "s": 10240, "text": "will use this library to make DataFrame(Key data structure of this library). DataFrames allow us to store and manipulate tabular data in rows of observations and columns of variables." }, { "code": null, "e": 10518, "s": 10424, "text": "import urllib.request,sys,timefrom bs4 import BeautifulSoupimport requestsimport pandas as pd" }, { "code": null, "e": 10652, "s": 10518, "text": "with the request module, we can get the HTML content and store into the page variable.Make a simple get request(just fetching a page)" }, { "code": null, "e": 10974, "s": 10652, "text": "#url of the page that we want to Scarpe#+str() is used to convert int datatype of the page no. and concatenate that to a URL for pagination purposes.URL = 'https://www.politifact.com/factchecks/list/?page='+str(page)#Use the browser to get the URL. This is a suspicious command that might blow up.page = requests.get(url)" }, { "code": null, "e": 11091, "s": 10974, "text": "Since, requests.get(url) is a suspicious command and might throw an exception, we will call it in a try-except block" }, { "code": null, "e": 11602, "s": 11091, "text": "try: # this might throw an exception if something goes wrong. page=requests.get(url) # this describes what to do if an exception is thrown except Exception as e: # get the exception information error_type, error_obj, error_info = sys.exc_info() #print the link that cause the problem print ('ERROR FOR LINK:',url) #print error info and line that threw the exception print (error_type, 'Line:', error_info.tb_lineno) continue" }, { "code": null, "e": 11662, "s": 11602, "text": "We will also use an outer for loop for pagination purposes." }, { "code": null, "e": 11749, "s": 11662, "text": "I. See what response code the server sent back (useful fordetecting 4XX or 5XX errors." }, { "code": null, "e": 11766, "s": 11749, "text": "page.status_code" }, { "code": null, "e": 11774, "s": 11766, "text": "Output:" }, { "code": null, "e": 11861, "s": 11774, "text": "The HTTP 200 OK success status response code indicates that the request has succeeded." }, { "code": null, "e": 11940, "s": 11861, "text": "II. Access the full response as text(get the HTML of the page in a big string)" }, { "code": null, "e": 11950, "s": 11940, "text": "page.text" }, { "code": null, "e": 11958, "s": 11950, "text": "Output:" }, { "code": null, "e": 12035, "s": 11958, "text": "It will return the HTML content of a response object in Unicode.Alternative:" }, { "code": null, "e": 12048, "s": 12035, "text": "page.content" }, { "code": null, "e": 12056, "s": 12048, "text": "Output:" }, { "code": null, "e": 12064, "s": 12056, "text": "Output:" }, { "code": null, "e": 12122, "s": 12064, "text": "whereas, It will return the content of response in bytes." }, { "code": null, "e": 12186, "s": 12122, "text": "III. Look for a specific substring of text within the response." }, { "code": null, "e": 12248, "s": 12186, "text": "if \"Politifact\" in page.text: print(\"Yes, Scarpe it\")" }, { "code": null, "e": 12328, "s": 12248, "text": "IV. Check the response’s Content-Type (see if you got back HTML,JSON, XML, etc)" }, { "code": null, "e": 12380, "s": 12328, "text": "print (page.headers.get(\"content-type\", \"unknown\"))" }, { "code": null, "e": 12388, "s": 12380, "text": "Output:" }, { "code": null, "e": 12535, "s": 12388, "text": "Next with the time module, we can call sleep(2) function with a value of 2 seconds. Here it delayed sending requests to a web-server by 2 seconds." }, { "code": null, "e": 12549, "s": 12535, "text": "time.sleep(2)" }, { "code": null, "e": 12642, "s": 12549, "text": "The sleep() function suspends execution of the current thread for a given number of seconds." }, { "code": null, "e": 12788, "s": 12642, "text": "Now that you’ve made your HTTP request and gotten some HTML content, it’s time to parse it so that you can extract the values you’re looking for." }, { "code": null, "e": 12905, "s": 12788, "text": "A)Using Regular ExpressionsUsing Regular Expressions for looking up HTML content is strongly not recommended at all." }, { "code": null, "e": 13036, "s": 12905, "text": "However, regular expressions are still useful for finding specific string patterns like prices, email addresses, or phone numbers." }, { "code": null, "e": 13120, "s": 13036, "text": "Run a regular expression on the response text to look for specific string patterns:" }, { "code": null, "e": 13211, "s": 13120, "text": "import re # put this at the top of the file...print(re.findall(r'\\$[0-9,.]+', page.text))" }, { "code": null, "e": 13219, "s": 13211, "text": "Output:" }, { "code": null, "e": 13502, "s": 13219, "text": "B)Using BeautifulSoup's object SoupBeautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It commonly saves programmers hours or days of work" }, { "code": null, "e": 13549, "s": 13502, "text": "soup = BeautifulSoup(page.text, \"html.parser\")" }, { "code": null, "e": 13654, "s": 13549, "text": "The below-listed command will Look for all the tags e.g.,<li> with specific attribute 'o-listicle__item'" }, { "code": null, "e": 13715, "s": 13654, "text": "links=soup.find_all('li',attrs={'class':'o-listicle__item'})" }, { "code": null, "e": 13942, "s": 13715, "text": "INSPECTING WEBPAGEFor being able to understand above code, you need to inspect the webpage & please do follow along:1)Go to listed URL above2)press ctrl+shift+I to inspect it.3)This is how your 'Inspect window' will look like:" }, { "code": null, "e": 14073, "s": 13942, "text": "press ctrl+shift+C to select an element in the page to inspect it or go to the leftmost arrow in the header of the Inspect window." }, { "code": null, "e": 14140, "s": 14073, "text": "4)For getting above specific element & attribute in inspect window" }, { "code": null, "e": 14381, "s": 14140, "text": "First, tries to go to every section of the webpage, & see changes on your inspect window, you will easily grasp the idea behind how webpages are working and which element is what and what particular attribute is contributing to the webpage." }, { "code": null, "e": 14511, "s": 14381, "text": "When done with the above step, now I am assuming that you can understand the working of the above element<li> and it's attribute." }, { "code": null, "e": 14762, "s": 14511, "text": "Since I needed the news section of a particular article, I go to that article section by selecting the inspect element option in the inspect window, It will highlight that article section on the web-page and its HTML source on Inspect Window. Voila!✨" }, { "code": null, "e": 14815, "s": 14762, "text": "Did you able to locate the same tag on your machine?" }, { "code": null, "e": 14911, "s": 14815, "text": "If yes, You are all set to understand every bit of HTML tags whatsoever I have used in my code." }, { "code": null, "e": 14938, "s": 14911, "text": "Continuing with my code: πŸ˜…" }, { "code": null, "e": 14956, "s": 14938, "text": "print(len(links))" }, { "code": null, "e": 15150, "s": 14956, "text": "This command will help you to inspect how many news articles are there on a given page.Help you understand accordingly, up to what level you need to paginate your loop for extracting huge data." }, { "code": null, "e": 15266, "s": 15150, "text": "Look for all anchor tags on the page (useful if you’re building a crawler and need to find the next pages to visit)" }, { "code": null, "e": 15293, "s": 15266, "text": "links = soup.find_all(\"a\")" }, { "code": null, "e": 15527, "s": 15293, "text": "It will find a division tag under <li> tag where div tag should contain listed or specific attribute value. Here 'j' is an iterable variable that is iterating over response object 'Links' for all news articles listed on a given page." }, { "code": null, "e": 15590, "s": 15527, "text": "Statement = j.find(\"div\",attrs={'class':'m-statement__quote'})" }, { "code": null, "e": 15730, "s": 15590, "text": "text.strip() function will return text contained within this tag and strip any kind of extra spaces, '\\n','\\t' from the text string object." }, { "code": null, "e": 15810, "s": 15730, "text": "Statement = j.find(\"div\",attrs={'class':'m- statement__quote'}).text.strip()" }, { "code": null, "e": 15886, "s": 15810, "text": "Bravo! 🌟 We have scraped the first attribute i.e., Statement of our dataset" }, { "code": null, "e": 16086, "s": 15886, "text": "In the same division section, It will look for anchor tag and return with the value of the hypertext link. Again, strip() function is used to get our values organized so that our CSV file looks good." }, { "code": null, "e": 16168, "s": 16086, "text": "Link=j.find(\"div\",attrs={'class':'m-statement__quote'}).find('a')['href'].strip()" }, { "code": null, "e": 16359, "s": 16168, "text": "For getting Date attribute, you need to inspect web-page first, As there is a string contained with it. So calling text function without specifying indexing, you will get something like this" }, { "code": null, "e": 16554, "s": 16359, "text": "But we don't need text other than the date, So I use indexing. Although you can clean your attribute later using some regex combinations. 'footer' is an element that contained the required text." }, { "code": null, "e": 16647, "s": 16554, "text": "Date = j.find('div',attrs={'class':'m-statement__body'}).find('footer').text[-14:-1].strip()" }, { "code": null, "e": 16778, "s": 16647, "text": "Here also, I have done everything same as before except get(), which is extracting the content of an attribute passed(i.e., title)" }, { "code": null, "e": 16871, "s": 16778, "text": "Source = j.find('div', attrs={'class':'m-statement__author'}).find('a').get('title').strip()" }, { "code": null, "e": 17409, "s": 16871, "text": "Since, For my project, I needed a dataset that is not already altered and also, I need to know already about thousands of articles that which article lies in what category for my training data. and No-one can do that manually. So, On this website, I do find articles attached already with labels but the text is not retrievable because it is contained in an image. For this kind of specific task, you can use get() to retrieve particular text effectively. Here, I am passing 'alt' as an attribute to get(), which contains our Label text." }, { "code": null, "e": 17539, "s": 17409, "text": "Label = j.find('div', attrs ={'class':'m-statement__content'}).find('img',attrs={'class':'c-image__original'}).get('alt').strip()" }, { "code": null, "e": 17670, "s": 17539, "text": "In the below lines of code, I have put all concepts together & tried to fetch details for five different attributes of my Dataset." }, { "code": null, "e": 18227, "s": 17670, "text": "for j in links: Statement = j.find(\"div\",attrs={'class':'m-statement__quote'}).text.strip() Link=st.find('a')['href'].strip() Date = j.find('div',attrs={'class':'m-statement__body'}).find('footer').text[-14:-1].strip() Source = j.find('div', attrs={'class':'m-statement__author'}).find('a').get('title').strip() Label = j.find('div', attrs ={'class':'m-statement__content'}).find('img',attrs={'class':'c-image__original'}).get('alt').strip() frame.append([Statement,Link,Date,Source,Label])upperframe.extend(frame)" }, { "code": null, "e": 18297, "s": 18227, "text": "Append each attribute value to an empty list 'frame' for each article" }, { "code": null, "e": 18346, "s": 18297, "text": "frame.append([Statement,Link,Date,Source,Label])" }, { "code": null, "e": 18414, "s": 18346, "text": "Then, extend this list to an empty list 'upperframe' for each page." }, { "code": null, "e": 18439, "s": 18414, "text": "upperframe.extend(frame)" }, { "code": null, "e": 18527, "s": 18439, "text": "If you wanted to visualize your data on Jupiter, you can use pandas DataFrame to do so." }, { "code": null, "e": 18622, "s": 18527, "text": "data=pd.DataFrame(upperframe, columns=['Statement','Link','Date','Source','Label'])data.head()" }, { "code": null, "e": 18794, "s": 18622, "text": "A) Opening & writing to fileThe below command will help you to write CSV file and save it to your machine in the same directory as where your python file has been saved in" }, { "code": null, "e": 19054, "s": 18794, "text": "filename=\"NEWS.csv\" f=open(filename,\"w\") headers=\"Statement,Link,Date, Source, Label\\n\" f.write(headers) .... f.write(Statement.replace(\",\",\"^\")+\",\"+Link+\",\"+Date.replace(\",\",\"^\")+\",\"+Source.replace(\",\",\"^\")+\",\"+Label.replace(\",\",\"^\")+\"\\n\")" }, { "code": null, "e": 19133, "s": 19054, "text": "This line will write each attribute to a file with replacing any ',' with '^'." }, { "code": null, "e": 19264, "s": 19133, "text": "f.write(Statement.replace(\",\",\"^\")+\",\"+Link+\",\"+Date.replace(\",\",\"^\")+\",\"+Source.replace(\",\",\"^\")+\",\"+Label.replace(\",\",\"^\")+\"\\n\")" }, { "code": null, "e": 19584, "s": 19264, "text": "So, when you run this file on command shell, It will make a CSV file in your .py file directory.On opening it, you might see weird data if you don't use strip() while scraping. So do check it without applying strip() and if you don't replace '^' with ',', It will also look weird.So replace it using these simple steps:" }, { "code": null, "e": 19617, "s": 19584, "text": "open your excel file (.csv file)" }, { "code": null, "e": 19696, "s": 19617, "text": "Press ctrl+H (a pop-up window will come asking about find what & replace with)" }, { "code": null, "e": 19776, "s": 19696, "text": "give '^' value to 'find what' field and give ',' value in 'replace with' field." }, { "code": null, "e": 19794, "s": 19776, "text": "Press Replace All" }, { "code": null, "e": 19975, "s": 19794, "text": "Click Close & Woohoo!😍 You are all done with having your dataset in perfect form. and don't forget to close your file with the following command after done with both the for loops," }, { "code": null, "e": 19985, "s": 19975, "text": "f.close()" }, { "code": null, "e": 20115, "s": 19985, "text": "and running the same code again and again might throw an error if it has already created a dataset using the file writing method." }, { "code": null, "e": 20350, "s": 20115, "text": "B) converting dataframe into csv file using to_csv()So, instead of this lengthy method, you can opt for another method: to_csv() is also used to convert the data frame into a CSV file and also provide an attribute to specify the path." }, { "code": null, "e": 20441, "s": 20350, "text": "path = 'C:\\\\Users\\\\Kajal\\\\Desktop\\\\KAJAL\\\\Project\\\\Datasets\\\\'data.to_csv(path+'NEWS.csv')" }, { "code": null, "e": 20517, "s": 20441, "text": "To avoid the ambiguity and allow portability of your code you can use this:" }, { "code": null, "e": 20570, "s": 20517, "text": "import osdata.to_csv(os.path.join(path,r'NEWS.csv'))" }, { "code": null, "e": 20637, "s": 20570, "text": "this will append your CSV name to your destination path correctly." }, { "code": null, "e": 20872, "s": 20637, "text": "Although I will suggest using the first method using open file and writing to it and then close it, I know it is a bit lengthy & tacky to implement but at least it will not provide you with ambiguous data as to_csv method mostly does." }, { "code": null, "e": 21123, "s": 20872, "text": "See in the above image, how it extracts ambiguous data for the Statement attribute.So, instead of spending hours cleaning your data manually, I would suggest writing a few extra lines of code specified in the first method.Now, you are done with it.✌️" }, { "code": null, "e": 21406, "s": 21123, "text": "IMPORTANT NOTE: If you tried to copy-paste my source code for scraping different websites & run it, It might possible that it will throw an error. In fact, It will definitely throw an error because each webpage's layout is different & for that, you need to make changes accordingly." }, { "code": null, "e": 21419, "s": 21406, "text": "The Dataset:" }, { "code": null, "e": 21577, "s": 21419, "text": "This article is the first part of the series of web-scraping and for those who come from non-technical backgrounds, read the second part of this series here." }, { "code": null, "e": 21755, "s": 21577, "text": "I hope you will find it useful and liked my article.πŸ˜‡ Please feel free to share your thoughts and hit me up with any queries you might have. You can reach me via the following :" }, { "code": null, "e": 21989, "s": 21755, "text": "Subscribe to my YouTube channel for video content coming soon hereFollow me on MediumConnect and reach me on LinkedInFollow me on my blogging journey:- https://kajalyadav.com/Become a member:- https://techykajal.medium.com/membership" }, { "code": null, "e": 22056, "s": 21989, "text": "Subscribe to my YouTube channel for video content coming soon here" }, { "code": null, "e": 22076, "s": 22056, "text": "Follow me on Medium" }, { "code": null, "e": 22109, "s": 22076, "text": "Connect and reach me on LinkedIn" }, { "code": null, "e": 22168, "s": 22109, "text": "Follow me on my blogging journey:- https://kajalyadav.com/" }, { "code": null, "e": 22227, "s": 22168, "text": "Become a member:- https://techykajal.medium.com/membership" } ]
JqueryUI - Resizable
jQueryUI provides resizable() method to resize any DOM element. This method simplifies the resizing of element which otherwise takes time and lot of coding in HTML. The resizable () method displays an icon in the bottom right of the item to resize. The resizable() method can be used in two forms βˆ’ $(selector, context).resizable (options) Method $(selector, context).resizable (options) Method $(selector, context).resizable ("action", params) Method $(selector, context).resizable ("action", params) Method The resizable (options) method declares that an HTML element can be resized. The options parameter is an object that specifies the behavior of the elements involved when resizing. $(selector, context).resizable (options); You can provide one or more options at a time of using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows βˆ’ $(selector, context).resizable({option1: value1, option2: value2..... }); The following table lists the different options that can be used with this method βˆ’ This option is of type Selector, jQuery , or any DOM Element. It represents elements that also resize when resizing the original object. By default its value is false. Option - alsoResize This option can be of type Selector, jQuery , or any DOM Element. It represents elements that also resize when resizing the original object. By default its value is false. This can be of type βˆ’ Selector βˆ’ This type indicates DOM elements to be selected from a DOM document for resizing. Selector βˆ’ This type indicates DOM elements to be selected from a DOM document for resizing. jQuery βˆ’ A callback function will be called for each resizable element on page. This function should return true if the element is resized. jQuery βˆ’ A callback function will be called for each resizable element on page. This function should return true if the element is resized. Element βˆ’ An element in the Document Object Model (DOM). Element βˆ’ An element in the Document Object Model (DOM). Syntax $( ".selector" ).resizable({ alsoResize: "#identifier" }); This option when set to true is used to enable a visual effect during resizing when the mouse button is released. The default value is false (no effect). Option - animate This option when set to true is used to enable a visual effect during resizing when the mouse button is released. The default value is false (no effect). Syntax $( ".selector" ).resizable({ animate: true }); This option is used to set the duration (in milliseconds) of the resizing effect. This option is used only when animate option is true. By default its value is "slow". Option - animateDuration This option is used to set the duration (in milliseconds) of the resizing effect. This option is used only when animate option is true. By default its value is "slow". This can be of type βˆ’ Number βˆ’ This specifies duration in milliseconds Number βˆ’ This specifies duration in milliseconds String βˆ’ This sepcifies named duration, such as "slow" or "fast". String βˆ’ This sepcifies named duration, such as "slow" or "fast". Syntax $( ".selector" ).resizable({ animateDuration: "fast" }); This option is used to specify which easing to apply when using the animate option. By default its value is "swing". Option - animateEasing This option is used to specify which easing to apply when using the animate option. By default its value is "swing". Easing functions specify the speed at which an animation progresses at different points within the animation. Syntax $( ".selector" ).resizable({ animateEasing: "easeOutBounce" }); This option is used to indicate whether to keep the aspect (height and width) ratio for the item. By default its value is false. Option - aspectRatio This option is used to indicate whether to keep the aspect (height and width) ratio for the item. By default its value is false. This can be of type βˆ’ Boolean βˆ’ This value if set to true, the element will maintain its original aspect ratio. Boolean βˆ’ This value if set to true, the element will maintain its original aspect ratio. Number βˆ’ This specifies the element to maintain a specific aspect ratio during resizing. Number βˆ’ This specifies the element to maintain a specific aspect ratio during resizing. Syntax $( ".selector" ).resizable({ aspectRatio: true }); This option is used to hide the magnification icon or handles, except when the mouse is over the item. By default its value is false. Option - autoHide This option is used to hide the magnification icon or handles, except when the mouse is over the item. By default its value is false. Syntax $( ".selector" ).resizable({ autoHide: true }); This option is used to prevent resizing on specified elements. By default its value is input,textarea,button,select,option. Option - cancel This option is used to prevent resizing on specified elements. By default its value is input,textarea,button,select,option. Syntax $( ".selector" ).resizable({ cancel: ".cancel" }); This option is used restrict the resizing of elements within a specified element or region. By default its value is false. Option - containment This option is used restrict the resizing of elements within a specified element or region. By default its value is false. This can be of type βˆ’ Selector βˆ’ This type indicates that resizable element will be contained to only the first item in the list found by the selector. Selector βˆ’ This type indicates that resizable element will be contained to only the first item in the list found by the selector. Element βˆ’ This type indicates any DOM element. The resizable element will be contained to the bounding box of this element. Element βˆ’ This type indicates any DOM element. The resizable element will be contained to the bounding box of this element. String βˆ’ Possible values for this type are - parent and document. String βˆ’ Possible values for this type are - parent and document. Syntax $( ".selector" ).resizable({ containment: "parent" }); This option is used to set tolerance or delay in milliseconds. Resizing or displacement will begin thereafter. By default its value is 0. Option - delay This option is used to set tolerance or delay in milliseconds. Resizing or displacement will begin thereafter. By default its value is 0. Syntax $( ".selector" ).resizable({ delay: 150 }); This option disables the resizing mechanism when set to true. The mouse no longer resizes elements, until the mechanism is enabled, using the resizable ("enable"). By default its value is false. Option - disabled This option disables the resizing mechanism when set to true. The mouse no longer resizes elements, until the mechanism is enabled, using the resizable ("enable"). By default its value is false. Syntax $( ".selector" ).resizable({ disabled: true }); With this option, the resizing starts only when the mouse moves a distance(pixels). By default its value is 1 pixel. This can help prevent unintended resizing when clicking on an element. Option - distance With this option, the resizing starts only when the mouse moves a distance(pixels). By default its value is 1 pixel. This can help prevent unintended resizing when clicking on an element. Syntax $( ".selector" ).resizable({ distance: 30 }); This option when set to true, a semi-transparent helper element is shown for resizing. This ghost item will be deleted when the mouse is released. By default its value is false. Option - ghost This option when set to true, a semi-transparent helper element is shown for resizing. This ghost item will be deleted when the mouse is released. By default its value is false. Syntax $( ".selector" ).resizable({ ghost: true }); This option is of type Array [x, y], indicating the number of pixels that the element expands horizontally and vertically during movement of the mouse. By default its value is false. Option - grid This option is of type Array [x, y], indicating the number of pixels that the element expands horizontally and vertically during movement of the mouse. By default its value is false. Syntax $( ".selector" ).resizable({ grid: [ 20, 10 ] }); This option is a character string indicating which sides or angles of the element can be resized. By default its values are e, s, se. Option - handles This option is a character string indicating which sides or angles of the element can be resized. The possible values are: n, e, s, and w for the four sides, and ne, se, nw, and sw for the four corners. The letters n, e, s, and w represent the four cardinal points (North, South, East, and West). By default its values are e, s, se. Syntax $( ".selector" ).resizable({ handles: "n, e, s, w" }); This option is used to add a CSS class to style the element to be resized. When the element is resized a new <div> element is created, which is the one that is scaled (ui-resizable-helper class). Once the resize is complete, the original element is sized and the <div> element disappears. By default its value is false. Option - helper This option is used to add a CSS class to style the element to be resized. When the element is resized a new <div> element is created, which is the one that is scaled (ui-resizable-helper class). Once the resize is complete, the original element is sized and the <div> element disappears. By default its value is false. Syntax $( ".selector" ).resizable({ helper: "resizable-helper" }); This option is used to set the maximum height the resizable should be allowed to resize to. By default its value is null. Option - maxHeight This option is used to set the maximum height the resizable should be allowed to resize to. By default its value is null. Syntax $( ".selector" ).resizable({ maxHeight: 300 }); This option is used to set the maximum width the resizable should be allowed to resize to. By default its value is null. Option - maxWidth This option is used to set the maximum width the resizable should be allowed to resize to. By default its value is null. Syntax $( ".selector" ).resizable({ maxWidth: 300 }); This option is used to set the minimum height the resizable should be allowed to resize to. By default its value is 10. Option - minHeight This option is used to set the minimum height the resizable should be allowed to resize to. By default its value is 10. Syntax $( ".selector" ).resizable({ minHeight: 150 }); This option is used to set the minimum width the resizable should be allowed to resize to. By default its value is 10. Option - minWidth This option is used to set the minimum width the resizable should be allowed to resize to. By default its value is 10. This can be of type βˆ’ Syntax $( ".selector" ).resizable({ minWidth: 150 }); The following section will show you few a working examples of resize functionality. The following example demonstrates a simple example of resizable functionality, passing no parameters to the resizable() method. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Resizable functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-widget-header { background:#b9cd6d; border: 1px solid #b9cd6d; color: #FFFFFF; font-weight: bold; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } #resizable { width: 150px; height: 150px; padding: 0.5em; text-align: center; margin: 0; } </style> <!-- Javascript --> <script> $(function() { $( "#resizable" ).resizable(); }); </script> </head> <body> <!-- HTML --> <div id = "resizable" class = "ui-widget-content"> <h3 class = "ui-widget-header">Pull my edges to resize me!!</h3> </div> </body> </html> Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’ Drag the square border to resize. The following example demonstrates the usage of two options animate and ghost in the resize function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Resizable functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-widget-header { background:#b9cd6d; border: 1px solid #b9cd6d; color: #FFFFFF; font-weight: bold; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } #resizable-2,#resizable-3 { width: 150px; height: 150px; padding: 0.5em; text-align: center; margin: 0; } </style> <!-- Javascript --> <script> $(function() { $( "#resizable-2" ).resizable({ animate: true }); $( "#resizable-3" ).resizable({ ghost: true }); }); </script> </head> <body> <!-- HTML --> <div id = "resizable-2" class = "ui-widget-content"> <h3 class = "ui-widget-header"> Pull my edges and Check the animation!! </h3> </div><br> <div id = "resizable-3" class = "ui-widget-content"> <h3 class = "ui-widget-header">I'm ghost!!</h3> </div> </body> </html> Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result βˆ’ Drag the square border to resize and see the effect of animate and ghost options. The following example demonstrates the usage of three options containment, minHeight and minWidth in the resize function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Resizable functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style> .ui-widget-header { background:#b9cd6d; border: 1px solid #b9cd6d; color: #FFFFFF; font-weight: bold; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } #container-1 { width: 300px; height: 300px; } #resizable-4 {background-position: top left; width: 150px; height: 150px; } #resizable-4, #container { padding: 0.5em; } </style> <script> $(function() { $( "#resizable-4" ).resizable({ containment: "#container", minHeight: 70, minWidth: 100 }); }); </script> </head> <body> <div id = "container" class = "ui-widget-content"> <div id = "resizable-4" class = "ui-state-active"> <h3 class = "ui-widget-header"> Resize contained to this container </h3> </div> </div> </body> </html> Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’ Drag the square border to resize, you cannot resize beyond the main container. The following example demonstrates the usage of three options delay, distance and autoHide in the resize function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Resizable functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style> .ui-widget-header { background:#b9cd6d; border: 1px solid #b9cd6d; color: #FFFFFF; font-weight: bold; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } .square { width: 150px; height: 150px; border: 1px solid black; text-align: center; float: left; margin-left: 20px; -right: 20px; } </style> <script> $(function() { $( "#resizable-5" ).resizable({ delay: 1000 }); $( "#resizable-6" ).resizable({ distance: 40 }); $( "#resizable-7" ).resizable({ autoHide: true }); }); </script> </head> <body> <div id = "resizable-5" class = "square ui-widget-content"> <h3 class = "ui-widget-header"> Resize starts after delay of 1000ms </h3> </div><br> <div id = "resizable-6" class = "square ui-widget-content"> <h3 class = "ui-widget-header"> Resize starts at distance of 40px </h3> </div><br> <div id = "resizable-7" class = "square ui-widget-content"> <h3 class = "ui-widget-header"> Hover over me to see the magnification icon! </h3> </div> </body> </html> Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’ Drag the square border to resize and you can notice that βˆ’ The first square box resizes after a delay of 1000ms, The first square box resizes after a delay of 1000ms, Second square box starts resizing after the mouse moves 40px. Second square box starts resizing after the mouse moves 40px. Hover the mouse on the third square box, and the magnification icon appears. Hover the mouse on the third square box, and the magnification icon appears. The following example demonstrates the usage of option alsoResize in the resize function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Resizable functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-widget-header { background:#b9cd6d; border: 1px solid #b9cd6d; color: #FFFFFF; font-weight: bold; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } #resizable-8,#resizable-9{ width: 150px; height: 150px; padding: 0.5em;text-align: center; margin: 0; } </style> <!-- Javascript --> <script> $(function() { $( "#resizable-8" ).resizable({ alsoResize: "#resizable-9" }); $( "#resizable-9" ).resizable(); }); </script> </head> <body> <!-- HTML --> <div id = "resizable-8" class = "ui-widget-content"> <h3 class = "ui-widget-header">Resize!!</h3> </div><br> <div id = "resizable-9" class = "ui-widget-content"> <h3 class = "ui-widget-header">I also get resized!!</h3> </div> </body> </html> Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’ Drag the square border to resize and you can notice that the second square box also resizes with the first square box. The following example demonstrates the usage of option aspectRatio and grid in the resize function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Resizable functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style> .ui-widget-header { background:#b9cd6d; border: 1px solid #b9cd6d; color: #FFFFFF; font-weight: bold; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } .square { width: 150px; height: 150px; border: 1px solid black; text-align: center; float: left; margin-left: 20px; margin-right: 20px; } </style> <script> $(function() { $( "#resizable-10" ).resizable({ aspectRatio: 10 / 3 }); $( "#resizable-11" ).resizable({ grid: [50,20] }); }); </script> </head> <body> <div id = "resizable-10" class = "square ui-widget-content"> <h3 class = "ui-widget-header"> Resize with aspectRatio of 10/3 </h3> </div> <div id = "resizable-11" class = "square ui-widget-content"> <h3 class = "ui-widget-header"> Snap me to the grid of [50,20] </h3> </div> </body> </html> Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’ Drag the square border to resize, the first square box resizes with the aspect ratio of 10 / 3 and the second one resizes with grid of [50,20]. The resizable ("action", params) method can perform an action on resizable elements, such as allowing or preventing resizing functionality. The action is specified as a string in the first argument (e.g., "disable" to prevent the resize). Check out the actions that can be passed, in the following table. $(selector, context).resizable ("action", params);; The following table lists the different actions that can be used with this method βˆ’ This action destroys the resizable functionality of an element completely. This will return the element back to its pre-init state. Action - destroy This action destroys the resizable fubctionality of an element completely. This will return the element back to its pre-init state. This method does not accept any arguments. Syntax $( ".selector" ).resizable("destroy"); This action disables the resizing functionality of an element. This method does not accept any arguments. Action - disable This action disables the resizing functionality of an element. This method does not accept any arguments. Syntax $( ".selector" ).resizable("disable"); This action enables the resizing functionality of an element. This method does not accept any arguments. Action - enable This action enables the resizing functionality of an element. This method does not accept any arguments. Syntax $( ".selector" ).resizable("enable"); This action retrieves the value of the specified optionName. This option corresponds to one of those used with resizable (options). Action - option( optionName ) This action retrieves the value of the specified optionName. This option corresponds to one of those used with resizable (options). Syntax var isDisabled = $( ".selector" ).resizable( "option", "disabled" ); Gets an object containing key/value pairs representing the current resizable options hash. This does not accept any arguments. Action - option() Gets an object containing key/value pairs representing the current resizable options hash. This does not accept any arguments. Syntax var options = $( ".selector" ).resizable( "option" ); This action sets the value of the resizable option with the specified optionName. This option corresponds to one of those used with resizable (options). Action - option( optionName, value ) This action sets the value of the resizable option with the specified optionName. This option corresponds to one of those used with resizable (options). Syntax $( ".selector" ).resizable( "option", "disabled", true ); This action sets one or more options for the resizable. Action - option( options ) This action sets one or more options for the resizable. Syntax $( ".selector" ).resizable( "option", { disabled: true } ); This action returns a jQuery object containing the resizable element. This method does not accept any arguments. Action - widget() This action returns a jQuery object containing the resizable element. This method does not accept any arguments. Syntax var widget = $( ".selector" ).resizable( "widget" ); Now let us see an example using the actions from the above table. The following example demonstrates the use of destroy() and disable() methods. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Resizable functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-widget-header { background:#b9cd6d; border: 1px solid #b9cd6d; color: #FFFFFF; font-weight: bold; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } #resizable-12,#resizable-13 { width: 150px; height: 150px; padding: 0.5em;text-align: center; margin: 0; } </style> <!-- Javascript --> <script> $(function() { $( "#resizable-12" ).resizable(); $( "#resizable-12" ).resizable('disable'); $( "#resizable-13" ).resizable(); $( "#resizable-13" ).resizable('destroy'); }); </script> </head> <body> <!-- HTML --> <div id = "resizable-12" class = "ui-widget-content"> <h3 class = "ui-widget-header">I'm disable!!</h3> </div><br> <div id = "resizable-13" class = "ui-widget-content"> <h3 class = "ui-widget-header">I'm Destroyed!!</h3> </div> </body> </html> Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output βˆ’ You cannot resize the first square box as its disabled and the second square box is destroyed. In addition to the resizable (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below βˆ’ This event is triggered when the resizable element is created. Event - create(event, ui) This event is triggered when the resizable element is created. Where event is of type Event, and ui is of type Object. Syntax $( ".selector" ).resizable({ create: function( event, ui ) {} }); This event is triggered when the handler of resizable element is dragged. Event - resize(event, ui) This event is triggered when the handler of resizable element is dragged. Where event is of type Event, and ui is of type Object. Possible values of ui are βˆ’ element βˆ’ A jQuery object representing the resizable element. element βˆ’ A jQuery object representing the resizable element. helper βˆ’ A jQuery object representing the helper that is being resized. helper βˆ’ A jQuery object representing the helper that is being resized. originalElement βˆ’ The jQuery object representing the original element before it is wrapped. originalElement βˆ’ The jQuery object representing the original element before it is wrapped. originalPosition βˆ’ The position represented as {left, top } before the resizable is resized. originalPosition βˆ’ The position represented as {left, top } before the resizable is resized. originalSize βˆ’ The size represented as { width, height } before the resizable is resized. originalSize βˆ’ The size represented as { width, height } before the resizable is resized. position βˆ’ The current position represented as {left, top }. position βˆ’ The current position represented as {left, top }. size βˆ’ The current size represented as { width, height }. size βˆ’ The current size represented as { width, height }. Syntax $( ".selector" ).resizable({ resize: function( event, ui ) {} }); This event is triggered at the start of a resize operation. Event - start(event, ui) This event is triggered at the start of a resize operation. Where event is of type Event, and ui is of type Object. Possible values of ui are βˆ’ element βˆ’ A jQuery object representing the resizable element. element βˆ’ A jQuery object representing the resizable element. helper βˆ’ A jQuery object representing the helper that is being resized. helper βˆ’ A jQuery object representing the helper that is being resized. originalElement βˆ’ The jQuery object representing the original element before it is wrapped. originalElement βˆ’ The jQuery object representing the original element before it is wrapped. originalPosition βˆ’ The position represented as {left, top } before the resizable is resized. originalPosition βˆ’ The position represented as {left, top } before the resizable is resized. originalSize βˆ’ The size represented as { width, height } before the resizable is resized. originalSize βˆ’ The size represented as { width, height } before the resizable is resized. position βˆ’ The current position represented as {left, top }. position βˆ’ The current position represented as {left, top }. size βˆ’ The current size represented as { width, height }. size βˆ’ The current size represented as { width, height }. Syntax $( ".selector" ).resizable({ start: function( event, ui ) {} }); This event is triggered at the end of a resize operation. Event - stop(event, ui) This event is triggered at the end of a resize operation. Where event is of type Event, and ui is of type Object. Possible values of ui are βˆ’ element βˆ’ A jQuery object representing the resizable element. element βˆ’ A jQuery object representing the resizable element. helper βˆ’ A jQuery object representing the helper that is being resized. helper βˆ’ A jQuery object representing the helper that is being resized. originalElement βˆ’ The jQuery object representing the original element before it is wrapped. originalElement βˆ’ The jQuery object representing the original element before it is wrapped. originalPosition βˆ’ The position represented as {left, top } before the resizable is resized. originalPosition βˆ’ The position represented as {left, top } before the resizable is resized. originalSize βˆ’ The size represented as { width, height } before the resizable is resized. originalSize βˆ’ The size represented as { width, height } before the resizable is resized. position βˆ’ The current position represented as {left, top }. position βˆ’ The current position represented as {left, top }. size βˆ’ The current size represented as { width,height }. size βˆ’ The current size represented as { width,height }. Syntax $( ".selector" ).resizable({ stop: function( event, ui ) {} }); The following example demonstrates the event method usage during resize functionality. This example demonstrates the use of events create, and resize. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Resizable functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-widget-header { background:#b9cd6d; border: 1px solid #b9cd6d; color: #FFFFFF; font-weight: bold; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } #resizable-14{ width: 150px; height: 150px; padding: 0.5em;text-align: center; margin: 0; } </style> <!-- Javascript --> <script> $(function() { $( "#resizable-14" ).resizable({ create: function( event, ui ) { $("#resizable-15").text ("I'm Created!!"); }, resize: function (event, ui) { $("#resizable-16").text ("top = " + ui.position.top + ", left = " + ui.position.left + ", width = " + ui.size.width + ", height = " + ui.size.height); } }); }); </script> </head> <body> <!-- HTML --> <div id = "resizable-14" class = "ui-widget-content"> <h3 class = "ui-widget-header">Resize !!</h3> </div><br> <span id = "resizable-15"></span><br> <span id = "resizable-16"></span> </body> </html> Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, should must see the following output βˆ’ Drag the square box and you will see the output getting displayed on resize event. Print Add Notes Bookmark this page
[ { "code": null, "e": 2513, "s": 2264, "text": "jQueryUI provides resizable() method to resize any DOM element. This method simplifies the resizing of element which otherwise takes time and lot of coding in HTML. The resizable () method displays an icon in the bottom right of the item to resize." }, { "code": null, "e": 2563, "s": 2513, "text": "The resizable() method can be used in two forms βˆ’" }, { "code": null, "e": 2612, "s": 2563, "text": "$(selector, context).resizable (options) Method\n" }, { "code": null, "e": 2660, "s": 2612, "text": "$(selector, context).resizable (options) Method" }, { "code": null, "e": 2718, "s": 2660, "text": "$(selector, context).resizable (\"action\", params) Method\n" }, { "code": null, "e": 2775, "s": 2718, "text": "$(selector, context).resizable (\"action\", params) Method" }, { "code": null, "e": 2955, "s": 2775, "text": "The resizable (options) method declares that an HTML element can be resized. The options parameter is an object that specifies the behavior of the elements involved when resizing." }, { "code": null, "e": 2997, "s": 2955, "text": "$(selector, context).resizable (options);" }, { "code": null, "e": 3176, "s": 2997, "text": "You can provide one or more options at a time of using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows βˆ’" }, { "code": null, "e": 3250, "s": 3176, "text": "$(selector, context).resizable({option1: value1, option2: value2..... });" }, { "code": null, "e": 3334, "s": 3250, "text": "The following table lists the different options that can be used with this method βˆ’" }, { "code": null, "e": 3502, "s": 3334, "text": "This option is of type Selector, jQuery , or any DOM Element. It represents elements that also resize when resizing the original object. By default its value is false." }, { "code": null, "e": 3522, "s": 3502, "text": "Option - alsoResize" }, { "code": null, "e": 3694, "s": 3522, "text": "This option can be of type Selector, jQuery , or any DOM Element. It represents elements that also resize when resizing the original object. By default its value is false." }, { "code": null, "e": 3716, "s": 3694, "text": "This can be of type βˆ’" }, { "code": null, "e": 3809, "s": 3716, "text": "Selector βˆ’ This type indicates DOM elements to be selected from a DOM document for resizing." }, { "code": null, "e": 3902, "s": 3809, "text": "Selector βˆ’ This type indicates DOM elements to be selected from a DOM document for resizing." }, { "code": null, "e": 4042, "s": 3902, "text": "jQuery βˆ’ A callback function will be called for each resizable element on page. This function should return true if the element is resized." }, { "code": null, "e": 4182, "s": 4042, "text": "jQuery βˆ’ A callback function will be called for each resizable element on page. This function should return true if the element is resized." }, { "code": null, "e": 4239, "s": 4182, "text": "Element βˆ’ An element in the Document Object Model (DOM)." }, { "code": null, "e": 4296, "s": 4239, "text": "Element βˆ’ An element in the Document Object Model (DOM)." }, { "code": null, "e": 4303, "s": 4296, "text": "Syntax" }, { "code": null, "e": 4363, "s": 4303, "text": "$( \".selector\" ).resizable({ alsoResize: \"#identifier\" });\n" }, { "code": null, "e": 4517, "s": 4363, "text": "This option when set to true is used to enable a visual effect during resizing when the mouse button is released. The default value is false (no effect)." }, { "code": null, "e": 4534, "s": 4517, "text": "Option - animate" }, { "code": null, "e": 4688, "s": 4534, "text": "This option when set to true is used to enable a visual effect during resizing when the mouse button is released. The default value is false (no effect)." }, { "code": null, "e": 4695, "s": 4688, "text": "Syntax" }, { "code": null, "e": 4743, "s": 4695, "text": "$( \".selector\" ).resizable({ animate: true });\n" }, { "code": null, "e": 4911, "s": 4743, "text": "This option is used to set the duration (in milliseconds) of the resizing effect. This option is used only when animate\noption is true. By default its value is \"slow\"." }, { "code": null, "e": 4936, "s": 4911, "text": "Option - animateDuration" }, { "code": null, "e": 5104, "s": 4936, "text": "This option is used to set the duration (in milliseconds) of the resizing effect. This option is used only when animate option is true. By default its value is \"slow\"." }, { "code": null, "e": 5126, "s": 5104, "text": "This can be of type βˆ’" }, { "code": null, "e": 5175, "s": 5126, "text": "Number βˆ’ This specifies duration in milliseconds" }, { "code": null, "e": 5224, "s": 5175, "text": "Number βˆ’ This specifies duration in milliseconds" }, { "code": null, "e": 5290, "s": 5224, "text": "String βˆ’ This sepcifies named duration, such as \"slow\" or \"fast\"." }, { "code": null, "e": 5356, "s": 5290, "text": "String βˆ’ This sepcifies named duration, such as \"slow\" or \"fast\"." }, { "code": null, "e": 5363, "s": 5356, "text": "Syntax" }, { "code": null, "e": 5421, "s": 5363, "text": "$( \".selector\" ).resizable({ animateDuration: \"fast\" });\n" }, { "code": null, "e": 5538, "s": 5421, "text": "This option is used to specify which easing to apply when using the animate option. By default its value is \"swing\"." }, { "code": null, "e": 5561, "s": 5538, "text": "Option - animateEasing" }, { "code": null, "e": 5678, "s": 5561, "text": "This option is used to specify which easing to apply when using the animate option. By default its value is \"swing\"." }, { "code": null, "e": 5788, "s": 5678, "text": "Easing functions specify the speed at which an animation progresses at different points within the animation." }, { "code": null, "e": 5795, "s": 5788, "text": "Syntax" }, { "code": null, "e": 5860, "s": 5795, "text": "$( \".selector\" ).resizable({ animateEasing: \"easeOutBounce\" });\n" }, { "code": null, "e": 5989, "s": 5860, "text": "This option is used to indicate whether to keep the aspect (height and width) ratio for the item. By default its value is false." }, { "code": null, "e": 6010, "s": 5989, "text": "Option - aspectRatio" }, { "code": null, "e": 6139, "s": 6010, "text": "This option is used to indicate whether to keep the aspect (height and width) ratio for the item. By default its value is false." }, { "code": null, "e": 6161, "s": 6139, "text": "This can be of type βˆ’" }, { "code": null, "e": 6251, "s": 6161, "text": "Boolean βˆ’ This value if set to true, the element will maintain its original aspect ratio." }, { "code": null, "e": 6341, "s": 6251, "text": "Boolean βˆ’ This value if set to true, the element will maintain its original aspect ratio." }, { "code": null, "e": 6430, "s": 6341, "text": "Number βˆ’ This specifies the element to maintain a specific aspect ratio during resizing." }, { "code": null, "e": 6519, "s": 6430, "text": "Number βˆ’ This specifies the element to maintain a specific aspect ratio during resizing." }, { "code": null, "e": 6526, "s": 6519, "text": "Syntax" }, { "code": null, "e": 6578, "s": 6526, "text": "$( \".selector\" ).resizable({ aspectRatio: true });\n" }, { "code": null, "e": 6712, "s": 6578, "text": "This option is used to hide the magnification icon or handles, except when the mouse is over the item. By default its value is false." }, { "code": null, "e": 6730, "s": 6712, "text": "Option - autoHide" }, { "code": null, "e": 6864, "s": 6730, "text": "This option is used to hide the magnification icon or handles, except when the mouse is over the item. By default its value is false." }, { "code": null, "e": 6871, "s": 6864, "text": "Syntax" }, { "code": null, "e": 6920, "s": 6871, "text": "$( \".selector\" ).resizable({ autoHide: true });\n" }, { "code": null, "e": 7044, "s": 6920, "text": "This option is used to prevent resizing on specified elements. By default its value is input,textarea,button,select,option." }, { "code": null, "e": 7060, "s": 7044, "text": "Option - cancel" }, { "code": null, "e": 7184, "s": 7060, "text": "This option is used to prevent resizing on specified elements. By default its value is input,textarea,button,select,option." }, { "code": null, "e": 7191, "s": 7184, "text": "Syntax" }, { "code": null, "e": 7243, "s": 7191, "text": "$( \".selector\" ).resizable({ cancel: \".cancel\" });\n" }, { "code": null, "e": 7366, "s": 7243, "text": "This option is used restrict the resizing of elements within a specified element or region. By default its value is false." }, { "code": null, "e": 7387, "s": 7366, "text": "Option - containment" }, { "code": null, "e": 7510, "s": 7387, "text": "This option is used restrict the resizing of elements within a specified element or region. By default its value is false." }, { "code": null, "e": 7532, "s": 7510, "text": "This can be of type βˆ’" }, { "code": null, "e": 7662, "s": 7532, "text": "Selector βˆ’ This type indicates that resizable element will be contained to only the first item in the list found by the selector." }, { "code": null, "e": 7792, "s": 7662, "text": "Selector βˆ’ This type indicates that resizable element will be contained to only the first item in the list found by the selector." }, { "code": null, "e": 7916, "s": 7792, "text": "Element βˆ’ This type indicates any DOM element. The resizable element will be contained to the bounding box of this element." }, { "code": null, "e": 8040, "s": 7916, "text": "Element βˆ’ This type indicates any DOM element. The resizable element will be contained to the bounding box of this element." }, { "code": null, "e": 8106, "s": 8040, "text": "String βˆ’ Possible values for this type are - parent and document." }, { "code": null, "e": 8172, "s": 8106, "text": "String βˆ’ Possible values for this type are - parent and document." }, { "code": null, "e": 8179, "s": 8172, "text": "Syntax" }, { "code": null, "e": 8235, "s": 8179, "text": "$( \".selector\" ).resizable({ containment: \"parent\" });\n" }, { "code": null, "e": 8373, "s": 8235, "text": "This option is used to set tolerance or delay in milliseconds. Resizing or displacement will begin thereafter. By default its value is\n0." }, { "code": null, "e": 8388, "s": 8373, "text": "Option - delay" }, { "code": null, "e": 8526, "s": 8388, "text": "This option is used to set tolerance or delay in milliseconds. Resizing or displacement will begin thereafter. By default its value is\n0." }, { "code": null, "e": 8533, "s": 8526, "text": "Syntax" }, { "code": null, "e": 8578, "s": 8533, "text": "$( \".selector\" ).resizable({ delay: 150 });\n" }, { "code": null, "e": 8773, "s": 8578, "text": "This option disables the resizing mechanism when set to true. The mouse no longer resizes elements, until the mechanism is enabled, using the resizable (\"enable\"). By default its value is false." }, { "code": null, "e": 8791, "s": 8773, "text": "Option - disabled" }, { "code": null, "e": 8986, "s": 8791, "text": "This option disables the resizing mechanism when set to true. The mouse no longer resizes elements, until the mechanism is enabled, using the resizable (\"enable\"). By default its value is false." }, { "code": null, "e": 8993, "s": 8986, "text": "Syntax" }, { "code": null, "e": 9042, "s": 8993, "text": "$( \".selector\" ).resizable({ disabled: true });\n" }, { "code": null, "e": 9230, "s": 9042, "text": "With this option, the resizing starts only when the mouse moves a distance(pixels). By default its value is 1 pixel. This can help prevent unintended resizing when clicking on an element." }, { "code": null, "e": 9248, "s": 9230, "text": "Option - distance" }, { "code": null, "e": 9436, "s": 9248, "text": "With this option, the resizing starts only when the mouse moves a distance(pixels). By default its value is 1 pixel. This can help prevent unintended resizing when clicking on an element." }, { "code": null, "e": 9443, "s": 9436, "text": "Syntax" }, { "code": null, "e": 9490, "s": 9443, "text": "$( \".selector\" ).resizable({ distance: 30 });\n" }, { "code": null, "e": 9668, "s": 9490, "text": "This option when set to true, a semi-transparent helper element is shown for resizing. This ghost item will be deleted when the mouse is released. By default its value is false." }, { "code": null, "e": 9683, "s": 9668, "text": "Option - ghost" }, { "code": null, "e": 9861, "s": 9683, "text": "This option when set to true, a semi-transparent helper element is shown for resizing. This ghost item will be deleted when the mouse is released. By default its value is false." }, { "code": null, "e": 9868, "s": 9861, "text": "Syntax" }, { "code": null, "e": 9914, "s": 9868, "text": "$( \".selector\" ).resizable({ ghost: true });\n" }, { "code": null, "e": 10097, "s": 9914, "text": "This option is of type Array [x, y], indicating the number of pixels that the element expands horizontally and vertically during movement of the mouse. By default its value is false." }, { "code": null, "e": 10111, "s": 10097, "text": "Option - grid" }, { "code": null, "e": 10294, "s": 10111, "text": "This option is of type Array [x, y], indicating the number of pixels that the element expands horizontally and vertically during movement of the mouse. By default its value is false." }, { "code": null, "e": 10301, "s": 10294, "text": "Syntax" }, { "code": null, "e": 10352, "s": 10301, "text": "$( \".selector\" ).resizable({ grid: [ 20, 10 ] });\n" }, { "code": null, "e": 10486, "s": 10352, "text": "This option is a character string indicating which sides or angles of the element can be resized. By default its values are e, s, se." }, { "code": null, "e": 10503, "s": 10486, "text": "Option - handles" }, { "code": null, "e": 10800, "s": 10503, "text": "This option is a character string indicating which sides or angles of the element can be resized. The possible values are: n,\ne, s, and w for the four sides, and ne, se, nw, and sw for the four corners. The letters n, e, s, and w\nrepresent the four cardinal points (North, South, East, and West)." }, { "code": null, "e": 10836, "s": 10800, "text": "By default its values are e, s, se." }, { "code": null, "e": 10843, "s": 10836, "text": "Syntax" }, { "code": null, "e": 10899, "s": 10843, "text": "$( \".selector\" ).resizable({ handles: \"n, e, s, w\" });\n" }, { "code": null, "e": 11219, "s": 10899, "text": "This option is used to add a CSS class to style the element to be resized. When the element is resized a new <div> element is created, which is the one that is scaled (ui-resizable-helper class). Once the resize is complete, the original element is sized and the\n<div> element disappears. By default its value is false." }, { "code": null, "e": 11235, "s": 11219, "text": "Option - helper" }, { "code": null, "e": 11555, "s": 11235, "text": "This option is used to add a CSS class to style the element to be resized. When the element is resized a new <div> element is created, which is the one that is scaled (ui-resizable-helper class). Once the resize is complete, the original element is sized and the\n<div> element disappears. By default its value is false." }, { "code": null, "e": 11562, "s": 11555, "text": "Syntax" }, { "code": null, "e": 11623, "s": 11562, "text": "$( \".selector\" ).resizable({ helper: \"resizable-helper\" });\n" }, { "code": null, "e": 11745, "s": 11623, "text": "This option is used to set the maximum height the resizable should be allowed to resize to. By default its value is null." }, { "code": null, "e": 11764, "s": 11745, "text": "Option - maxHeight" }, { "code": null, "e": 11886, "s": 11764, "text": "This option is used to set the maximum height the resizable should be allowed to resize to. By default its value is null." }, { "code": null, "e": 11893, "s": 11886, "text": "Syntax" }, { "code": null, "e": 11942, "s": 11893, "text": "$( \".selector\" ).resizable({ maxHeight: 300 });\n" }, { "code": null, "e": 12063, "s": 11942, "text": "This option is used to set the maximum width the resizable should be allowed to resize to. By default its value is null." }, { "code": null, "e": 12081, "s": 12063, "text": "Option - maxWidth" }, { "code": null, "e": 12202, "s": 12081, "text": "This option is used to set the maximum width the resizable should be allowed to resize to. By default its value is null." }, { "code": null, "e": 12209, "s": 12202, "text": "Syntax" }, { "code": null, "e": 12257, "s": 12209, "text": "$( \".selector\" ).resizable({ maxWidth: 300 });\n" }, { "code": null, "e": 12377, "s": 12257, "text": "This option is used to set the minimum height the resizable should be allowed to resize to. By default its value is 10." }, { "code": null, "e": 12396, "s": 12377, "text": "Option - minHeight" }, { "code": null, "e": 12516, "s": 12396, "text": "This option is used to set the minimum height the resizable should be allowed to resize to. By default its value is 10." }, { "code": null, "e": 12523, "s": 12516, "text": "Syntax" }, { "code": null, "e": 12572, "s": 12523, "text": "$( \".selector\" ).resizable({ minHeight: 150 });\n" }, { "code": null, "e": 12691, "s": 12572, "text": "This option is used to set the minimum width the resizable should be allowed to resize to. By default its value is 10." }, { "code": null, "e": 12709, "s": 12691, "text": "Option - minWidth" }, { "code": null, "e": 12828, "s": 12709, "text": "This option is used to set the minimum width the resizable should be allowed to resize to. By default its value is 10." }, { "code": null, "e": 12850, "s": 12828, "text": "This can be of type βˆ’" }, { "code": null, "e": 12857, "s": 12850, "text": "Syntax" }, { "code": null, "e": 12905, "s": 12857, "text": "$( \".selector\" ).resizable({ minWidth: 150 });\n" }, { "code": null, "e": 12989, "s": 12905, "text": "The following section will show you few a working examples of resize functionality." }, { "code": null, "e": 13118, "s": 12989, "text": "The following example demonstrates a simple example of resizable functionality, passing no parameters to the resizable() method." }, { "code": null, "e": 14347, "s": 13118, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Resizable functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-widget-header {\n background:#b9cd6d;\n border: 1px solid #b9cd6d;\n color: #FFFFFF;\n font-weight: bold;\n }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n #resizable { width: 150px; height: 150px; padding: 0.5em;\n text-align: center; margin: 0; }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#resizable\" ).resizable();\n });\n </script>\n </head>\n\n <body>\n <!-- HTML --> \n <div id = \"resizable\" class = \"ui-widget-content\"> \n <h3 class = \"ui-widget-header\">Pull my edges to resize me!!</h3>\n </div>\n </body>\n</html>" }, { "code": null, "e": 14542, "s": 14347, "text": "Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’" }, { "code": null, "e": 14576, "s": 14542, "text": "Drag the square border to resize." }, { "code": null, "e": 14690, "s": 14576, "text": "The following example demonstrates the usage of two options animate and ghost in the resize function of JqueryUI." }, { "code": null, "e": 16255, "s": 14690, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Resizable functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-widget-header {\n background:#b9cd6d;\n border: 1px solid #b9cd6d;\n color: #FFFFFF;\n font-weight: bold;\n }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n #resizable-2,#resizable-3 { \n width: 150px; height: 150px; padding: 0.5em;\n text-align: center; margin: 0; }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#resizable-2\" ).resizable({\n animate: true\n });\n $( \"#resizable-3\" ).resizable({\n ghost: true\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"resizable-2\" class = \"ui-widget-content\"> \n <h3 class = \"ui-widget-header\">\n Pull my edges and Check the animation!!\n </h3>\n </div><br>\n <div id = \"resizable-3\" class = \"ui-widget-content\"> \n <h3 class = \"ui-widget-header\">I'm ghost!!</h3>\n </div> \n </body>\n</html>" }, { "code": null, "e": 16453, "s": 16255, "text": "Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result βˆ’" }, { "code": null, "e": 16535, "s": 16453, "text": "Drag the square border to resize and see the effect of animate and ghost options." }, { "code": null, "e": 16669, "s": 16535, "text": "The following example demonstrates the usage of three options containment, minHeight and minWidth in the resize function of JqueryUI." }, { "code": null, "e": 18154, "s": 16669, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Resizable functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n .ui-widget-header {\n background:#b9cd6d;\n border: 1px solid #b9cd6d;\n color: #FFFFFF;\n font-weight: bold;\n }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n #container-1 { width: 300px; height: 300px; }\n #resizable-4 {background-position: top left; \n width: 150px; height: 150px; } \n #resizable-4, #container { padding: 0.5em; } \n </style>\n\n <script>\n $(function() {\n $( \"#resizable-4\" ).resizable({\n containment: \"#container\",\n minHeight: 70,\n minWidth: 100\n });\n });\n </script>\n </head>\n\n <body>\n <div id = \"container\" class = \"ui-widget-content\">\n <div id = \"resizable-4\" class = \"ui-state-active\">\n <h3 class = \"ui-widget-header\">\n Resize contained to this container\n </h3>\n </div>\n </div> \n </body>\n</html>" }, { "code": null, "e": 18349, "s": 18154, "text": "Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’" }, { "code": null, "e": 18428, "s": 18349, "text": "Drag the square border to resize, you cannot resize beyond the main container." }, { "code": null, "e": 18555, "s": 18428, "text": "The following example demonstrates the usage of three options delay, distance and autoHide in the resize function of JqueryUI." }, { "code": null, "e": 20486, "s": 18555, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Resizable functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n .ui-widget-header {\n background:#b9cd6d;\n border: 1px solid #b9cd6d;\n color: #FFFFFF;\n font-weight: bold;\n }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n .square {\n width: 150px;\n height: 150px;\n border: 1px solid black;\n text-align: center;\n float: left;\n margin-left: 20px;\n -right: 20px;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#resizable-5\" ).resizable({\n delay: 1000\n });\n\n $( \"#resizable-6\" ).resizable({\n distance: 40\n });\n $( \"#resizable-7\" ).resizable({\n autoHide: true\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"resizable-5\" class = \"square ui-widget-content\">\n <h3 class = \"ui-widget-header\">\n Resize starts after delay of 1000ms\n </h3>\n </div><br>\n <div id = \"resizable-6\" class = \"square ui-widget-content\">\n <h3 class = \"ui-widget-header\">\n Resize starts at distance of 40px\n </h3>\n </div><br>\n <div id = \"resizable-7\" class = \"square ui-widget-content\">\n <h3 class = \"ui-widget-header\">\n Hover over me to see the magnification icon!\n </h3>\n </div>\n </body>\n</html>" }, { "code": null, "e": 20681, "s": 20486, "text": "Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’" }, { "code": null, "e": 20740, "s": 20681, "text": "Drag the square border to resize and you can notice that βˆ’" }, { "code": null, "e": 20795, "s": 20740, "text": "The first square box resizes after a delay of 1000ms, " }, { "code": null, "e": 20850, "s": 20795, "text": "The first square box resizes after a delay of 1000ms, " }, { "code": null, "e": 20912, "s": 20850, "text": "Second square box starts resizing after the mouse moves 40px." }, { "code": null, "e": 20974, "s": 20912, "text": "Second square box starts resizing after the mouse moves 40px." }, { "code": null, "e": 21051, "s": 20974, "text": "Hover the mouse on the third square box, and the magnification icon appears." }, { "code": null, "e": 21128, "s": 21051, "text": "Hover the mouse on the third square box, and the magnification icon appears." }, { "code": null, "e": 21230, "s": 21128, "text": "The following example demonstrates the usage of option alsoResize in the resize function of JqueryUI." }, { "code": null, "e": 22704, "s": 21230, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Resizable functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-widget-header {\n background:#b9cd6d;\n border: 1px solid #b9cd6d;\n color: #FFFFFF;\n font-weight: bold;\n }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n #resizable-8,#resizable-9{ width: 150px; height: 150px; \n padding: 0.5em;text-align: center; margin: 0; }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#resizable-8\" ).resizable({\n alsoResize: \"#resizable-9\"\n });\n $( \"#resizable-9\" ).resizable();\n });\n </script>\n </head>\n\n <body>\n <!-- HTML --> \n <div id = \"resizable-8\" class = \"ui-widget-content\"> \n <h3 class = \"ui-widget-header\">Resize!!</h3>\n </div><br>\n <div id = \"resizable-9\" class = \"ui-widget-content\"> \n <h3 class = \"ui-widget-header\">I also get resized!!</h3>\n </div> \n </body>\n</html>" }, { "code": null, "e": 22899, "s": 22704, "text": "Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’" }, { "code": null, "e": 23018, "s": 22899, "text": "Drag the square border to resize and you can notice that the second square box also resizes with the first square box." }, { "code": null, "e": 23130, "s": 23018, "text": "The following example demonstrates the usage of option aspectRatio and grid in the resize function of JqueryUI." }, { "code": null, "e": 24784, "s": 23130, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Resizable functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n .ui-widget-header {\n background:#b9cd6d;\n border: 1px solid #b9cd6d;\n color: #FFFFFF;\n font-weight: bold;\n }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n .square {\n width: 150px;\n height: 150px;\n border: 1px solid black;\n text-align: center;\n float: left;\n margin-left: 20px;\n margin-right: 20px;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#resizable-10\" ).resizable({\n aspectRatio: 10 / 3\n });\n\n $( \"#resizable-11\" ).resizable({\n grid: [50,20]\n });\n\n });\n </script>\n </head>\n \n <body>\n <div id = \"resizable-10\" class = \"square ui-widget-content\">\n <h3 class = \"ui-widget-header\">\n Resize with aspectRatio of 10/3\n </h3>\n </div>\n <div id = \"resizable-11\" class = \"square ui-widget-content\">\n <h3 class = \"ui-widget-header\">\n Snap me to the grid of [50,20]\n </h3>\n </div>\n </body>\n</html>" }, { "code": null, "e": 24979, "s": 24784, "text": "Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result βˆ’" }, { "code": null, "e": 25123, "s": 24979, "text": "Drag the square border to resize, the first square box resizes with the aspect ratio of 10 / 3 and the second one resizes with grid of [50,20]." }, { "code": null, "e": 25428, "s": 25123, "text": "The resizable (\"action\", params) method can perform an action on resizable elements, such as allowing or preventing resizing functionality. The action is specified as a string in the first argument (e.g., \"disable\" to prevent the resize). Check out the actions that can be passed, in the following table." }, { "code": null, "e": 25480, "s": 25428, "text": "$(selector, context).resizable (\"action\", params);;" }, { "code": null, "e": 25564, "s": 25480, "text": "The following table lists the different actions that can be used with this method βˆ’" }, { "code": null, "e": 25696, "s": 25564, "text": "This action destroys the resizable functionality of an element completely. This will return the element back to its pre-init state." }, { "code": null, "e": 25713, "s": 25696, "text": "Action - destroy" }, { "code": null, "e": 25888, "s": 25713, "text": "This action destroys the resizable fubctionality of an element completely. This will return the element back to its pre-init state.\nThis method does not accept any arguments." }, { "code": null, "e": 25895, "s": 25888, "text": "Syntax" }, { "code": null, "e": 25936, "s": 25895, "text": " $( \".selector\" ).resizable(\"destroy\");\n" }, { "code": null, "e": 26042, "s": 25936, "text": "This action disables the resizing functionality of an element. This method does not accept any arguments." }, { "code": null, "e": 26059, "s": 26042, "text": "Action - disable" }, { "code": null, "e": 26165, "s": 26059, "text": "This action disables the resizing functionality of an element. This method does not accept any arguments." }, { "code": null, "e": 26172, "s": 26165, "text": "Syntax" }, { "code": null, "e": 26213, "s": 26172, "text": " $( \".selector\" ).resizable(\"disable\");\n" }, { "code": null, "e": 26318, "s": 26213, "text": "This action enables the resizing functionality of an element. This method does not accept any arguments." }, { "code": null, "e": 26334, "s": 26318, "text": "Action - enable" }, { "code": null, "e": 26439, "s": 26334, "text": "This action enables the resizing functionality of an element. This method does not accept any arguments." }, { "code": null, "e": 26446, "s": 26439, "text": "Syntax" }, { "code": null, "e": 26485, "s": 26446, "text": "$( \".selector\" ).resizable(\"enable\");\n" }, { "code": null, "e": 26617, "s": 26485, "text": "This action retrieves the value of the specified optionName. This option corresponds to one of those used with resizable (options)." }, { "code": null, "e": 26647, "s": 26617, "text": "Action - option( optionName )" }, { "code": null, "e": 26779, "s": 26647, "text": "This action retrieves the value of the specified optionName. This option corresponds to one of those used with resizable (options)." }, { "code": null, "e": 26786, "s": 26779, "text": "Syntax" }, { "code": null, "e": 26856, "s": 26786, "text": "var isDisabled = $( \".selector\" ).resizable( \"option\", \"disabled\" );\n" }, { "code": null, "e": 26983, "s": 26856, "text": "Gets an object containing key/value pairs representing the current resizable options hash. This does not accept any arguments." }, { "code": null, "e": 27001, "s": 26983, "text": "Action - option()" }, { "code": null, "e": 27128, "s": 27001, "text": "Gets an object containing key/value pairs representing the current resizable options hash. This does not accept any arguments." }, { "code": null, "e": 27135, "s": 27128, "text": "Syntax" }, { "code": null, "e": 27192, "s": 27135, "text": " \nvar options = $( \".selector\" ).resizable( \"option\" );\n" }, { "code": null, "e": 27345, "s": 27192, "text": "This action sets the value of the resizable option with the specified optionName. This option corresponds to one of those used with resizable (options)." }, { "code": null, "e": 27382, "s": 27345, "text": "Action - option( optionName, value )" }, { "code": null, "e": 27535, "s": 27382, "text": "This action sets the value of the resizable option with the specified optionName. This option corresponds to one of those used with resizable (options)." }, { "code": null, "e": 27542, "s": 27535, "text": "Syntax" }, { "code": null, "e": 27603, "s": 27542, "text": " \n$( \".selector\" ).resizable( \"option\", \"disabled\", true );\n" }, { "code": null, "e": 27659, "s": 27603, "text": "This action sets one or more options for the resizable." }, { "code": null, "e": 27686, "s": 27659, "text": "Action - option( options )" }, { "code": null, "e": 27742, "s": 27686, "text": "This action sets one or more options for the resizable." }, { "code": null, "e": 27749, "s": 27742, "text": "Syntax" }, { "code": null, "e": 27812, "s": 27749, "text": " \n$( \".selector\" ).resizable( \"option\", { disabled: true } );\n" }, { "code": null, "e": 27925, "s": 27812, "text": "This action returns a jQuery object containing the resizable element. This method does not accept any arguments." }, { "code": null, "e": 27943, "s": 27925, "text": "Action - widget()" }, { "code": null, "e": 28056, "s": 27943, "text": "This action returns a jQuery object containing the resizable element. This method does not accept any arguments." }, { "code": null, "e": 28063, "s": 28056, "text": "Syntax" }, { "code": null, "e": 28119, "s": 28063, "text": " \nvar widget = $( \".selector\" ).resizable( \"widget\" );\n" }, { "code": null, "e": 28266, "s": 28119, "text": "Now let us see an example using the actions from the above table. The following example demonstrates the use of destroy() and disable() methods." }, { "code": null, "e": 29800, "s": 28266, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Resizable functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-widget-header {\n background:#b9cd6d;\n border: 1px solid #b9cd6d;\n color: #FFFFFF;\n font-weight: bold;\n }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n #resizable-12,#resizable-13 { width: 150px; height: 150px; \n padding: 0.5em;text-align: center; margin: 0; }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#resizable-12\" ).resizable();\n $( \"#resizable-12\" ).resizable('disable');\n $( \"#resizable-13\" ).resizable();\n $( \"#resizable-13\" ).resizable('destroy');\t\n });\n </script>\n </head>\n\n <body>\n <!-- HTML --> \n <div id = \"resizable-12\" class = \"ui-widget-content\"> \n <h3 class = \"ui-widget-header\">I'm disable!!</h3>\n </div><br>\n <div id = \"resizable-13\" class = \"ui-widget-content\"> \n <h3 class = \"ui-widget-header\">I'm Destroyed!!</h3>\n </div>\n </body>\n</html>" }, { "code": null, "e": 29960, "s": 29800, "text": "Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, you should see the following output βˆ’" }, { "code": null, "e": 30055, "s": 29960, "text": "You cannot resize the first square box as its disabled and the second square box is destroyed." }, { "code": null, "e": 30256, "s": 30055, "text": "In addition to the resizable (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below βˆ’" }, { "code": null, "e": 30319, "s": 30256, "text": "This event is triggered when the resizable element is created." }, { "code": null, "e": 30345, "s": 30319, "text": "Event - create(event, ui)" }, { "code": null, "e": 30464, "s": 30345, "text": "This event is triggered when the resizable element is created. Where event is of type Event, and ui is of type\nObject." }, { "code": null, "e": 30471, "s": 30464, "text": "Syntax" }, { "code": null, "e": 30538, "s": 30471, "text": "$( \".selector\" ).resizable({\ncreate: function( event, ui ) {}\n});\n" }, { "code": null, "e": 30612, "s": 30538, "text": "This event is triggered when the handler of resizable element is dragged." }, { "code": null, "e": 30638, "s": 30612, "text": "Event - resize(event, ui)" }, { "code": null, "e": 30796, "s": 30638, "text": "This event is triggered when the handler of resizable element is dragged. Where event is of type Event, and ui\nis of type Object. Possible values of ui are βˆ’" }, { "code": null, "e": 30858, "s": 30796, "text": "element βˆ’ A jQuery object representing the resizable element." }, { "code": null, "e": 30920, "s": 30858, "text": "element βˆ’ A jQuery object representing the resizable element." }, { "code": null, "e": 30992, "s": 30920, "text": "helper βˆ’ A jQuery object representing the helper that is being resized." }, { "code": null, "e": 31064, "s": 30992, "text": "helper βˆ’ A jQuery object representing the helper that is being resized." }, { "code": null, "e": 31156, "s": 31064, "text": "originalElement βˆ’ The jQuery object representing the original element before it is wrapped." }, { "code": null, "e": 31248, "s": 31156, "text": "originalElement βˆ’ The jQuery object representing the original element before it is wrapped." }, { "code": null, "e": 31341, "s": 31248, "text": "originalPosition βˆ’ The position represented as {left, top } before the resizable is resized." }, { "code": null, "e": 31434, "s": 31341, "text": "originalPosition βˆ’ The position represented as {left, top } before the resizable is resized." }, { "code": null, "e": 31524, "s": 31434, "text": "originalSize βˆ’ The size represented as { width, height } before the resizable is resized." }, { "code": null, "e": 31614, "s": 31524, "text": "originalSize βˆ’ The size represented as { width, height } before the resizable is resized." }, { "code": null, "e": 31675, "s": 31614, "text": "position βˆ’ The current position represented as {left, top }." }, { "code": null, "e": 31736, "s": 31675, "text": "position βˆ’ The current position represented as {left, top }." }, { "code": null, "e": 31794, "s": 31736, "text": "size βˆ’ The current size represented as { width, height }." }, { "code": null, "e": 31852, "s": 31794, "text": "size βˆ’ The current size represented as { width, height }." }, { "code": null, "e": 31859, "s": 31852, "text": "Syntax" }, { "code": null, "e": 31926, "s": 31859, "text": "$( \".selector\" ).resizable({\nresize: function( event, ui ) {}\n});\n" }, { "code": null, "e": 31986, "s": 31926, "text": "This event is triggered at the start of a resize operation." }, { "code": null, "e": 32011, "s": 31986, "text": "Event - start(event, ui)" }, { "code": null, "e": 32155, "s": 32011, "text": "This event is triggered at the start of a resize operation. Where event is of type Event, and ui is of type\nObject. Possible values of ui are βˆ’" }, { "code": null, "e": 32217, "s": 32155, "text": "element βˆ’ A jQuery object representing the resizable element." }, { "code": null, "e": 32279, "s": 32217, "text": "element βˆ’ A jQuery object representing the resizable element." }, { "code": null, "e": 32351, "s": 32279, "text": "helper βˆ’ A jQuery object representing the helper that is being resized." }, { "code": null, "e": 32423, "s": 32351, "text": "helper βˆ’ A jQuery object representing the helper that is being resized." }, { "code": null, "e": 32515, "s": 32423, "text": "originalElement βˆ’ The jQuery object representing the original element before it is wrapped." }, { "code": null, "e": 32607, "s": 32515, "text": "originalElement βˆ’ The jQuery object representing the original element before it is wrapped." }, { "code": null, "e": 32700, "s": 32607, "text": "originalPosition βˆ’ The position represented as {left, top } before the resizable is resized." }, { "code": null, "e": 32793, "s": 32700, "text": "originalPosition βˆ’ The position represented as {left, top } before the resizable is resized." }, { "code": null, "e": 32883, "s": 32793, "text": "originalSize βˆ’ The size represented as { width, height } before the resizable is resized." }, { "code": null, "e": 32973, "s": 32883, "text": "originalSize βˆ’ The size represented as { width, height } before the resizable is resized." }, { "code": null, "e": 33034, "s": 32973, "text": "position βˆ’ The current position represented as {left, top }." }, { "code": null, "e": 33095, "s": 33034, "text": "position βˆ’ The current position represented as {left, top }." }, { "code": null, "e": 33153, "s": 33095, "text": "size βˆ’ The current size represented as { width, height }." }, { "code": null, "e": 33211, "s": 33153, "text": "size βˆ’ The current size represented as { width, height }." }, { "code": null, "e": 33218, "s": 33211, "text": "Syntax" }, { "code": null, "e": 33285, "s": 33218, "text": "$( \".selector\" ).resizable({\n start: function( event, ui ) {}\n});\n" }, { "code": null, "e": 33343, "s": 33285, "text": "This event is triggered at the end of a resize operation." }, { "code": null, "e": 33367, "s": 33343, "text": "Event - stop(event, ui)" }, { "code": null, "e": 33509, "s": 33367, "text": "This event is triggered at the end of a resize operation. Where event is of type Event, and ui is of type\nObject. Possible values of ui are βˆ’" }, { "code": null, "e": 33571, "s": 33509, "text": "element βˆ’ A jQuery object representing the resizable element." }, { "code": null, "e": 33633, "s": 33571, "text": "element βˆ’ A jQuery object representing the resizable element." }, { "code": null, "e": 33705, "s": 33633, "text": "helper βˆ’ A jQuery object representing the helper that is being resized." }, { "code": null, "e": 33777, "s": 33705, "text": "helper βˆ’ A jQuery object representing the helper that is being resized." }, { "code": null, "e": 33869, "s": 33777, "text": "originalElement βˆ’ The jQuery object representing the original element before it is wrapped." }, { "code": null, "e": 33961, "s": 33869, "text": "originalElement βˆ’ The jQuery object representing the original element before it is wrapped." }, { "code": null, "e": 34054, "s": 33961, "text": "originalPosition βˆ’ The position represented as {left, top } before the resizable is resized." }, { "code": null, "e": 34147, "s": 34054, "text": "originalPosition βˆ’ The position represented as {left, top } before the resizable is resized." }, { "code": null, "e": 34237, "s": 34147, "text": "originalSize βˆ’ The size represented as { width, height } before the resizable is resized." }, { "code": null, "e": 34327, "s": 34237, "text": "originalSize βˆ’ The size represented as { width, height } before the resizable is resized." }, { "code": null, "e": 34388, "s": 34327, "text": "position βˆ’ The current position represented as {left, top }." }, { "code": null, "e": 34449, "s": 34388, "text": "position βˆ’ The current position represented as {left, top }." }, { "code": null, "e": 34506, "s": 34449, "text": "size βˆ’ The current size represented as { width,height }." }, { "code": null, "e": 34563, "s": 34506, "text": "size βˆ’ The current size represented as { width,height }." }, { "code": null, "e": 34570, "s": 34563, "text": "Syntax" }, { "code": null, "e": 34635, "s": 34570, "text": "$( \".selector\" ).resizable({\nstop: function( event, ui ) {}\n});\n" }, { "code": null, "e": 34786, "s": 34635, "text": "The following example demonstrates the event method usage during resize functionality. This example demonstrates the use of events create, and resize." }, { "code": null, "e": 36527, "s": 34786, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Resizable functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-widget-header {\n background:#b9cd6d;\n border: 1px solid #b9cd6d;\n color: #FFFFFF;\n font-weight: bold;\n }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n #resizable-14{ width: 150px; height: 150px; \n padding: 0.5em;text-align: center; margin: 0; }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#resizable-14\" ).resizable({\n create: function( event, ui ) {\n $(\"#resizable-15\").text (\"I'm Created!!\");\n },\n resize: function (event, ui) {\n $(\"#resizable-16\").text (\"top = \" + ui.position.top +\n \", left = \" + ui.position.left +\n \", width = \" + ui.size.width +\n \", height = \" + ui.size.height);\n }\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"resizable-14\" class = \"ui-widget-content\"> \n <h3 class = \"ui-widget-header\">Resize !!</h3>\n </div><br>\n <span id = \"resizable-15\"></span><br>\n <span id = \"resizable-16\"></span>\n </body>\n</html>" }, { "code": null, "e": 36688, "s": 36527, "text": "Let us save the above code in an HTML file resizeexample.htm and open it in a standard browser which supports javascript, should must see the following output βˆ’" }, { "code": null, "e": 36771, "s": 36688, "text": "Drag the square box and you will see the output getting displayed on resize event." }, { "code": null, "e": 36778, "s": 36771, "text": " Print" }, { "code": null, "e": 36789, "s": 36778, "text": " Add Notes" } ]
Kotlin Constructors
In the previous chapter, we created an object of a class, and specified the properties inside the class, like this: class Car { var brand = "" var model = "" var year = 0 } fun main() { val c1 = Car() c1.brand = "Ford" c1.model = "Mustang" c1.year = 1969 } In Kotlin, there's a faster way of doing this, by using a constructor. A constructor is like a special function, and it is defined by using two parantheses () after the class name. You can specify the properties inside of the parantheses (like passing parameters into a regular function). The constructor will initialize the properties when you create an object of a class. Just remember to specify the type of the property/variable: class Car(var brand: String, var model: String, var year: Int) fun main() { val c1 = Car("Ford", "Mustang", 1969) } Now it's even easier to specify multiple objects of one class: class Car(var brand: String, var model: String, var year: Int) fun main() { val c1 = Car("Ford", "Mustang", 1969) val c2 = Car("BMW", "X5", 1999) val c3 = Car("Tesla", "Model S", 2020) } We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 116, "s": 0, "text": "In the previous chapter, we created an object of a class, and specified the properties inside the class, like this:" }, { "code": null, "e": 272, "s": 116, "text": "class Car {\n var brand = \"\"\n var model = \"\"\n var year = 0\n}\n\nfun main() {\n val c1 = Car()\n c1.brand = \"Ford\"\n c1.model = \"Mustang\"\n c1.year = 1969\n}" }, { "code": null, "e": 343, "s": 272, "text": "In Kotlin, there's a faster way of doing this, by using a constructor." }, { "code": null, "e": 564, "s": 343, "text": "A \nconstructor is like a special function, and it is defined by using two parantheses () \nafter the class name. You can specify the properties inside of the parantheses (like passing \nparameters into a regular function)." }, { "code": null, "e": 710, "s": 564, "text": "The constructor will initialize the properties when you create an object of a class. Just remember to specify the \ntype of the property/variable:" }, { "code": null, "e": 829, "s": 710, "text": "class Car(var brand: String, var model: String, var year: Int)\n\nfun main() {\n val c1 = Car(\"Ford\", \"Mustang\", 1969)\n}" }, { "code": null, "e": 892, "s": 829, "text": "Now it's even easier to specify multiple objects of one class:" }, { "code": null, "e": 1086, "s": 892, "text": "class Car(var brand: String, var model: String, var year: Int)\n\nfun main() {\n val c1 = Car(\"Ford\", \"Mustang\", 1969)\n val c2 = Car(\"BMW\", \"X5\", 1999)\n val c3 = Car(\"Tesla\", \"Model S\", 2020)\n}" }, { "code": null, "e": 1119, "s": 1086, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1161, "s": 1119, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1268, "s": 1161, "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": 1287, "s": 1268, "text": "help@w3schools.com" } ]
Select multiple columns in a Pandas DataFrame
To select multiple columns in a Pandas DataFrame, we can create new a DataFrame from the existing DataFrame Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df. Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df. Print the input DataFrame. Print the input DataFrame. Create a new DataFrame, df1, with selection of multiple columns. Create a new DataFrame, df1, with selection of multiple columns. Print the new DataFrame with multiple selected columns. Print the new DataFrame with multiple selected columns. Live Demo import pandas as pd df = pd.DataFrame( { "x": [5, 2, 1, 9], "y": [4, 1, 5, 10], "z": [4, 1, 5, 0] } ) print "Input DataFrame is:\n", df df1 = df[['x', 'y']] print "After selecting multiple columns:\n", df1 Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 After selecting multiple columns: x y 0 5 4 1 2 1 2 1 5 3 9 10
[ { "code": null, "e": 1170, "s": 1062, "text": "To select multiple columns in a Pandas DataFrame, we can create new a DataFrame from the existing DataFrame" }, { "code": null, "e": 1254, "s": 1170, "text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df." }, { "code": null, "e": 1338, "s": 1254, "text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df." }, { "code": null, "e": 1365, "s": 1338, "text": "Print the input DataFrame." }, { "code": null, "e": 1392, "s": 1365, "text": "Print the input DataFrame." }, { "code": null, "e": 1457, "s": 1392, "text": "Create a new DataFrame, df1, with selection of multiple columns." }, { "code": null, "e": 1522, "s": 1457, "text": "Create a new DataFrame, df1, with selection of multiple columns." }, { "code": null, "e": 1578, "s": 1522, "text": "Print the new DataFrame with multiple selected columns." }, { "code": null, "e": 1634, "s": 1578, "text": "Print the new DataFrame with multiple selected columns." }, { "code": null, "e": 1645, "s": 1634, "text": " Live Demo" }, { "code": null, "e": 1878, "s": 1645, "text": "import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"x\": [5, 2, 1, 9],\n \"y\": [4, 1, 5, 10],\n \"z\": [4, 1, 5, 0]\n }\n)\n\nprint \"Input DataFrame is:\\n\", df\n\ndf1 = df[['x', 'y']]\nprint \"After selecting multiple columns:\\n\", df1" }, { "code": null, "e": 2028, "s": 1878, "text": "Input DataFrame is:\n x y z\n0 5 4 4\n1 2 1 1\n2 1 5 5\n3 9 10 0\n\nAfter selecting multiple columns:\n x y\n0 5 4\n1 2 1\n2 1 5\n3 9 10" } ]
Reinforcement Learning β€” Cliff Walking Implementation | by Jeremy Zhang | Towards Data Science
The essence of reinforcement learning is the way the agent iteratively updates its estimation of state, action pairs by trials(if you are not familiar with value iteration, please check my previous example). In previous posts, I have been repetitively talking about Q-learning and how the agent updates its Q-value based on this method. In fact, besides the update method defined in Q-learning, there are more other ways of updating estimations of state, action pairs. In this post, we will together explore another method called SARSA, compare this method with Q-learning and see how the difference in update methods affects an agent’s behaviour. Let’s first talk of temporal difference, which is the core of an updating method. We know that at each iteration or episode, an agent explores the environment by taking action following a policy(say Ξ΅-greedy), and based on its latest observation, which is summarised as a value of state-action, it updates its current estimates by tweaking the current estimation a little bit towards the latest observation, and the difference between the values of latest observation and last is called temporal difference. And it is from this temporal difference that our agent learns and updates itself. The definition of temporal difference distinguishes methods from each other. In order to give you a more concrete sense, let’s directly dive into the algorithm definition and check the difference. It is clear that the only difference lies in updating the Q function. In SARSA(by the way, the name SARSA comes explicitly from the process of the agent, which state, action, reward, state, action ...), the temporal difference is defined as : [R + Q(S', A') - Q(S, A)] where the observed Q value of next state, action pair contributes directly to the update of current state. SARSA is also called on-policy, because the update process is consistent with the current policy. However the temporal difference defined in Q-learning is: [R + max_a(Q(S', a)) - Q(S, A)] where the observed Q value of next state, action pair may not directly contribute to the update of current state. The Q-learning always uses the max value of next state, in which case the state, action being taken to update the Q value may not be consistent with the current policy, thus it is called off-policy method. The difference, in fact, could result in different behaviours of an agent. The gut feeling is that Q-learning(off-policy) is more optimistic in value estimation, where it always assume the best action be taken in the process, which, could result in bolder actions of the agent. Whereas SARSA(off-policy) is more conservative in value estimation, which result in saver actions of the agent. To clearly demonstrate this point, let’s get into an example, cliff walking, which is drawn from the reinforcement learning an introduction. This is a standard un-discounted, episodic task, with start and goal states, and the usual actions causing movement up, down, right, and left. Reward is -1 on all transitions except those into the region marked Cliff. Stepping into this region incurs a reward of optimal path -100 and sends the agent instantly back to the start. This is a typical 2 dimensional board game, so the board settings are mostly same as the example I described here. In the following sections, I will mainly emphasise on the implementation of SARSA and Q-learning, and the comparison of resulted agent’s behaviours between these two methods. In a nut shell, we will have a Cliff class which represents the board that is able to: Keep track of an agent’s current positionGiven an action, decide the agent’s next position and judge whether it is the end of gameGive feedback as reward Keep track of an agent’s current position Given an action, decide the agent’s next position and judge whether it is the end of game Give feedback as reward These are the major function inside class Cliff. The nxtPosition function takes in an action and returns the agent’s next position on the board, and if the agent bashes its head into the wall(reaches the border), it remains at the same position. The giveReward function gives reward -1 to all states except the cliff area, where results in reward -100. Let’s have a look at the board we implemented. The agent starts at the left end of the board with a sign S, and the only way to end the game is to reach the right end of the board with a sign G. And * represents the cliff area. In terms of game playing, we will have an Agent class representing our agent, and inside the agent class, there is a function decides the agent’s action taking, which is again the Ξ΅-greedy policy. (Check out full implementation here) The key difference lies in the play function: In each episode(each round of the game), we keep track of our agent’s action, state and reward in the list self.states . And at the end of the game, we update the Q function(the self.state_actions) in reversed fashion β€” if the method is SARSA(on-policy), the newly updated reward (which essentially is Q(S', A')) will be directly applied to next update, and if the method is Q-learning, there is one more step, reward = np.max(list(self.state_actions[pos].values())) which takes the maximum value of all actions in that position to the next round of update.The maximum operation shapes the agent behaviour and enables it to take more adventurous actions. I ran both methods with exploration rate 0.1 for 500 rounds and took the final (state, action) they learned. The result I learnt is slightly different from the optimal result in the book, but it is clear enough to see the difference between the two. The conclusion part I will take a reference from Sutton’s book, which perfectly summarises the difference between the two methods: Q-learning learns values for the optimal policy, that which travels right along the edge of the cliff. Unfortunately, this results in its occasionally falling off the cliff because of the β€œepsilon-greedy” action selection. SARSA, on the other hand, takes the action selection into account and learns the longer but safer path through the upper part of the grid. Although Q-learning actually learns the values of the optimal policy, its online performance is worse than that of SARSA, which learns the roundabout policy. Of course, if Ξ΅ were gradually reduced, then both methods would asymptotically converge to the optimal policy. And finally, please check out the full code here. You are welcomed to contribute, and if you have any questions or suggestions, please raise comment below!
[ { "code": null, "e": 827, "s": 179, "text": "The essence of reinforcement learning is the way the agent iteratively updates its estimation of state, action pairs by trials(if you are not familiar with value iteration, please check my previous example). In previous posts, I have been repetitively talking about Q-learning and how the agent updates its Q-value based on this method. In fact, besides the update method defined in Q-learning, there are more other ways of updating estimations of state, action pairs. In this post, we will together explore another method called SARSA, compare this method with Q-learning and see how the difference in update methods affects an agent’s behaviour." }, { "code": null, "e": 1417, "s": 827, "text": "Let’s first talk of temporal difference, which is the core of an updating method. We know that at each iteration or episode, an agent explores the environment by taking action following a policy(say Ξ΅-greedy), and based on its latest observation, which is summarised as a value of state-action, it updates its current estimates by tweaking the current estimation a little bit towards the latest observation, and the difference between the values of latest observation and last is called temporal difference. And it is from this temporal difference that our agent learns and updates itself." }, { "code": null, "e": 1614, "s": 1417, "text": "The definition of temporal difference distinguishes methods from each other. In order to give you a more concrete sense, let’s directly dive into the algorithm definition and check the difference." }, { "code": null, "e": 1857, "s": 1614, "text": "It is clear that the only difference lies in updating the Q function. In SARSA(by the way, the name SARSA comes explicitly from the process of the agent, which state, action, reward, state, action ...), the temporal difference is defined as :" }, { "code": null, "e": 1883, "s": 1857, "text": "[R + Q(S', A') - Q(S, A)]" }, { "code": null, "e": 2088, "s": 1883, "text": "where the observed Q value of next state, action pair contributes directly to the update of current state. SARSA is also called on-policy, because the update process is consistent with the current policy." }, { "code": null, "e": 2146, "s": 2088, "text": "However the temporal difference defined in Q-learning is:" }, { "code": null, "e": 2178, "s": 2146, "text": "[R + max_a(Q(S', a)) - Q(S, A)]" }, { "code": null, "e": 2498, "s": 2178, "text": "where the observed Q value of next state, action pair may not directly contribute to the update of current state. The Q-learning always uses the max value of next state, in which case the state, action being taken to update the Q value may not be consistent with the current policy, thus it is called off-policy method." }, { "code": null, "e": 2888, "s": 2498, "text": "The difference, in fact, could result in different behaviours of an agent. The gut feeling is that Q-learning(off-policy) is more optimistic in value estimation, where it always assume the best action be taken in the process, which, could result in bolder actions of the agent. Whereas SARSA(off-policy) is more conservative in value estimation, which result in saver actions of the agent." }, { "code": null, "e": 3029, "s": 2888, "text": "To clearly demonstrate this point, let’s get into an example, cliff walking, which is drawn from the reinforcement learning an introduction." }, { "code": null, "e": 3359, "s": 3029, "text": "This is a standard un-discounted, episodic task, with start and goal states, and the usual actions causing movement up, down, right, and left. Reward is -1 on all transitions except those into the region marked Cliff. Stepping into this region incurs a reward of optimal path -100 and sends the agent instantly back to the start." }, { "code": null, "e": 3649, "s": 3359, "text": "This is a typical 2 dimensional board game, so the board settings are mostly same as the example I described here. In the following sections, I will mainly emphasise on the implementation of SARSA and Q-learning, and the comparison of resulted agent’s behaviours between these two methods." }, { "code": null, "e": 3736, "s": 3649, "text": "In a nut shell, we will have a Cliff class which represents the board that is able to:" }, { "code": null, "e": 3890, "s": 3736, "text": "Keep track of an agent’s current positionGiven an action, decide the agent’s next position and judge whether it is the end of gameGive feedback as reward" }, { "code": null, "e": 3932, "s": 3890, "text": "Keep track of an agent’s current position" }, { "code": null, "e": 4022, "s": 3932, "text": "Given an action, decide the agent’s next position and judge whether it is the end of game" }, { "code": null, "e": 4046, "s": 4022, "text": "Give feedback as reward" }, { "code": null, "e": 4399, "s": 4046, "text": "These are the major function inside class Cliff. The nxtPosition function takes in an action and returns the agent’s next position on the board, and if the agent bashes its head into the wall(reaches the border), it remains at the same position. The giveReward function gives reward -1 to all states except the cliff area, where results in reward -100." }, { "code": null, "e": 4446, "s": 4399, "text": "Let’s have a look at the board we implemented." }, { "code": null, "e": 4627, "s": 4446, "text": "The agent starts at the left end of the board with a sign S, and the only way to end the game is to reach the right end of the board with a sign G. And * represents the cliff area." }, { "code": null, "e": 4861, "s": 4627, "text": "In terms of game playing, we will have an Agent class representing our agent, and inside the agent class, there is a function decides the agent’s action taking, which is again the Ξ΅-greedy policy. (Check out full implementation here)" }, { "code": null, "e": 4907, "s": 4861, "text": "The key difference lies in the play function:" }, { "code": null, "e": 5318, "s": 4907, "text": "In each episode(each round of the game), we keep track of our agent’s action, state and reward in the list self.states . And at the end of the game, we update the Q function(the self.state_actions) in reversed fashion β€” if the method is SARSA(on-policy), the newly updated reward (which essentially is Q(S', A')) will be directly applied to next update, and if the method is Q-learning, there is one more step," }, { "code": null, "e": 5374, "s": 5318, "text": "reward = np.max(list(self.state_actions[pos].values()))" }, { "code": null, "e": 5562, "s": 5374, "text": "which takes the maximum value of all actions in that position to the next round of update.The maximum operation shapes the agent behaviour and enables it to take more adventurous actions." }, { "code": null, "e": 5671, "s": 5562, "text": "I ran both methods with exploration rate 0.1 for 500 rounds and took the final (state, action) they learned." }, { "code": null, "e": 5812, "s": 5671, "text": "The result I learnt is slightly different from the optimal result in the book, but it is clear enough to see the difference between the two." }, { "code": null, "e": 5943, "s": 5812, "text": "The conclusion part I will take a reference from Sutton’s book, which perfectly summarises the difference between the two methods:" }, { "code": null, "e": 6574, "s": 5943, "text": "Q-learning learns values for the optimal policy, that which travels right along the edge of the cliff. Unfortunately, this results in its occasionally falling off the cliff because of the β€œepsilon-greedy” action selection. SARSA, on the other hand, takes the action selection into account and learns the longer but safer path through the upper part of the grid. Although Q-learning actually learns the values of the optimal policy, its online performance is worse than that of SARSA, which learns the roundabout policy. Of course, if Ξ΅ were gradually reduced, then both methods would asymptotically converge to the optimal policy." } ]
VBScript - Interview Questions
Dear readers, these VBScript Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of VBScript. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: Microsoft VBScript (Visual Basic Script) is a general-purpose, lightweight and active scripting language developed by Microsoft that is modelled on Visual Basic. Nowadays, VBScript is the primary scripting language for Quick Test Professional (QTP), which is a test automation tool. Following are the advantages of VBScript βˆ’ VBScript is a lightweight scripting language, which has a lightning fast interpreter. VBScript is a lightweight scripting language, which has a lightning fast interpreter. VBScript, for the most part, is case insensitive. It has a very simple syntax, easy to learn and to implement. VBScript, for the most part, is case insensitive. It has a very simple syntax, easy to learn and to implement. Unlike C++ or Java, VBScript is an object-based scripting language and NOT an Object-Oriented Programming language. Unlike C++ or Java, VBScript is an object-based scripting language and NOT an Object-Oriented Programming language. It uses Component Object Model (COM) in order to access the elements of the environment in which it is executing. It uses Component Object Model (COM) in order to access the elements of the environment in which it is executing. Successful execution of VBScript can happen only if it is executed in Host Environment such as Internet Explorer (IE), Internet Information Services (IIS) and Windows Scripting Host (WSH). Successful execution of VBScript can happen only if it is executed in Host Environment such as Internet Explorer (IE), Internet Information Services (IIS) and Windows Scripting Host (WSH). Following are the disadvantages of VBScript βˆ’ VBscript is used only by IE Browsers. Other browsers such as Chrome, Firefox DONOT Support VBScript. Hence, JavaScript is preferred over VBScript. VBscript is used only by IE Browsers. Other browsers such as Chrome, Firefox DONOT Support VBScript. Hence, JavaScript is preferred over VBScript. VBScript has a Limited command line support. VBScript has a Limited command line support. Since there is no development environment available by default, debugging is difficult. Since there is no development environment available by default, debugging is difficult. No! VBScript is a case-insensitive language. This means that language keywords, variables, function names and any other identifiers need NOT be typed with a consistent capitalization of letters. So identifiers int_counter, INT_Counter and INT_COUNTER have the same meaning within VBScript. Variable is a named memory location used to hold a value that can be changed during the script execution. VBScript has only ONE fundamental data type, Variant. Rules for Declaring Variables βˆ’ Variable Name must begin with an alphabet. Variable Name must begin with an alphabet. Variable names cannot exceed 255 characters. Variable names cannot exceed 255 characters. Variables Should NOT contain a period(.) Variables Should NOT contain a period(.) Variable Names should be unique in the declared context. Variable Names should be unique in the declared context. Variables are declared using "dim" keyword. No! Since there is only ONE fundamental data type, all the declared variables are variant by default. Hence, a user NEED NOT mention the type of data during declaration. The numeric values should be assigned without double quotes. The String values should be enclosed within doublequotes("). Date and Time variables should be enclosed within hash symbol(#). Following are the scopes of variable in VBScript βˆ’ Dim Dim Public Public Private Private Variables declared using "Dim" keyword at a Procedure level are available only within the same procedure. Variables declared using "Dim" Keyword at script level are available to all the procedures within the same script. Variables declared using "Public" Keyword are available to all the procedures across all the associated scripts. When declaring a variable of type "public", Dim keyword is replaced by "Public". Variables that are declared as "Private" have scope only within that script in which they are declared. When declaring a variable of type "Private", Dim keyword is replaced by "Private". Constants are declared using "const" keyword. The Public constants are available for all the scripts and procedures. Private Constants are available within the procedure or Class. VBScript language supports following types of operators βˆ’ Arithmetic Operators Arithmetic Operators Comparison Operators Comparison Operators Logical (or Relational) Operators Logical (or Relational) Operators Concatenation Operators Concatenation Operators MOD opeator is used to get the modulus of two numbers. Example βˆ’ Dim a : a = 5 Dim b : b = 10 Dim c c = b MOD a Document.write ("Modulus Result is " &c) ^ opeator is used to get the exponent of two numbers. Example βˆ’ Dim a : a = 5 Dim b : b = 10 Dim c c = b ^ a Document.write ("Exponentiation Result is " &c) <> operator is used to check if two numbers are equal or not. Example βˆ’ Dim a : a = 5 Dim b : b = 10 Dim c c = b <> a Document.write ("Equality Check is " &c) XOR Called Logical Exclusion operator. It is used to do an XOR operation. Example βˆ’ A. Dim a : a = 5 Dim b : b = 10 Dim c c = b XOR a Document.write ("XOR Check is " &c) + operator adds two Values as Variable Values are Numeric. So A + B will give 15. + operator concatenates two Values if values are string. So A + B will give VBScript. & operator concatenates two values. So A + B will give 510. & operator concatenates two values. So A & B will give VBScript. VBScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page. The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this βˆ’ Syntax βˆ’ document.cookie = "key1 = value1; key2 = value2; expires = date"; Here expires attribute is optional. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and after that cookies' value will not be accessible. Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value. You can use strings' split() function to break the string into key and values. Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past. Using CDbl function, which converts a given number of any variant subtype to double. Example βˆ’ x = 123 y = 123.882 document.write("x value after converting to double - " & CDbl(x) & "<br />") Using CInt function, which converts a given number of any variant subtype to Integer. Example βˆ’ x = 123 y = 123.882 document.write("y value after converting to Int - " & CInt(y) & "<br />") Using CLng function, which converts a given number of any variant subtype to Long. Example βˆ’ x = 123 y = 123.882 document.write("x value after converting to Long -" & CLng(x) & "<br />") Using CSng function, which converts a given number of any variant subtype to Single. Example βˆ’ x = 123 y = 123.882 document.write("x value after converting to Single -" & CSng(x) & "<br />") Using Hex function, which converts a given number of any variant subtype to Hexadecimal. Example βˆ’ x = 123 y = 123.882 document.write("y value after converting to Hex -" & Hex(y) & "<br />") Using FormatNumber function, which would return an expression formatted as a number. Example βˆ’ Dim num : num = -645.998651 document.write(FormatNumber(num, 3))& "<br/>" '-645.999 Using FormatPercent function, which would return an expression formatted as a percent. Example βˆ’ Dim num : num = -645.998651 document.write(FormatPercent(num, 2))& "<br/>" '-64,599.86% Using Int function, which returns the integer part of the given number. Example βˆ’ Dim num : num = -645.998651 document.write("int Result of num is : " & int(num))& "<br/>" '-646 Using Log function, which returns the natural logarithm of the given number. Example βˆ’ Dim num : num = 210 document.write("Log Result of num2 is : " & Log(num2))& "<br/>" '5.34710753071747 Using Oct function, which returns the octal value of the given number. Example βˆ’ Dim num : num = -645.998651 document.write("Oct Result of num is : " & Oct(num))& "<br/>" '37777776572 Using Hex function, which returns the hexadecimal value of the given number. Example βˆ’ Dim num : num = -645.998651 document.write("Hex Result of num is : " & Hex(num))& "<br/>" 'FFFFFD7A Using Rnd function,which returns a random number between 0 and 1. Example βˆ’ Dim num : num = -645.998651 document.write("Rnd Result of num is : " & Rnd(num))& "<br/>" '0.5130115 Using Sqr function, which returns the square root of the given number. Example βˆ’ Dim num : num = -210 document.write("Sqr Result of num is : " & Sqr(num))& "<br/>" '14.4913767461894 Using Abs function, which returns the absolute value of the given number. Example βˆ’ Dim num : num = -645.998651 document.write("Abs Result of num is : " & Abs(num))& "<br/>" '645.998651 Using Exp function, which returns the value of e raised to the specified number. Example βˆ’ Dim num : num = -645.998651 document.write("Exp Result of num is : " & Exp(num))& "<br/>" '2.79479883633128E-281 Using InStr function, which returns the first occurrence of one string within another string. The search happens from left to right. Using InStrRev function, which returns the first occurrence of one string within another string. The search happens from right to left. Using Lcase function, which returns the lower case of the specified string. Using Ucase function, which returns the upper case of the specified string. Using Ltrim function, which returns a string after removing the spaces on the left side of the specified string. Using Rtrim function, which returns a string after removing the spaces on the left side of the specified string. Using Trim function, which returns a string value after removing both leading and trailing blank spaces. Using Len function, which returns the length of the given string. Using Replace function, which returns a string after replacing a string with another string. Using Space function, which fills a string with the specified number of spaces. Using StrComp function, which returns an integer value after comparing the two specified strings. The StrComp Function returns an integer value after comparing the two given strings. It can return any of the three values -1, 0 or 1 based on the input strings to be compared. If String 1 < String 2 then StrComp returns -1 If String 1 < String 2 then StrComp returns -1 If String 1 = String 2 then StrComp returns 0 If String 1 = String 2 then StrComp returns 0 If String 1 > String 2 then StrComp returns 1 If String 1 > String 2 then StrComp returns 1 Using String function, which returns a String with a specified character the specified number of times. Using StrReverse function, whihc returns a String after reversing the sequece of the characters of the given string. rrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the below example, the size of the array is mentioned in the brackets. Example βˆ’ 'Method 1 : Using Dim Dim arr1() 'Without Size 'Method 2 : Mentioning the Size Dim arr2(5) 'Declared with size of 5 'Method 3 : using 'Array' Parameter Dim arr3 arr3 = Array("apple","Orange","Grapes") The values are assigned to the array by specifying array index value against each one of the values to be assigned. Example βˆ’ Dim arr(5) arr(0) = "VBScript" 'String document.write("Value stored in Array index 0 : " & arr(0) & "<br />") Using ReDim statement, we can declare dynamic-array variables and allocate or reallocate storage space. Using LBound function, which returns an integer that corresponds to the smallest subscript of the given arrays. Using UBound function, which returns an integer that corresponds to the largest subscript of the given arrays. Using Split function, which returns an array that contains a specified number of values. Splitted based on a Delimiter. Using Join function, which returns a String that contains a specified number of substrings in an array. This is an exact opposite function of Split Method. Using Filter function, returns a zero based array that contains a subset of a string array based on a specific filter criteria. Using IsArray function, which returns a boolean value that indicates whether or not the input variable is an array. Using Erase Function, which recovers the allocated memory for the array variables. The most common way to define a function in VBScript is by using the Function keyword, followed by a unique function name and it may or may not carry a list of parameters and a statement with a End Function keyword, which indicates the end of the function. To invoke a function somewhere later in the script, you would simple need to write the name of that function with the Call keyword. To return a value from a function, simply assign the value to the function name itself. Yes! A function can return multiple values separated by comma as an array assigned to the function name itself. Sub Procedures are similar to functions but there are few differences. Sub procedures DONOT Return a value while functions may or may not return a value. Sub procedures DONOT Return a value while functions may or may not return a value. Sub procedures Can be called without call keyword. Sub procedures Can be called without call keyword. Sub procedures are always enclosed within Sub and End Sub statements. Sub procedures are always enclosed within Sub and End Sub statements. If ByVal is specified, then the arguments are sent as by value when the function or procedure is called. If ByRef is specified, then the arguments are sent as by reference when the function or procedure is called. we need to declare the object and instantiate it using Set Keyword. Example βˆ’ Dim obj Set obj = CreateObject("Scripting.Dictionary") In order to destroy the objects, we need to use Set Keyword followed by the object name and point it to Nothing. Example βˆ’ Dim obj Set obj = CreateObject("Scripting.Dictionary") Set obj = Nothing Class is a construct that is used to define a unique type. Like Object Oriented Programming, VbScript 5.0 supports the creation of classes and it is very similar to writing COM objects with VB. Class is simply the template for an object and we instantiate an object to access the properties and methods of it. Classes can contain variables, properties, methods or events. VBScript classes are enclosed within Class .... End Class 'Defining the Class Class classname 'Declare the object name ... End Class ' Instantiation of the Class Set objectname = new classname Classes can contain variables, which can be of private or public. Variables within classes should follow VBScript naming conventions. By default, the variables in class are Public. That is why they can be accessed outside the class. Example βˆ’ Dim var1 , var2. Private var1 , var2. Public var1 , var2. Class properties, such as Property Let, which handles the process of data validation and assigning the new value to the private variable. Property set, which assigns the new property value to the private object variable. Read-only properties have only a Property Get procedure while write-only properties (which are rare) have only a Property Let or a Property Set procedure. Example βˆ’ Class Comp Private modStrType Private OS Public Property Let ComputerType(strType) modStrType = strType End Property Public Property Get ComputerType() ComputerType = modStrType End Property Public Property Set OperatingSystem(oObj) Set OS = oObj End Property Public Property Get OperatingSystem() Set OperatingSystem = OS End Property End Class Methods allow the class to perform the operation that the developer wants. The Methods are nothing but Functions or Subroutines. Example βˆ’ Class Car Private Model Private Year Public Start() Fuel = 2.45 Pressure = 4.15 End Function End Class There are two events that are automatically associated with every class by default. Class_Initialize and Class_Terminate. Class_Initialize is triggered whenever you instantiate an object based on the class. Class_Terminate event is fired when the object goes out of scope or when the object is set to Nothing. Example βˆ’ In the below example, we will make you understand how the events work in VBScript. 'Instantation of the Object Set objectname = New classname Private Sub Class_Initialize( ) Initalization code goes here End Sub 'When Object is Set to Nothing Private Sub Class_Terminate( ) Termination code goes here End Sub This class provides file system objects which help the developers to work with drives, folders and files. Example βˆ’ Dim oFS, drive Set oFS = CreateObject("Scripting.FileSystemObject") Set drive = oFS.GetDrive(oFS.GetDriveName("C:\")) Document.write drive.VolumeName Drive contains methods and properties that allow you to gather information about a drive attached to the system. File contains methods and properties that allow developers to create, delete or move a file. Files provides a list of all files contained within a folder. Folder provides methods and properties that allow developers to create, delete or move folders. Folders provides a list of all the folders within a Folder. TextStream enables developers to read and write text files. RegExp object helps the developers to match the pattern of strings and the properties and methods help us to work with Regular Expressions easily. Following are the properties of RegExp object βˆ’ Pattern βˆ’ The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object. Pattern βˆ’ The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object. IgnoreCase βˆ’ A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False. IgnoreCase βˆ’ A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False. Global βˆ’ A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False. Global βˆ’ A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False. The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned. The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned. The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn't modify the original string. If we want to capture the error, then Err Object is used. Use Err.Raise to throw an error. Example βˆ’ Err.Raise 6 ' Raise an overflow error. Err.Number gives the error number and Err.Description gives error description. Example βˆ’ Err.Raise 6 ' Raise an overflow error. MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description Err.Clear clear an error. Example βˆ’ Err.Raise 6 ' Raise an overflow error. MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description Err.Clear ' Clear the error. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2520, "s": 2080, "text": "Dear readers, these VBScript Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of VBScript. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:" }, { "code": null, "e": 2803, "s": 2520, "text": "Microsoft VBScript (Visual Basic Script) is a general-purpose, lightweight and active scripting language developed by Microsoft that is modelled on Visual Basic. Nowadays, VBScript is the primary scripting language for Quick Test Professional (QTP), which is a test automation tool." }, { "code": null, "e": 2846, "s": 2803, "text": "Following are the advantages of VBScript βˆ’" }, { "code": null, "e": 2932, "s": 2846, "text": "VBScript is a lightweight scripting language, which has a lightning fast interpreter." }, { "code": null, "e": 3018, "s": 2932, "text": "VBScript is a lightweight scripting language, which has a lightning fast interpreter." }, { "code": null, "e": 3129, "s": 3018, "text": "VBScript, for the most part, is case insensitive. It has a very simple syntax, easy to learn and to implement." }, { "code": null, "e": 3240, "s": 3129, "text": "VBScript, for the most part, is case insensitive. It has a very simple syntax, easy to learn and to implement." }, { "code": null, "e": 3356, "s": 3240, "text": "Unlike C++ or Java, VBScript is an object-based scripting language and NOT an Object-Oriented Programming language." }, { "code": null, "e": 3472, "s": 3356, "text": "Unlike C++ or Java, VBScript is an object-based scripting language and NOT an Object-Oriented Programming language." }, { "code": null, "e": 3586, "s": 3472, "text": "It uses Component Object Model (COM) in order to access the elements of the environment in which it is executing." }, { "code": null, "e": 3700, "s": 3586, "text": "It uses Component Object Model (COM) in order to access the elements of the environment in which it is executing." }, { "code": null, "e": 3889, "s": 3700, "text": "Successful execution of VBScript can happen only if it is executed in Host Environment such as Internet Explorer (IE), Internet Information Services (IIS) and Windows Scripting Host (WSH)." }, { "code": null, "e": 4078, "s": 3889, "text": "Successful execution of VBScript can happen only if it is executed in Host Environment such as Internet Explorer (IE), Internet Information Services (IIS) and Windows Scripting Host (WSH)." }, { "code": null, "e": 4124, "s": 4078, "text": "Following are the disadvantages of VBScript βˆ’" }, { "code": null, "e": 4271, "s": 4124, "text": "VBscript is used only by IE Browsers. Other browsers such as Chrome, Firefox DONOT Support VBScript. Hence, JavaScript is preferred over VBScript." }, { "code": null, "e": 4418, "s": 4271, "text": "VBscript is used only by IE Browsers. Other browsers such as Chrome, Firefox DONOT Support VBScript. Hence, JavaScript is preferred over VBScript." }, { "code": null, "e": 4463, "s": 4418, "text": "VBScript has a Limited command line support." }, { "code": null, "e": 4508, "s": 4463, "text": "VBScript has a Limited command line support." }, { "code": null, "e": 4596, "s": 4508, "text": "Since there is no development environment available by default, debugging is difficult." }, { "code": null, "e": 4684, "s": 4596, "text": "Since there is no development environment available by default, debugging is difficult." }, { "code": null, "e": 4879, "s": 4684, "text": "No! VBScript is a case-insensitive language. This means that language keywords, variables, function names and any other identifiers need NOT be typed with a consistent capitalization of letters." }, { "code": null, "e": 4974, "s": 4879, "text": "So identifiers int_counter, INT_Counter and INT_COUNTER have the same meaning within VBScript." }, { "code": null, "e": 5134, "s": 4974, "text": "Variable is a named memory location used to hold a value that can be changed during the script execution. VBScript has only ONE fundamental data type, Variant." }, { "code": null, "e": 5166, "s": 5134, "text": "Rules for Declaring Variables βˆ’" }, { "code": null, "e": 5209, "s": 5166, "text": "Variable Name must begin with an alphabet." }, { "code": null, "e": 5252, "s": 5209, "text": "Variable Name must begin with an alphabet." }, { "code": null, "e": 5297, "s": 5252, "text": "Variable names cannot exceed 255 characters." }, { "code": null, "e": 5342, "s": 5297, "text": "Variable names cannot exceed 255 characters." }, { "code": null, "e": 5383, "s": 5342, "text": "Variables Should NOT contain a period(.)" }, { "code": null, "e": 5424, "s": 5383, "text": "Variables Should NOT contain a period(.)" }, { "code": null, "e": 5481, "s": 5424, "text": "Variable Names should be unique in the declared context." }, { "code": null, "e": 5538, "s": 5481, "text": "Variable Names should be unique in the declared context." }, { "code": null, "e": 5582, "s": 5538, "text": "Variables are declared using \"dim\" keyword." }, { "code": null, "e": 5752, "s": 5582, "text": "No! Since there is only ONE fundamental data type, all the declared variables are variant by default. Hence, a user NEED NOT mention the type of data during declaration." }, { "code": null, "e": 5813, "s": 5752, "text": "The numeric values should be assigned without double quotes." }, { "code": null, "e": 5874, "s": 5813, "text": "The String values should be enclosed within doublequotes(\")." }, { "code": null, "e": 5940, "s": 5874, "text": "Date and Time variables should be enclosed within hash symbol(#)." }, { "code": null, "e": 5991, "s": 5940, "text": "Following are the scopes of variable in VBScript βˆ’" }, { "code": null, "e": 5995, "s": 5991, "text": "Dim" }, { "code": null, "e": 5999, "s": 5995, "text": "Dim" }, { "code": null, "e": 6006, "s": 5999, "text": "Public" }, { "code": null, "e": 6013, "s": 6006, "text": "Public" }, { "code": null, "e": 6021, "s": 6013, "text": "Private" }, { "code": null, "e": 6029, "s": 6021, "text": "Private" }, { "code": null, "e": 6250, "s": 6029, "text": "Variables declared using \"Dim\" keyword at a Procedure level are available only within the same procedure. Variables declared using \"Dim\" Keyword at script level are available to all the procedures within the same script." }, { "code": null, "e": 6444, "s": 6250, "text": "Variables declared using \"Public\" Keyword are available to all the procedures across all the associated scripts. When declaring a variable of type \"public\", Dim keyword is replaced by \"Public\"." }, { "code": null, "e": 6631, "s": 6444, "text": "Variables that are declared as \"Private\" have scope only within that script in which they are declared. When declaring a variable of type \"Private\", Dim keyword is replaced by \"Private\"." }, { "code": null, "e": 6677, "s": 6631, "text": "Constants are declared using \"const\" keyword." }, { "code": null, "e": 6748, "s": 6677, "text": "The Public constants are available for all the scripts and procedures." }, { "code": null, "e": 6811, "s": 6748, "text": "Private Constants are available within the procedure or Class." }, { "code": null, "e": 6870, "s": 6811, "text": " VBScript language supports following types of operators βˆ’" }, { "code": null, "e": 6891, "s": 6870, "text": "Arithmetic Operators" }, { "code": null, "e": 6912, "s": 6891, "text": "Arithmetic Operators" }, { "code": null, "e": 6933, "s": 6912, "text": "Comparison Operators" }, { "code": null, "e": 6954, "s": 6933, "text": "Comparison Operators" }, { "code": null, "e": 6988, "s": 6954, "text": "Logical (or Relational) Operators" }, { "code": null, "e": 7022, "s": 6988, "text": "Logical (or Relational) Operators" }, { "code": null, "e": 7046, "s": 7022, "text": "Concatenation Operators" }, { "code": null, "e": 7070, "s": 7046, "text": "Concatenation Operators" }, { "code": null, "e": 7125, "s": 7070, "text": "MOD opeator is used to get the modulus of two numbers." }, { "code": null, "e": 7135, "s": 7125, "text": "Example βˆ’" }, { "code": null, "e": 7223, "s": 7135, "text": "Dim a : a = 5\nDim b : b = 10\nDim c\nc = b MOD a\nDocument.write (\"Modulus Result is \" &c)" }, { "code": null, "e": 7277, "s": 7223, "text": "^ opeator is used to get the exponent of two numbers." }, { "code": null, "e": 7287, "s": 7277, "text": "Example βˆ’" }, { "code": null, "e": 7380, "s": 7287, "text": "Dim a : a = 5\nDim b : b = 10\nDim c\nc = b ^ a\nDocument.write (\"Exponentiation Result is \" &c)" }, { "code": null, "e": 7442, "s": 7380, "text": "<> operator is used to check if two numbers are equal or not." }, { "code": null, "e": 7452, "s": 7442, "text": "Example βˆ’" }, { "code": null, "e": 7539, "s": 7452, "text": "Dim a : a = 5\nDim b : b = 10\nDim c\nc = b <> a\nDocument.write (\"Equality Check is \" &c)" }, { "code": null, "e": 7613, "s": 7539, "text": "XOR Called Logical Exclusion operator. It is used to do an XOR operation." }, { "code": null, "e": 7623, "s": 7613, "text": "Example βˆ’" }, { "code": null, "e": 7709, "s": 7623, "text": "A. Dim a : a = 5\nDim b : b = 10\nDim c\nc = b XOR a\nDocument.write (\"XOR Check is \" &c)" }, { "code": null, "e": 7791, "s": 7709, "text": "+ operator adds two Values as Variable Values are Numeric. So A + B will give 15." }, { "code": null, "e": 7877, "s": 7791, "text": "+ operator concatenates two Values if values are string. So A + B will give VBScript." }, { "code": null, "e": 7937, "s": 7877, "text": "& operator concatenates two values. So A + B will give 510." }, { "code": null, "e": 8002, "s": 7937, "text": "& operator concatenates two values. So A & B will give VBScript." }, { "code": null, "e": 8195, "s": 8002, "text": "VBScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page." }, { "code": null, "e": 8314, "s": 8195, "text": "The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this βˆ’" }, { "code": null, "e": 8323, "s": 8314, "text": "Syntax βˆ’" }, { "code": null, "e": 8389, "s": 8323, "text": "document.cookie = \"key1 = value1; key2 = value2; expires = date\";" }, { "code": null, "e": 8585, "s": 8389, "text": "Here expires attribute is optional. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and after that cookies' value will not be accessible." }, { "code": null, "e": 8766, "s": 8585, "text": "Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie." }, { "code": null, "e": 8921, "s": 8766, "text": "The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value." }, { "code": null, "e": 9000, "s": 8921, "text": "You can use strings' split() function to break the string into key and values." }, { "code": null, "e": 9182, "s": 9000, "text": "Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past." }, { "code": null, "e": 9267, "s": 9182, "text": "Using CDbl function, which converts a given number of any variant subtype to double." }, { "code": null, "e": 9277, "s": 9267, "text": "Example βˆ’" }, { "code": null, "e": 9374, "s": 9277, "text": "x = 123\ny = 123.882\ndocument.write(\"x value after converting to double - \" & CDbl(x) & \"<br />\")" }, { "code": null, "e": 9460, "s": 9374, "text": "Using CInt function, which converts a given number of any variant subtype to Integer." }, { "code": null, "e": 9470, "s": 9460, "text": "Example βˆ’" }, { "code": null, "e": 9564, "s": 9470, "text": "x = 123\ny = 123.882\ndocument.write(\"y value after converting to Int - \" & CInt(y) & \"<br />\")" }, { "code": null, "e": 9647, "s": 9564, "text": "Using CLng function, which converts a given number of any variant subtype to Long." }, { "code": null, "e": 9657, "s": 9647, "text": "Example βˆ’" }, { "code": null, "e": 9751, "s": 9657, "text": "x = 123\ny = 123.882\ndocument.write(\"x value after converting to Long -\" & CLng(x) & \"<br />\")" }, { "code": null, "e": 9836, "s": 9751, "text": "Using CSng function, which converts a given number of any variant subtype to Single." }, { "code": null, "e": 9846, "s": 9836, "text": "Example βˆ’" }, { "code": null, "e": 9942, "s": 9846, "text": "x = 123\ny = 123.882\ndocument.write(\"x value after converting to Single -\" & CSng(x) & \"<br />\")" }, { "code": null, "e": 10031, "s": 9942, "text": "Using Hex function, which converts a given number of any variant subtype to Hexadecimal." }, { "code": null, "e": 10041, "s": 10031, "text": "Example βˆ’" }, { "code": null, "e": 10134, "s": 10041, "text": "x = 123\ny = 123.882\ndocument.write(\"y value after converting to Hex -\" & Hex(y) & \"<br />\") " }, { "code": null, "e": 10219, "s": 10134, "text": "Using FormatNumber function, which would return an expression formatted as a number." }, { "code": null, "e": 10229, "s": 10219, "text": "Example βˆ’" }, { "code": null, "e": 10317, "s": 10229, "text": "Dim num : num = -645.998651\ndocument.write(FormatNumber(num, 3))& \"<br/>\" '-645.999" }, { "code": null, "e": 10404, "s": 10317, "text": "Using FormatPercent function, which would return an expression formatted as a percent." }, { "code": null, "e": 10414, "s": 10404, "text": "Example βˆ’" }, { "code": null, "e": 10505, "s": 10414, "text": "Dim num : num = -645.998651\ndocument.write(FormatPercent(num, 2))& \"<br/>\" '-64,599.86%" }, { "code": null, "e": 10577, "s": 10505, "text": "Using Int function, which returns the integer part of the given number." }, { "code": null, "e": 10587, "s": 10577, "text": "Example βˆ’" }, { "code": null, "e": 10684, "s": 10587, "text": "Dim num : num = -645.998651\ndocument.write(\"int Result of num is : \" & int(num))& \"<br/>\" '-646" }, { "code": null, "e": 10761, "s": 10684, "text": "Using Log function, which returns the natural logarithm of the given number." }, { "code": null, "e": 10771, "s": 10761, "text": "Example βˆ’" }, { "code": null, "e": 10873, "s": 10771, "text": "Dim num : num = 210\ndocument.write(\"Log Result of num2 is : \" & Log(num2))& \"<br/>\" '5.34710753071747" }, { "code": null, "e": 10944, "s": 10873, "text": "Using Oct function, which returns the octal value of the given number." }, { "code": null, "e": 10954, "s": 10944, "text": "Example βˆ’" }, { "code": null, "e": 11057, "s": 10954, "text": "Dim num : num = -645.998651\ndocument.write(\"Oct Result of num is : \" & Oct(num))& \"<br/>\" '37777776572" }, { "code": null, "e": 11134, "s": 11057, "text": "Using Hex function, which returns the hexadecimal value of the given number." }, { "code": null, "e": 11144, "s": 11134, "text": "Example βˆ’" }, { "code": null, "e": 11244, "s": 11144, "text": "Dim num : num = -645.998651\ndocument.write(\"Hex Result of num is : \" & Hex(num))& \"<br/>\" 'FFFFFD7A" }, { "code": null, "e": 11310, "s": 11244, "text": "Using Rnd function,which returns a random number between 0 and 1." }, { "code": null, "e": 11320, "s": 11310, "text": "Example βˆ’" }, { "code": null, "e": 11421, "s": 11320, "text": "Dim num : num = -645.998651\ndocument.write(\"Rnd Result of num is : \" & Rnd(num))& \"<br/>\" '0.5130115" }, { "code": null, "e": 11492, "s": 11421, "text": "Using Sqr function, which returns the square root of the given number." }, { "code": null, "e": 11502, "s": 11492, "text": "Example βˆ’" }, { "code": null, "e": 11603, "s": 11502, "text": "Dim num : num = -210\ndocument.write(\"Sqr Result of num is : \" & Sqr(num))& \"<br/>\" '14.4913767461894" }, { "code": null, "e": 11677, "s": 11603, "text": "Using Abs function, which returns the absolute value of the given number." }, { "code": null, "e": 11687, "s": 11677, "text": "Example βˆ’" }, { "code": null, "e": 11789, "s": 11687, "text": "Dim num : num = -645.998651\ndocument.write(\"Abs Result of num is : \" & Abs(num))& \"<br/>\" '645.998651" }, { "code": null, "e": 11870, "s": 11789, "text": "Using Exp function, which returns the value of e raised to the specified number." }, { "code": null, "e": 11880, "s": 11870, "text": "Example βˆ’" }, { "code": null, "e": 11993, "s": 11880, "text": "Dim num : num = -645.998651\ndocument.write(\"Exp Result of num is : \" & Exp(num))& \"<br/>\" '2.79479883633128E-281" }, { "code": null, "e": 12126, "s": 11993, "text": "Using InStr function, which returns the first occurrence of one string within another string. The search happens from left to right." }, { "code": null, "e": 12262, "s": 12126, "text": "Using InStrRev function, which returns the first occurrence of one string within another string. The search happens from right to left." }, { "code": null, "e": 12338, "s": 12262, "text": "Using Lcase function, which returns the lower case of the specified string." }, { "code": null, "e": 12414, "s": 12338, "text": "Using Ucase function, which returns the upper case of the specified string." }, { "code": null, "e": 12527, "s": 12414, "text": "Using Ltrim function, which returns a string after removing the spaces on the left side of the specified string." }, { "code": null, "e": 12640, "s": 12527, "text": "Using Rtrim function, which returns a string after removing the spaces on the left side of the specified string." }, { "code": null, "e": 12745, "s": 12640, "text": "Using Trim function, which returns a string value after removing both leading and trailing blank spaces." }, { "code": null, "e": 12811, "s": 12745, "text": "Using Len function, which returns the length of the given string." }, { "code": null, "e": 12904, "s": 12811, "text": "Using Replace function, which returns a string after replacing a string with another string." }, { "code": null, "e": 12984, "s": 12904, "text": "Using Space function, which fills a string with the specified number of spaces." }, { "code": null, "e": 13082, "s": 12984, "text": "Using StrComp function, which returns an integer value after comparing the two specified strings." }, { "code": null, "e": 13259, "s": 13082, "text": "The StrComp Function returns an integer value after comparing the two given strings. It can return any of the three values -1, 0 or 1 based on the input strings to be compared." }, { "code": null, "e": 13306, "s": 13259, "text": "If String 1 < String 2 then StrComp returns -1" }, { "code": null, "e": 13353, "s": 13306, "text": "If String 1 < String 2 then StrComp returns -1" }, { "code": null, "e": 13399, "s": 13353, "text": "If String 1 = String 2 then StrComp returns 0" }, { "code": null, "e": 13445, "s": 13399, "text": "If String 1 = String 2 then StrComp returns 0" }, { "code": null, "e": 13491, "s": 13445, "text": "If String 1 > String 2 then StrComp returns 1" }, { "code": null, "e": 13537, "s": 13491, "text": "If String 1 > String 2 then StrComp returns 1" }, { "code": null, "e": 13641, "s": 13537, "text": "Using String function, which returns a String with a specified character the specified number of times." }, { "code": null, "e": 13758, "s": 13641, "text": "Using StrReverse function, whihc returns a String after reversing the sequece of the characters of the given string." }, { "code": null, "e": 13960, "s": 13758, "text": "rrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the below example, the size of the array is mentioned in the brackets." }, { "code": null, "e": 13970, "s": 13960, "text": "Example βˆ’" }, { "code": null, "e": 14172, "s": 13970, "text": "'Method 1 : Using Dim\nDim arr1() 'Without Size\n'Method 2 : Mentioning the Size\nDim arr2(5) 'Declared with size of 5\n'Method 3 : using 'Array' Parameter\nDim arr3\narr3 = Array(\"apple\",\"Orange\",\"Grapes\")" }, { "code": null, "e": 14288, "s": 14172, "text": "The values are assigned to the array by specifying array index value against each one of the values to be assigned." }, { "code": null, "e": 14298, "s": 14288, "text": "Example βˆ’" }, { "code": null, "e": 14411, "s": 14298, "text": "Dim arr(5)\narr(0) = \"VBScript\" 'String\ndocument.write(\"Value stored in Array index 0 : \" & arr(0) & \"<br />\")" }, { "code": null, "e": 14515, "s": 14411, "text": "Using ReDim statement, we can declare dynamic-array variables and allocate or reallocate storage space." }, { "code": null, "e": 14627, "s": 14515, "text": "Using LBound function, which returns an integer that corresponds to the smallest subscript of the given arrays." }, { "code": null, "e": 14738, "s": 14627, "text": "Using UBound function, which returns an integer that corresponds to the largest subscript of the given arrays." }, { "code": null, "e": 14858, "s": 14738, "text": "Using Split function, which returns an array that contains a specified number of values. Splitted based on a Delimiter." }, { "code": null, "e": 15014, "s": 14858, "text": "Using Join function, which returns a String that contains a specified number of substrings in an array. This is an exact opposite function of Split Method." }, { "code": null, "e": 15142, "s": 15014, "text": "Using Filter function, returns a zero based array that contains a subset of a string array based on a specific filter criteria." }, { "code": null, "e": 15258, "s": 15142, "text": "Using IsArray function, which returns a boolean value that indicates whether or not the input variable is an array." }, { "code": null, "e": 15341, "s": 15258, "text": "Using Erase Function, which recovers the allocated memory for the array variables." }, { "code": null, "e": 15598, "s": 15341, "text": "The most common way to define a function in VBScript is by using the Function keyword, followed by a unique function name and it may or may not carry a list of parameters and a statement with a End Function keyword, which indicates the end of the function." }, { "code": null, "e": 15730, "s": 15598, "text": "To invoke a function somewhere later in the script, you would simple need to write the name of that function with the Call keyword." }, { "code": null, "e": 15818, "s": 15730, "text": "To return a value from a function, simply assign the value to the function name itself." }, { "code": null, "e": 15930, "s": 15818, "text": "Yes! A function can return multiple values separated by comma as an array assigned to the function name itself." }, { "code": null, "e": 16001, "s": 15930, "text": "Sub Procedures are similar to functions but there are few differences." }, { "code": null, "e": 16084, "s": 16001, "text": "Sub procedures DONOT Return a value while functions may or may not return a value." }, { "code": null, "e": 16167, "s": 16084, "text": "Sub procedures DONOT Return a value while functions may or may not return a value." }, { "code": null, "e": 16218, "s": 16167, "text": "Sub procedures Can be called without call keyword." }, { "code": null, "e": 16269, "s": 16218, "text": "Sub procedures Can be called without call keyword." }, { "code": null, "e": 16339, "s": 16269, "text": "Sub procedures are always enclosed within Sub and End Sub statements." }, { "code": null, "e": 16409, "s": 16339, "text": "Sub procedures are always enclosed within Sub and End Sub statements." }, { "code": null, "e": 16514, "s": 16409, "text": "If ByVal is specified, then the arguments are sent as by value when the function or procedure is called." }, { "code": null, "e": 16623, "s": 16514, "text": "If ByRef is specified, then the arguments are sent as by reference when the function or procedure is called." }, { "code": null, "e": 16691, "s": 16623, "text": "we need to declare the object and instantiate it using Set Keyword." }, { "code": null, "e": 16701, "s": 16691, "text": "Example βˆ’" }, { "code": null, "e": 16758, "s": 16701, "text": "Dim obj \nSet obj = CreateObject(\"Scripting.Dictionary\")" }, { "code": null, "e": 16871, "s": 16758, "text": "In order to destroy the objects, we need to use Set Keyword followed by the object name and point it to Nothing." }, { "code": null, "e": 16881, "s": 16871, "text": "Example βˆ’" }, { "code": null, "e": 16956, "s": 16881, "text": "Dim obj \nSet obj = CreateObject(\"Scripting.Dictionary\")\nSet obj = Nothing" }, { "code": null, "e": 17150, "s": 16956, "text": "Class is a construct that is used to define a unique type. Like Object Oriented Programming, VbScript 5.0 supports the creation of classes and it is very similar to writing COM objects with VB." }, { "code": null, "e": 17328, "s": 17150, "text": "Class is simply the template for an object and we instantiate an object to access the properties and methods of it. Classes can contain variables, properties, methods or events." }, { "code": null, "e": 17386, "s": 17328, "text": "VBScript classes are enclosed within Class .... End Class" }, { "code": null, "e": 17524, "s": 17386, "text": "'Defining the Class\nClass classname 'Declare the object name\n...\nEnd Class\n' Instantiation of the Class\nSet objectname = new classname" }, { "code": null, "e": 17757, "s": 17524, "text": "Classes can contain variables, which can be of private or public. Variables within classes should follow VBScript naming conventions. By default, the variables in class are Public. That is why they can be accessed outside the class." }, { "code": null, "e": 17767, "s": 17757, "text": "Example βˆ’" }, { "code": null, "e": 17825, "s": 17767, "text": "Dim var1 , var2.\nPrivate var1 , var2.\nPublic var1 , var2." }, { "code": null, "e": 18046, "s": 17825, "text": "Class properties, such as Property Let, which handles the process of data validation and assigning the new value to the private variable. Property set, which assigns the new property value to the private object variable." }, { "code": null, "e": 18201, "s": 18046, "text": "Read-only properties have only a Property Get procedure while write-only properties (which are rare) have only a Property Let or a Property Set procedure." }, { "code": null, "e": 18211, "s": 18201, "text": "Example βˆ’" }, { "code": null, "e": 18625, "s": 18211, "text": "Class Comp\n \n Private modStrType\n Private OS\n \n Public Property Let ComputerType(strType)\n modStrType = strType\n End Property\n \n Public Property Get ComputerType()\n ComputerType = modStrType\n End Property\n \n Public Property Set OperatingSystem(oObj)\n Set OS = oObj\n End Property\n \n Public Property Get OperatingSystem()\n Set OperatingSystem = OS\n End Property\n \nEnd Class" }, { "code": null, "e": 18754, "s": 18625, "text": "Methods allow the class to perform the operation that the developer wants. The Methods are nothing but Functions or Subroutines." }, { "code": null, "e": 18764, "s": 18754, "text": "Example βˆ’" }, { "code": null, "e": 18897, "s": 18764, "text": "Class Car\n \n Private Model\n Private Year\n \n Public Start()\n Fuel = 2.45\n Pressure = 4.15\n End Function\n \nEnd Class" }, { "code": null, "e": 19019, "s": 18897, "text": "There are two events that are automatically associated with every class by default. Class_Initialize and Class_Terminate." }, { "code": null, "e": 19207, "s": 19019, "text": "Class_Initialize is triggered whenever you instantiate an object based on the class. Class_Terminate event is fired when the object goes out of scope or when the object is set to Nothing." }, { "code": null, "e": 19217, "s": 19207, "text": "Example βˆ’" }, { "code": null, "e": 19300, "s": 19217, "text": "In the below example, we will make you understand how the events work in VBScript." }, { "code": null, "e": 19534, "s": 19300, "text": "'Instantation of the Object\nSet objectname = New classname \n \nPrivate Sub Class_Initialize( )\n Initalization code goes here\nEnd Sub\n'When Object is Set to Nothing\nPrivate Sub Class_Terminate( )\n Termination code goes here\nEnd Sub" }, { "code": null, "e": 19640, "s": 19534, "text": "This class provides file system objects which help the developers to work with drives, folders and files." }, { "code": null, "e": 19650, "s": 19640, "text": "Example βˆ’" }, { "code": null, "e": 19800, "s": 19650, "text": "Dim oFS, drive\nSet oFS = CreateObject(\"Scripting.FileSystemObject\")\nSet drive = oFS.GetDrive(oFS.GetDriveName(\"C:\\\"))\nDocument.write drive.VolumeName" }, { "code": null, "e": 19913, "s": 19800, "text": "Drive contains methods and properties that allow you to gather information about a drive attached to the system." }, { "code": null, "e": 20006, "s": 19913, "text": "File contains methods and properties that allow developers to create, delete or move a file." }, { "code": null, "e": 20068, "s": 20006, "text": "Files provides a list of all files contained within a folder." }, { "code": null, "e": 20164, "s": 20068, "text": "Folder provides methods and properties that allow developers to create, delete or move folders." }, { "code": null, "e": 20224, "s": 20164, "text": "Folders provides a list of all the folders within a Folder." }, { "code": null, "e": 20284, "s": 20224, "text": "TextStream enables developers to read and write text files." }, { "code": null, "e": 20431, "s": 20284, "text": "RegExp object helps the developers to match the pattern of strings and the properties and methods help us to work with Regular Expressions easily." }, { "code": null, "e": 20479, "s": 20431, "text": "Following are the properties of RegExp object βˆ’" }, { "code": null, "e": 20639, "s": 20479, "text": "Pattern βˆ’ The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object." }, { "code": null, "e": 20799, "s": 20639, "text": "Pattern βˆ’ The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object." }, { "code": null, "e": 21012, "s": 20799, "text": "IgnoreCase βˆ’ A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False." }, { "code": null, "e": 21225, "s": 21012, "text": "IgnoreCase βˆ’ A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False." }, { "code": null, "e": 21413, "s": 21225, "text": "Global βˆ’ A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False." }, { "code": null, "e": 21601, "s": 21413, "text": "Global βˆ’ A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False." }, { "code": null, "e": 21768, "s": 21601, "text": "The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned." }, { "code": null, "e": 21989, "s": 21768, "text": "The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned." }, { "code": null, "e": 22172, "s": 21989, "text": "The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn't modify the original string." }, { "code": null, "e": 22230, "s": 22172, "text": "If we want to capture the error, then Err Object is used." }, { "code": null, "e": 22263, "s": 22230, "text": "Use Err.Raise to throw an error." }, { "code": null, "e": 22273, "s": 22263, "text": "Example βˆ’" }, { "code": null, "e": 22314, "s": 22273, "text": "Err.Raise 6 ' Raise an overflow error." }, { "code": null, "e": 22393, "s": 22314, "text": "Err.Number gives the error number and Err.Description gives error description." }, { "code": null, "e": 22403, "s": 22393, "text": "Example βˆ’" }, { "code": null, "e": 22505, "s": 22403, "text": "Err.Raise 6 ' Raise an overflow error.\nMsgBox \"Error # \" & CStr(Err.Number) & \" \" & Err.Description" }, { "code": null, "e": 22531, "s": 22505, "text": "Err.Clear clear an error." }, { "code": null, "e": 22541, "s": 22531, "text": "Example βˆ’" }, { "code": null, "e": 22674, "s": 22541, "text": "Err.Raise 6 ' Raise an overflow error.\nMsgBox \"Error # \" & CStr(Err.Number) & \" \" & Err.Description\nErr.Clear ' Clear the error." }, { "code": null, "e": 22961, "s": 22674, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 23291, "s": 22961, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 23324, "s": 23291, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 23341, "s": 23324, "text": " Frahaan Hussain" }, { "code": null, "e": 23348, "s": 23341, "text": " Print" }, { "code": null, "e": 23359, "s": 23348, "text": " Add Notes" } ]
Convert ASCII TO UTF-8 Encoding in PHP?
If we know that the current encoding is ASCII, the 'iconv' function can be used to convert ASCII to UTF-8. The original string can be passed as a parameter to the iconv function to encode it to UTF-8. Live Demo <?php $str = "ábreΜ‚cWtë"; echo 'Original :', ("$str"), PHP_EOL; echo 'Plain :', iconv("UTF-8", "ISO-8859-1", $str), PHP_EOL; ?> A string with special characters is assigned to β€˜str’ variable. This is passed to the β€˜iconv’ function, with the encoding that it currently is in, and the encoding to which it needs to be converted to. This will produce the following output βˆ’ Original :ábreΜ‚cWtë Plain :οΏ½brοΏ½cWtοΏ½ Another method is to detect the encoding and then converting it to an appropriate encoding βˆ’ Live Demo $string = "ábreΜ‚cWtë"; print(mb_detect_encoding ($string)); $string = mb_convert_encoding($string, "UTF-8"); print(mb_detect_encoding ($string)); A string value with special characters is assigned to β€˜string; variable. This is passed to the β€˜mb_convert_encoding’ function that converts it to the target encoding. This will produce the following output βˆ’ UTF-8UTF-8
[ { "code": null, "e": 1263, "s": 1062, "text": "If we know that the current encoding is ASCII, the 'iconv' function can be used to convert ASCII to UTF-8. The original string can be passed as a parameter to the iconv function to encode it to UTF-8." }, { "code": null, "e": 1274, "s": 1263, "text": " Live Demo" }, { "code": null, "e": 1413, "s": 1274, "text": "<?php\n $str = \"ábreΜ‚cWtë\";\n echo 'Original :', (\"$str\"), PHP_EOL;\n echo 'Plain :', iconv(\"UTF-8\", \"ISO-8859-1\", $str), PHP_EOL;\n?>" }, { "code": null, "e": 1615, "s": 1413, "text": "A string with special characters is assigned to β€˜str’ variable. This is passed to the β€˜iconv’ function, with the encoding that it currently is in, and the encoding to which it needs to be converted to." }, { "code": null, "e": 1656, "s": 1615, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 1694, "s": 1656, "text": "Original :ábreΜ‚cWtë Plain :οΏ½brοΏ½cWtοΏ½" }, { "code": null, "e": 1787, "s": 1694, "text": "Another method is to detect the encoding and then converting it to an appropriate encoding βˆ’" }, { "code": null, "e": 1798, "s": 1787, "text": " Live Demo" }, { "code": null, "e": 1946, "s": 1798, "text": "$string = \"ábreΜ‚cWtë\";\nprint(mb_detect_encoding ($string));\n$string = mb_convert_encoding($string, \"UTF-8\");\nprint(mb_detect_encoding ($string));" }, { "code": null, "e": 2113, "s": 1946, "text": "A string value with special characters is assigned to β€˜string; variable. This is passed to the β€˜mb_convert_encoding’ function that converts it to the target encoding." }, { "code": null, "e": 2154, "s": 2113, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2165, "s": 2154, "text": "UTF-8UTF-8" } ]
Uniscan – Web Application Penetration Testing Tool - GeeksforGeeks
14 Sep, 2021 With the rapid growth in the development of Web-based applications, there is also growth in vulnerabilities for which hackers are awaiting from all sides. Finding those vulnerabilities can be difficult if we use a manual approach, but with the help of automated plenty of tools makes the process easier. Vulnerability Scanners are game-changing tools that detect a vulnerability on the target domain. Uniscan tool is an automated tool developed in the Perl Language used for Fingerprinting and Vulnerability Testing. Uniscan tool is available on GitHub. Uniscan tool is an open-source and free-to-use tool. Its GUI Version is too powerful and easy to use as all the results are shown in the GUI Window itself. There are numerous types of Web Scanners that have their own unique methodology and features. However, choosing the right scanner matter for saving yourself from false-positive results. Let’s explore some Web Scanners and how can they be compared with Uniscan Scanner. Metasploit framework is well known for its modules. WMAP is an inbuilt scanner provided by the Metasploit framework. This Scanner performs a similar task to the Uniscan scanner of enumerating directories, files, robots.txt, etc. But this scanner is useful only while using the Metasploit framework as Uniscan can be used from anywhere in the system. Vega is one of the popular Web Scanner similar to Burp Suite. It’s more popular due to its proxy feature and its free and open-source. Like Uniscan scanner Vega scanner can also detect vulnerabilities in addition to other injection vulnerabilities. But this tool is only feasible on GUI Mode, Command-Line mode behaves uniformly sometimes. While all of these scanners are great tools for testing web apps for common flaws, Uniscan is the one to come back to when you need a quick-and-dirty web scanner that’s noob-friendly. The GUI Interface if Uniscan tool can be activated through the uniscan-gui command on the terminal. The interface is quite friendly with the new hackers. All the options can be used with a single click. Firstly, we need to specify the target domain URL for which the process will be done. Then we need to select the options which will be performed on the domain like directory check, file check, robots.txt file check, web fingerprinting, server fingerprinting, dynamic test option, static test option, and stress test. All the activities are saved in the log files which can be used as the result file for our scans on the target domain. Note: Make Sure You have Perl Installed on your System, as this is a Perl-based tool. Click to check the Installation process – Perl Installation Steps on Linux Step 1: Update the System by using the following command. sudo apt-get update Step 2: Now use the following command to install the Uniscan tool from the apt manager. sudo apt-get install uniscan Step 3: Now our tool is successfully installed. Check the help page by using the following command. sudo uniscan -h Example 1: Check Directory In this example, We are performing Directory Brute-Forcing on http://testphp.vulnweb.com Example 2: Check Files In this example, We are performing Files Brute-Forcing on http://testphp.vulnweb.com Example 3: Check /robots.txt In this Example, We are checking robots.txt file of http://testphp.vulnweb.com target domain. Example 4: Server Fingerprint In this Example, We are performing Server Fingerprinting on http://testphp.vulnweb.com. Example 5: Dynamic Tests In this Example, We are performing Dynamic Tests on http://testphp.vulnweb.com. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ Array Basics in Shell Scripting | Set 1 scp command in Linux with Examples nohup Command in Linux with Examples chown command in Linux with Examples mv command in Linux with examples Named Pipe or FIFO with example C program SED command in Linux | Set 2 Basic Operators in Shell Scripting Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 24326, "s": 24298, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24631, "s": 24326, "text": "With the rapid growth in the development of Web-based applications, there is also growth in vulnerabilities for which hackers are awaiting from all sides. Finding those vulnerabilities can be difficult if we use a manual approach, but with the help of automated plenty of tools makes the process easier. " }, { "code": null, "e": 25037, "s": 24631, "text": "Vulnerability Scanners are game-changing tools that detect a vulnerability on the target domain. Uniscan tool is an automated tool developed in the Perl Language used for Fingerprinting and Vulnerability Testing. Uniscan tool is available on GitHub. Uniscan tool is an open-source and free-to-use tool. Its GUI Version is too powerful and easy to use as all the results are shown in the GUI Window itself." }, { "code": null, "e": 25306, "s": 25037, "text": "There are numerous types of Web Scanners that have their own unique methodology and features. However, choosing the right scanner matter for saving yourself from false-positive results. Let’s explore some Web Scanners and how can they be compared with Uniscan Scanner." }, { "code": null, "e": 25656, "s": 25306, "text": "Metasploit framework is well known for its modules. WMAP is an inbuilt scanner provided by the Metasploit framework. This Scanner performs a similar task to the Uniscan scanner of enumerating directories, files, robots.txt, etc. But this scanner is useful only while using the Metasploit framework as Uniscan can be used from anywhere in the system." }, { "code": null, "e": 25996, "s": 25656, "text": "Vega is one of the popular Web Scanner similar to Burp Suite. It’s more popular due to its proxy feature and its free and open-source. Like Uniscan scanner Vega scanner can also detect vulnerabilities in addition to other injection vulnerabilities. But this tool is only feasible on GUI Mode, Command-Line mode behaves uniformly sometimes." }, { "code": null, "e": 26180, "s": 25996, "text": "While all of these scanners are great tools for testing web apps for common flaws, Uniscan is the one to come back to when you need a quick-and-dirty web scanner that’s noob-friendly." }, { "code": null, "e": 26819, "s": 26180, "text": "The GUI Interface if Uniscan tool can be activated through the uniscan-gui command on the terminal. The interface is quite friendly with the new hackers. All the options can be used with a single click. Firstly, we need to specify the target domain URL for which the process will be done. Then we need to select the options which will be performed on the domain like directory check, file check, robots.txt file check, web fingerprinting, server fingerprinting, dynamic test option, static test option, and stress test. All the activities are saved in the log files which can be used as the result file for our scans on the target domain." }, { "code": null, "e": 26980, "s": 26819, "text": "Note: Make Sure You have Perl Installed on your System, as this is a Perl-based tool. Click to check the Installation process – Perl Installation Steps on Linux" }, { "code": null, "e": 27038, "s": 26980, "text": "Step 1: Update the System by using the following command." }, { "code": null, "e": 27058, "s": 27038, "text": "sudo apt-get update" }, { "code": null, "e": 27146, "s": 27058, "text": "Step 2: Now use the following command to install the Uniscan tool from the apt manager." }, { "code": null, "e": 27175, "s": 27146, "text": "sudo apt-get install uniscan" }, { "code": null, "e": 27275, "s": 27175, "text": "Step 3: Now our tool is successfully installed. Check the help page by using the following command." }, { "code": null, "e": 27291, "s": 27275, "text": "sudo uniscan -h" }, { "code": null, "e": 27318, "s": 27291, "text": "Example 1: Check Directory" }, { "code": null, "e": 27407, "s": 27318, "text": "In this example, We are performing Directory Brute-Forcing on http://testphp.vulnweb.com" }, { "code": null, "e": 27430, "s": 27407, "text": "Example 2: Check Files" }, { "code": null, "e": 27515, "s": 27430, "text": "In this example, We are performing Files Brute-Forcing on http://testphp.vulnweb.com" }, { "code": null, "e": 27544, "s": 27515, "text": "Example 3: Check /robots.txt" }, { "code": null, "e": 27638, "s": 27544, "text": "In this Example, We are checking robots.txt file of http://testphp.vulnweb.com target domain." }, { "code": null, "e": 27668, "s": 27638, "text": "Example 4: Server Fingerprint" }, { "code": null, "e": 27756, "s": 27668, "text": "In this Example, We are performing Server Fingerprinting on http://testphp.vulnweb.com." }, { "code": null, "e": 27781, "s": 27756, "text": "Example 5: Dynamic Tests" }, { "code": null, "e": 27861, "s": 27781, "text": "In this Example, We are performing Dynamic Tests on http://testphp.vulnweb.com." }, { "code": null, "e": 27872, "s": 27861, "text": "Kali-Linux" }, { "code": null, "e": 27884, "s": 27872, "text": "Linux-Tools" }, { "code": null, "e": 27895, "s": 27884, "text": "Linux-Unix" }, { "code": null, "e": 27993, "s": 27895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28002, "s": 27993, "text": "Comments" }, { "code": null, "e": 28015, "s": 28002, "text": "Old Comments" }, { "code": null, "e": 28041, "s": 28015, "text": "Thread functions in C/C++" }, { "code": null, "e": 28081, "s": 28041, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 28116, "s": 28081, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28153, "s": 28116, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28190, "s": 28153, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28224, "s": 28190, "text": "mv command in Linux with examples" }, { "code": null, "e": 28266, "s": 28224, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 28295, "s": 28266, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28330, "s": 28295, "text": "Basic Operators in Shell Scripting" } ]
What does β€œunsigned” in MySQL mean and when to use it?
The β€œunsigned” in MySQL is a data type. Whenever we write an unsigned to any column that means you cannot insert negative numbers. Suppose, for a very large number you can use unsigned type. The maximum range with unsigned int is 4294967295. Note: If you insert negative value you will get a MySQL error. Here is the example demo of unsigned type. Let us first create a table with β€œunsigned” column. The following is the query to create a table βˆ’ mysql> create table UnsignedDemoWithPositiveValue -> ( -> Distance int unsigned -> ); Query OK, 0 rows affected (0.86 sec) If you will try to insert the upper value with unsigned 4294967295, then an error will generate since the value is out of range. Inserting out of range value. mysql> insert into UnsignedDemoWithPositiveValue values(4294967296); ERROR 1264 (22003): Out of range value for column 'Distance' at row 1 In the above example, I have inserted 4294967296, which is out of range, therefore error generates. Now I am inserting another value 4294967295 into the table. mysql> insert into UnsignedDemoWithPositiveValue values(4294967295); Query OK, 1 row affected (0.30 sec) Above, you can see that the query executed successfully. Now, let us see another example. If you insert negative records, then the following error can be seen βˆ’ mysql> insert into UnsignedDemoWithPositiveValue values(-124); ERROR 1264 (22003): Out of range value for column 'Distance' at row 1 I will now insert only positive value with value 124. The query is as follows βˆ’ mysql> insert into UnsignedDemoWithPositiveValue values(124); Query OK, 1 row affected (0.86 sec) As you can see above, the query executed successfully. Let us display the record with the help of select statement. The query is as follows βˆ’ mysql> select *from UnsignedDemoWithPositiveValue; Here is the output βˆ’ +------------+ | Distance | +------------+ | 4294967295 | | 124 | +------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1253, "s": 1062, "text": "The β€œunsigned” in MySQL is a data type. Whenever we write an unsigned to any column that means you cannot insert negative numbers. Suppose, for a very large number you can use unsigned type." }, { "code": null, "e": 1304, "s": 1253, "text": "The maximum range with unsigned int is 4294967295." }, { "code": null, "e": 1367, "s": 1304, "text": "Note: If you insert negative value you will get a MySQL error." }, { "code": null, "e": 1509, "s": 1367, "text": "Here is the example demo of unsigned type. Let us first create a table with β€œunsigned” column. The following is the query to create a table βˆ’" }, { "code": null, "e": 1641, "s": 1509, "text": "mysql> create table UnsignedDemoWithPositiveValue\n -> (\n -> Distance int unsigned\n -> );\nQuery OK, 0 rows affected (0.86 sec)" }, { "code": null, "e": 1770, "s": 1641, "text": "If you will try to insert the upper value with unsigned 4294967295, then an error will generate since the value is out of range." }, { "code": null, "e": 1800, "s": 1770, "text": "Inserting out of range value." }, { "code": null, "e": 1939, "s": 1800, "text": "mysql> insert into UnsignedDemoWithPositiveValue values(4294967296);\nERROR 1264 (22003): Out of range value for column 'Distance' at row 1" }, { "code": null, "e": 2039, "s": 1939, "text": "In the above example, I have inserted 4294967296, which is out of range, therefore error generates." }, { "code": null, "e": 2099, "s": 2039, "text": "Now I am inserting another value 4294967295 into the table." }, { "code": null, "e": 2204, "s": 2099, "text": "mysql> insert into UnsignedDemoWithPositiveValue values(4294967295);\nQuery OK, 1 row affected (0.30 sec)" }, { "code": null, "e": 2261, "s": 2204, "text": "Above, you can see that the query executed successfully." }, { "code": null, "e": 2365, "s": 2261, "text": "Now, let us see another example. If you insert negative records, then the following error can be seen βˆ’" }, { "code": null, "e": 2498, "s": 2365, "text": "mysql> insert into UnsignedDemoWithPositiveValue values(-124);\nERROR 1264 (22003): Out of range value for column 'Distance' at row 1" }, { "code": null, "e": 2578, "s": 2498, "text": "I will now insert only positive value with value 124. The query is as follows βˆ’" }, { "code": null, "e": 2676, "s": 2578, "text": "mysql> insert into UnsignedDemoWithPositiveValue values(124);\nQuery OK, 1 row affected (0.86 sec)" }, { "code": null, "e": 2731, "s": 2676, "text": "As you can see above, the query executed successfully." }, { "code": null, "e": 2818, "s": 2731, "text": "Let us display the record with the help of select statement. The query is as follows βˆ’" }, { "code": null, "e": 2869, "s": 2818, "text": "mysql> select *from UnsignedDemoWithPositiveValue;" }, { "code": null, "e": 2890, "s": 2869, "text": "Here is the output βˆ’" }, { "code": null, "e": 3005, "s": 2890, "text": "+------------+\n| Distance |\n+------------+\n| 4294967295 |\n| 124 |\n+------------+\n2 rows in set (0.00 sec)" } ]
Lodash _.round() Method - GeeksforGeeks
09 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.round() method is used to compute number rounded to precision. Syntax: _.round(number, [precision = 0]) Parameters: This method accepts two parameters as mentioned above and described below: number: This parameter holds the number to round. [precision = 0]: This parameter holds the precision to round to. Return Value: This method returns the rounded number. Example 1: Here, const _ = require(β€˜lodash’) is used to import the lodash library into the file. Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.round() // method let gfg = _.round(7.56); // Printing the output console.log(gfg); Output: 8 Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.round() // method let gfg = _.round(9.005, 2); // Printing the output console.log(gfg); Output: 9.01 Example 3: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.round() // method let gfg = _.round(1980, -2); // Printing the output console.log(gfg); Output: 2000 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript How to Open URL in New Tab using JavaScript ? How to read a local text file using JavaScript? Hide or show elements in HTML using display property Express.js express.Router() Function Installation of Node.js on Linux How to set input type date in dd-mm-yyyy format using HTML ? Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 37045, "s": 37017, "text": "\n09 Sep, 2020" }, { "code": null, "e": 37185, "s": 37045, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": null, "e": 37254, "s": 37185, "text": "The _.round() method is used to compute number rounded to precision." }, { "code": null, "e": 37262, "s": 37254, "text": "Syntax:" }, { "code": null, "e": 37295, "s": 37262, "text": "_.round(number, [precision = 0])" }, { "code": null, "e": 37382, "s": 37295, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 37432, "s": 37382, "text": "number: This parameter holds the number to round." }, { "code": null, "e": 37497, "s": 37432, "text": "[precision = 0]: This parameter holds the precision to round to." }, { "code": null, "e": 37551, "s": 37497, "text": "Return Value: This method returns the rounded number." }, { "code": null, "e": 37648, "s": 37551, "text": "Example 1: Here, const _ = require(β€˜lodash’) is used to import the lodash library into the file." }, { "code": null, "e": 37659, "s": 37648, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.round() // method let gfg = _.round(7.56); // Printing the output console.log(gfg);", "e": 37832, "s": 37659, "text": null }, { "code": null, "e": 37840, "s": 37832, "text": "Output:" }, { "code": null, "e": 37842, "s": 37840, "text": "8" }, { "code": null, "e": 37855, "s": 37842, "text": "Example 2: " }, { "code": null, "e": 37866, "s": 37855, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.round() // method let gfg = _.round(9.005, 2); // Printing the output console.log(gfg);", "e": 38043, "s": 37866, "text": null }, { "code": null, "e": 38051, "s": 38043, "text": "Output:" }, { "code": null, "e": 38056, "s": 38051, "text": "9.01" }, { "code": null, "e": 38069, "s": 38056, "text": "Example 3: " }, { "code": null, "e": 38080, "s": 38069, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.round() // method let gfg = _.round(1980, -2); // Printing the output console.log(gfg);", "e": 38257, "s": 38080, "text": null }, { "code": null, "e": 38265, "s": 38257, "text": "Output:" }, { "code": null, "e": 38270, "s": 38265, "text": "2000" }, { "code": null, "e": 38288, "s": 38270, "text": "JavaScript-Lodash" }, { "code": null, "e": 38299, "s": 38288, "text": "JavaScript" }, { "code": null, "e": 38316, "s": 38299, "text": "Web Technologies" }, { "code": null, "e": 38414, "s": 38316, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38423, "s": 38414, "text": "Comments" }, { "code": null, "e": 38436, "s": 38423, "text": "Old Comments" }, { "code": null, "e": 38508, "s": 38436, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 38553, "s": 38508, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 38599, "s": 38553, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 38647, "s": 38599, "text": "How to read a local text file using JavaScript?" }, { "code": null, "e": 38700, "s": 38647, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 38737, "s": 38700, "text": "Express.js express.Router() Function" }, { "code": null, "e": 38770, "s": 38737, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 38831, "s": 38770, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 38903, "s": 38831, "text": "Differences between Functional Components and Class Components in React" } ]
Python program to find all Strong Numbers in given list
24 Jun, 2019 Given a list, write a Python program to find all the Strong numbers in a given list of numbers. A Strong Number is a number that is equal to the sum of factorial of its digits. Examples: Input : [1, 2, 5, 145, 654, 34] Output : [1, 2, 145] Input : [15, 58, 75, 675, 145, 2] Output : [145, 2] Explanation : We defined 2 functions here: First is factorial() and second is strong_number(). As soon as strong_number() is called, the list is passed to the function and stored in the formal argument list. For loop iterates for every element in list, temp is a temporary variable on which calculation is done, then factorial() function is called on the remainder of temp mod 10 and passed it to the factorial function. Now when temp equates to 0, it exits the while loop and checks whether sum is equal to x or not. If True then it is added in the list using append() function which is predefined for list and is used to add elements in the list and if there is no strong number then it will return an empty list. Below is the Python implementation: # Python program to find all # Strong Numbers in given listdef factorial(number): if(number == 0 or number == 1): fact = 1 else: fact = number * factorial(number - 1) return fact def strong_number(list): new_list =[] for x in list: temp = x sum = 0 while(temp): rem = temp % 10 sum += factorial(rem) temp = temp // 10 if(sum == x): new_list.append(x) else: pass return new_list # Driver Codeval_list = [1, 2, 5, 145, 654, 34]strong_num_list = strong_number(val_list)print(strong_num_list) [1, 2, 145] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2019" }, { "code": null, "e": 148, "s": 52, "text": "Given a list, write a Python program to find all the Strong numbers in a given list of numbers." }, { "code": null, "e": 229, "s": 148, "text": "A Strong Number is a number that is equal to the sum of factorial of its digits." }, { "code": null, "e": 239, "s": 229, "text": "Examples:" }, { "code": null, "e": 347, "s": 239, "text": "Input : [1, 2, 5, 145, 654, 34] \nOutput : [1, 2, 145]\n\nInput : [15, 58, 75, 675, 145, 2]\nOutput : [145, 2]\n" }, { "code": null, "e": 361, "s": 347, "text": "Explanation :" }, { "code": null, "e": 442, "s": 361, "text": "We defined 2 functions here: First is factorial() and second is strong_number()." }, { "code": null, "e": 555, "s": 442, "text": "As soon as strong_number() is called, the list is passed to the function and stored in the formal argument list." }, { "code": null, "e": 768, "s": 555, "text": "For loop iterates for every element in list, temp is a temporary variable on which calculation is done, then factorial() function is called on the remainder of temp mod 10 and passed it to the factorial function." }, { "code": null, "e": 1063, "s": 768, "text": "Now when temp equates to 0, it exits the while loop and checks whether sum is equal to x or not. If True then it is added in the list using append() function which is predefined for list and is used to add elements in the list and if there is no strong number then it will return an empty list." }, { "code": null, "e": 1099, "s": 1063, "text": "Below is the Python implementation:" }, { "code": "# Python program to find all # Strong Numbers in given listdef factorial(number): if(number == 0 or number == 1): fact = 1 else: fact = number * factorial(number - 1) return fact def strong_number(list): new_list =[] for x in list: temp = x sum = 0 while(temp): rem = temp % 10 sum += factorial(rem) temp = temp // 10 if(sum == x): new_list.append(x) else: pass return new_list # Driver Codeval_list = [1, 2, 5, 145, 654, 34]strong_num_list = strong_number(val_list)print(strong_num_list)", "e": 1738, "s": 1099, "text": null }, { "code": null, "e": 1751, "s": 1738, "text": "[1, 2, 145]\n" }, { "code": null, "e": 1772, "s": 1751, "text": "Python list-programs" }, { "code": null, "e": 1779, "s": 1772, "text": "Python" }, { "code": null, "e": 1795, "s": 1779, "text": "Python Programs" }, { "code": null, "e": 1893, "s": 1795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1911, "s": 1893, "text": "Python Dictionary" }, { "code": null, "e": 1953, "s": 1911, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1975, "s": 1953, "text": "Enumerate() in Python" }, { "code": null, "e": 2001, "s": 1975, "text": "Python String | replace()" }, { "code": null, "e": 2033, "s": 2001, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2076, "s": 2033, "text": "Python program to convert a list to string" }, { "code": null, "e": 2098, "s": 2076, "text": "Defaultdict in Python" }, { "code": null, "e": 2137, "s": 2098, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2175, "s": 2137, "text": "Python | Convert a list to dictionary" } ]
Volume of solid of revolution
20 Jun, 2020 A solid of revolution is generated by revolving a plane area R about a line L known as axis of revolution in the plane. Below image shows an example of solid of revolution. We shall calculate the volume of solid of revolution when the equation of the curve is given in parametric form and polar form. Parametric Form :If the equation of curve in parametric form is given by:x= f(t) and y= g(t) Where t varies from t1to t2, then the volume of revolution:About x-axis –About y-axis –Polar form:Given the equation of curve in polar form as r=f(ΞΈ), where ΞΈ varies from ΞΈ1 to ΞΈ2, the volume of revolution is calculated using the given formulas:About the initial line OX i.e., x-axis (ΞΈ=0) –About the line perpendicular to the initial line i.e. along OY (ΞΈ=Ο€/2) – Parametric Form :If the equation of curve in parametric form is given by:x= f(t) and y= g(t) Where t varies from t1to t2, then the volume of revolution:About x-axis –About y-axis – x= f(t) and y= g(t) Where t varies from t1to t2, then the volume of revolution: About x-axis – About y-axis – Polar form:Given the equation of curve in polar form as r=f(ΞΈ), where ΞΈ varies from ΞΈ1 to ΞΈ2, the volume of revolution is calculated using the given formulas:About the initial line OX i.e., x-axis (ΞΈ=0) –About the line perpendicular to the initial line i.e. along OY (ΞΈ=Ο€/2) – About the initial line OX i.e., x-axis (ΞΈ=0) – About the line perpendicular to the initial line i.e. along OY (ΞΈ=Ο€/2) – Let us see the following examples. Example-1:Determine the volume of solid of revolution generated by revolving the curve whose parametric equations are – X= 2t+3 and y= 4t2-9 About x-axis for t= -3/2 to 3/2. Explanation :We know that volume of solid revolved about x-axis when equation is in parametric form is given byUsing this value we get Example-2:Find the volume of solid generated by revolving curve r= 2a cos ΞΈ about the initial line OX. Explanation :We know that volume of solid generated by revolving about OX in when equation is in polar form is given byAlso for OX, ΞΈ=0So Put Using these values we get Engineering Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2020" }, { "code": null, "e": 225, "s": 52, "text": "A solid of revolution is generated by revolving a plane area R about a line L known as axis of revolution in the plane. Below image shows an example of solid of revolution." }, { "code": null, "e": 353, "s": 225, "text": "We shall calculate the volume of solid of revolution when the equation of the curve is given in parametric form and polar form." }, { "code": null, "e": 810, "s": 353, "text": "Parametric Form :If the equation of curve in parametric form is given by:x= f(t) and y= g(t) Where t varies from t1to t2, then the volume of revolution:About x-axis –About y-axis –Polar form:Given the equation of curve in polar form as r=f(ΞΈ), where ΞΈ varies from ΞΈ1 to ΞΈ2, the volume of revolution is calculated using the given formulas:About the initial line OX i.e., x-axis (ΞΈ=0) –About the line perpendicular to the initial line i.e. along OY (ΞΈ=Ο€/2) –" }, { "code": null, "e": 991, "s": 810, "text": "Parametric Form :If the equation of curve in parametric form is given by:x= f(t) and y= g(t) Where t varies from t1to t2, then the volume of revolution:About x-axis –About y-axis –" }, { "code": null, "e": 1012, "s": 991, "text": "x= f(t) and y= g(t) " }, { "code": null, "e": 1072, "s": 1012, "text": "Where t varies from t1to t2, then the volume of revolution:" }, { "code": null, "e": 1087, "s": 1072, "text": "About x-axis –" }, { "code": null, "e": 1102, "s": 1087, "text": "About y-axis –" }, { "code": null, "e": 1379, "s": 1102, "text": "Polar form:Given the equation of curve in polar form as r=f(ΞΈ), where ΞΈ varies from ΞΈ1 to ΞΈ2, the volume of revolution is calculated using the given formulas:About the initial line OX i.e., x-axis (ΞΈ=0) –About the line perpendicular to the initial line i.e. along OY (ΞΈ=Ο€/2) –" }, { "code": null, "e": 1426, "s": 1379, "text": "About the initial line OX i.e., x-axis (ΞΈ=0) –" }, { "code": null, "e": 1499, "s": 1426, "text": "About the line perpendicular to the initial line i.e. along OY (ΞΈ=Ο€/2) –" }, { "code": null, "e": 1534, "s": 1499, "text": "Let us see the following examples." }, { "code": null, "e": 1654, "s": 1534, "text": "Example-1:Determine the volume of solid of revolution generated by revolving the curve whose parametric equations are –" }, { "code": null, "e": 1676, "s": 1654, "text": "X= 2t+3 and y= 4t2-9 " }, { "code": null, "e": 1709, "s": 1676, "text": "About x-axis for t= -3/2 to 3/2." }, { "code": null, "e": 1844, "s": 1709, "text": "Explanation :We know that volume of solid revolved about x-axis when equation is in parametric form is given byUsing this value we get" }, { "code": null, "e": 1947, "s": 1844, "text": "Example-2:Find the volume of solid generated by revolving curve r= 2a cos ΞΈ about the initial line OX." }, { "code": null, "e": 2115, "s": 1947, "text": "Explanation :We know that volume of solid generated by revolving about OX in when equation is in polar form is given byAlso for OX, ΞΈ=0So Put Using these values we get" }, { "code": null, "e": 2139, "s": 2115, "text": "Engineering Mathematics" } ]
Spring Boot JPA - Native Query
Some time case arises, where we need a custom native query to fulfil one test case. We can use @Query annotation to specify a query within a repository. Following is an example. In this example, we are using native query, and set an attribute nativeQuery=true in Query annotation to mark the query as native. We've added custom methods in Repository in JPA Custom Query chapter. Now let's add another method using native query and test it. Add a method to get list of employees order by their names. package com.tutorialspoint.repository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.tutorialspoint.entity.Employee; @Repository public interface EmployeeRepository extends CrudRepository<Employee, Integer> { public List<Employee> findByName(String name); public List<Employee> findByAge(int age); public Employee findByEmail(String email); @Query(value = "SELECT e FROM Employee e ORDER BY name") public List<Employee> findAllSortedByName(); @Query(value = "SELECT * FROM Employee ORDER BY name", nativeQuery = true) public List<Employee> findAllSortedByNameUsingNative(); } Let's test the methods added by adding their test cases in test file. Last two methods of below file tests the custom query method added. Following is the complete code of EmployeeRepositoryTest. package com.tutorialspoint.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.tutorialspoint.entity.Employee; import com.tutorialspoint.sprintbooth2.SprintBootH2Application; @ExtendWith(SpringExtension.class) @Transactional @SpringBootTest(classes = SprintBootH2Application.class) public class EmployeeRepositoryTest { @Autowired private EmployeeRepository employeeRepository; @Test public void testFindById() { Employee employee = getEmployee(); employeeRepository.save(employee); Employee result = employeeRepository.findById(employee.getId()).get(); assertEquals(employee.getId(), result.getId()); } @Test public void testFindAll() { Employee employee = getEmployee(); employeeRepository.save(employee); List<Employee> result = new ArrayList<>(); employeeRepository.findAll().forEach(e -> result.add(e)); assertEquals(result.size(), 1); } @Test public void testSave() { Employee employee = getEmployee(); employeeRepository.save(employee); Employee found = employeeRepository.findById(employee.getId()).get(); assertEquals(employee.getId(), found.getId()); } @Test public void testDeleteById() { Employee employee = getEmployee(); employeeRepository.save(employee); employeeRepository.deleteById(employee.getId()); List<Employee> result = new ArrayList<>(); employeeRepository.findAll().forEach(e -> result.add(e)); assertEquals(result.size(), 0); } private Employee getEmployee() { Employee employee = new Employee(); employee.setId(1); employee.setName("Mahesh"); employee.setAge(30); employee.setEmail("mahesh@test.com"); return employee; } @Test public void testFindByName() { Employee employee = getEmployee(); employeeRepository.save(employee); List<Employee> result = new ArrayList<>(); employeeRepository.findByName(employee.getName()).forEach(e -> result.add(e)); assertEquals(result.size(), 1); } @Test public void testFindByAge() { Employee employee = getEmployee(); employeeRepository.save(employee); List<Employee> result = new ArrayList<>(); employeeRepository.findByAge(employee.getAge()).forEach(e -> result.add(e)); assertEquals(result.size(), 1); } @Test public void testFindByEmail() { Employee employee = getEmployee(); employeeRepository.save(employee); Employee result = employeeRepository.findByEmail(employee.getEmail()); assertNotNull(result); } @Test public void testFindAllSortedByName() { Employee employee = getEmployee(); Employee employee1 = new Employee(); employee1.setId(2); employee1.setName("Aarav"); employee1.setAge(20); employee1.setEmail("aarav@test.com"); employeeRepository.save(employee); employeeRepository.save(employee1); List<Employee> result = employeeRepository.findAllSortedByName(); assertEquals(employee1.getName(), result.get(0).getName()); } @Test public void testFindAllSortedByNameUsingNative() { Employee employee = getEmployee(); Employee employee1 = new Employee(); employee1.setId(2); employee1.setName("Aarav"); employee1.setAge(20); employee1.setEmail("aarav@test.com"); employeeRepository.save(employee); employeeRepository.save(employee1); List<Employee> result = employeeRepository.findAllSortedByNameUsingNative(); assertEquals(employee1.getName(), result.get(0).getName()); } } Right Click on the file in eclipse and select Run a JUnit Test and verify the result.
[ { "code": null, "e": 2421, "s": 2112, "text": "Some time case arises, where we need a custom native query to fulfil one test case. We can use @Query annotation to specify a query within a repository. Following is an example. In this example, we are using native query, and set an attribute nativeQuery=true in Query annotation to mark the query as native." }, { "code": null, "e": 2552, "s": 2421, "text": "We've added custom methods in Repository in JPA Custom Query chapter. Now let's add another method using native query and test it." }, { "code": null, "e": 2612, "s": 2552, "text": "Add a method to get list of employees order by their names." }, { "code": null, "e": 3349, "s": 2612, "text": "package com.tutorialspoint.repository;\n\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.CrudRepository;\nimport org.springframework.stereotype.Repository;\nimport com.tutorialspoint.entity.Employee;\n\n@Repository\npublic interface EmployeeRepository extends CrudRepository<Employee, Integer> {\n public List<Employee> findByName(String name);\t\n public List<Employee> findByAge(int age);\n public Employee findByEmail(String email);\n \n @Query(value = \"SELECT e FROM Employee e ORDER BY name\")\n public List<Employee> findAllSortedByName();\n \n @Query(value = \"SELECT * FROM Employee ORDER BY name\", nativeQuery = true)\n public List<Employee> findAllSortedByNameUsingNative();\n}" }, { "code": null, "e": 3487, "s": 3349, "text": "Let's test the methods added by adding their test cases in test file. Last two methods of below file tests the custom query method added." }, { "code": null, "e": 3545, "s": 3487, "text": "Following is the complete code of EmployeeRepositoryTest." }, { "code": null, "e": 7629, "s": 3545, "text": "package com.tutorialspoint.repository;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.transaction.Transactional;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\nimport com.tutorialspoint.entity.Employee;\nimport com.tutorialspoint.sprintbooth2.SprintBootH2Application;\n\n@ExtendWith(SpringExtension.class)\n@Transactional\n@SpringBootTest(classes = SprintBootH2Application.class)\npublic class EmployeeRepositoryTest {\n @Autowired\n private EmployeeRepository employeeRepository;\n\n @Test\n public void testFindById() {\n Employee employee = getEmployee();\t \n employeeRepository.save(employee);\n Employee result = employeeRepository.findById(employee.getId()).get();\n assertEquals(employee.getId(), result.getId());\t \n }\n @Test\n public void testFindAll() {\n Employee employee = getEmployee();\n employeeRepository.save(employee);\n List<Employee> result = new ArrayList<>();\n employeeRepository.findAll().forEach(e -> result.add(e));\n assertEquals(result.size(), 1);\t \n }\n @Test\n public void testSave() {\n Employee employee = getEmployee();\n employeeRepository.save(employee);\n Employee found = employeeRepository.findById(employee.getId()).get();\n assertEquals(employee.getId(), found.getId());\t \n }\n @Test\n public void testDeleteById() {\n Employee employee = getEmployee();\n employeeRepository.save(employee);\n employeeRepository.deleteById(employee.getId());\n List<Employee> result = new ArrayList<>();\n employeeRepository.findAll().forEach(e -> result.add(e));\n assertEquals(result.size(), 0);\n }\n private Employee getEmployee() {\n Employee employee = new Employee();\n employee.setId(1);\n employee.setName(\"Mahesh\");\n employee.setAge(30);\n employee.setEmail(\"mahesh@test.com\");\n return employee;\n }\n @Test\n public void testFindByName() {\n Employee employee = getEmployee();\n employeeRepository.save(employee);\n List<Employee> result = new ArrayList<>();\n employeeRepository.findByName(employee.getName()).forEach(e -> result.add(e));\n assertEquals(result.size(), 1);\t \n }\n @Test\n public void testFindByAge() {\n Employee employee = getEmployee();\n employeeRepository.save(employee);\n List<Employee> result = new ArrayList<>();\n employeeRepository.findByAge(employee.getAge()).forEach(e -> result.add(e));\n assertEquals(result.size(), 1);\t \n }\n @Test\n public void testFindByEmail() {\t \n Employee employee = getEmployee();\n employeeRepository.save(employee);\n Employee result = employeeRepository.findByEmail(employee.getEmail());\t \n assertNotNull(result);\t \n }\n @Test\n public void testFindAllSortedByName() {\n Employee employee = getEmployee();\n Employee employee1 = new Employee();\n employee1.setId(2);\n employee1.setName(\"Aarav\");\n employee1.setAge(20);\n employee1.setEmail(\"aarav@test.com\");\n employeeRepository.save(employee);\t \n employeeRepository.save(employee1);\n List<Employee> result = employeeRepository.findAllSortedByName();\n assertEquals(employee1.getName(), result.get(0).getName());\t \n }\n @Test\n public void testFindAllSortedByNameUsingNative() {\n Employee employee = getEmployee();\n Employee employee1 = new Employee();\n employee1.setId(2);\n employee1.setName(\"Aarav\");\n employee1.setAge(20);\n employee1.setEmail(\"aarav@test.com\");\n employeeRepository.save(employee);\t \n employeeRepository.save(employee1);\n List<Employee> result = employeeRepository.findAllSortedByNameUsingNative();\n assertEquals(employee1.getName(), result.get(0).getName());\t \n } \n}" } ]
Amazon Interview Experience for SDE-1 (Off-Campus)
11 May, 2021 I appeared for the amazon’s interview for SDE full-time role, and here is my experience Technical Interview Round-1 First question was there are given n ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to the sum of their lengths. We need to connect the ropes at a minimum cost. https://www.geeksforgeeks.org/connect-n-ropes-minimum-cost/For example, if we are given 4 ropes of lengths 8, 5, 1, and 2. We can connect the ropes in the following ways.First, connect ropes of lengths 1 and 2. Now we have three ropes of lengths 3(1+2), 5, and 8.Now connect ropes of lengths 3 and 5. Now we have two ropes of lengths 8(5+3) and 8.Finally connect the two ropes 8+8 and all ropes have connected.Total cost for connecting all ropes is 3+8+16 = 27.I told him solution using a priority queue, and also we can implement using the minimum heap, so he asked me to write code by implementing the whole heap function then he asked me about the time complexity of code, all the function of heap, why the time complexity of heap is log(n) and to explain them each and every function of code. I was able to write the code and to explain the time complexity but he was asking why the time complexity of insertion, deletion is log(n), I told him because the maximum height of heap will be log(n) ( where n is the size of the heap) and each level will have a count of element double then next so first level will have 1 element then next atmost 2 then 4 like this so last element will have 2^h element2^h=nh=log(n)in this way, maximum height will be log(n) but he did not seem to be satisfied, and maybe I was not getting his question so he told me we will move to the next question then later we will discuss this.Next question was robber is planning to rob houses and all houses are connected in form of a tree. Each house has a certain amount of money stashed, the only constraint stopping the robber from robbing each of them is that connected houses have security systems connected and it will automatically contact the police if two connected houses were robbed. you have to find the maximum amount of money robber can collect without calling the policeI was thinking solution, and also I was discussing my solution with the interviewer I was going off track, but the interviewer was helpful he gave me test cases where my logic will fail and gave me some hint, so I come up with a recursive solution, and he was also satisfied with the solution. He asked me about the time and space complexity. First question was there are given n ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to the sum of their lengths. We need to connect the ropes at a minimum cost. https://www.geeksforgeeks.org/connect-n-ropes-minimum-cost/For example, if we are given 4 ropes of lengths 8, 5, 1, and 2. We can connect the ropes in the following ways.First, connect ropes of lengths 1 and 2. Now we have three ropes of lengths 3(1+2), 5, and 8.Now connect ropes of lengths 3 and 5. Now we have two ropes of lengths 8(5+3) and 8.Finally connect the two ropes 8+8 and all ropes have connected.Total cost for connecting all ropes is 3+8+16 = 27.I told him solution using a priority queue, and also we can implement using the minimum heap, so he asked me to write code by implementing the whole heap function then he asked me about the time complexity of code, all the function of heap, why the time complexity of heap is log(n) and to explain them each and every function of code. I was able to write the code and to explain the time complexity but he was asking why the time complexity of insertion, deletion is log(n), I told him because the maximum height of heap will be log(n) ( where n is the size of the heap) and each level will have a count of element double then next so first level will have 1 element then next atmost 2 then 4 like this so last element will have 2^h element2^h=nh=log(n)in this way, maximum height will be log(n) but he did not seem to be satisfied, and maybe I was not getting his question so he told me we will move to the next question then later we will discuss this. For example, if we are given 4 ropes of lengths 8, 5, 1, and 2. We can connect the ropes in the following ways. First, connect ropes of lengths 1 and 2. Now we have three ropes of lengths 3(1+2), 5, and 8. Now connect ropes of lengths 3 and 5. Now we have two ropes of lengths 8(5+3) and 8. Finally connect the two ropes 8+8 and all ropes have connected. Total cost for connecting all ropes is 3+8+16 = 27. I told him solution using a priority queue, and also we can implement using the minimum heap, so he asked me to write code by implementing the whole heap function then he asked me about the time complexity of code, all the function of heap, why the time complexity of heap is log(n) and to explain them each and every function of code. I was able to write the code and to explain the time complexity but he was asking why the time complexity of insertion, deletion is log(n), I told him because the maximum height of heap will be log(n) ( where n is the size of the heap) and each level will have a count of element double then next so first level will have 1 element then next atmost 2 then 4 like this so last element will have 2^h element 2^h=n h=log(n) in this way, maximum height will be log(n) but he did not seem to be satisfied, and maybe I was not getting his question so he told me we will move to the next question then later we will discuss this. Next question was robber is planning to rob houses and all houses are connected in form of a tree. Each house has a certain amount of money stashed, the only constraint stopping the robber from robbing each of them is that connected houses have security systems connected and it will automatically contact the police if two connected houses were robbed. you have to find the maximum amount of money robber can collect without calling the policeI was thinking solution, and also I was discussing my solution with the interviewer I was going off track, but the interviewer was helpful he gave me test cases where my logic will fail and gave me some hint, so I come up with a recursive solution, and he was also satisfied with the solution. He asked me about the time and space complexity. I was thinking solution, and also I was discussing my solution with the interviewer I was going off track, but the interviewer was helpful he gave me test cases where my logic will fail and gave me some hint, so I come up with a recursive solution, and he was also satisfied with the solution. He asked me about the time and space complexity. Technical Interview Round-2 Discussion on the project.Then He asked me coding question Given a binary tree, a target node in the binary tree, and an integer value k, print all the nodes that are at distance k from the given target node. No parent pointers are available. https://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/https://media.geeksforgeeks.org/wp-content/uploads/20210506121359/BinaryTree4-300Γ—258.pngConsider the tree shown in diagram Input: target = pointer to node with data 8. root = pointer to node with data 20. k = 2. Output : 10 14 22 If target is 14 and k is 3, then output should be β€œ4 20”I told him the logic O(n) solution.Then a discussion on internship project why using this method only and so on.You have given a list of songs, and you have to play songs randomly how will you implement them.I told him I will use a random function to find a random number then mod it with the size of the list to find an index from 0 to size then I will play the song corresponding to that index.Then he told me that songs should not repeat then I told him to move the current song to the end of the list and then I will decrease the size so that we will not consider the last element we can use vectors for this. Discussion on the project. Then He asked me coding question Given a binary tree, a target node in the binary tree, and an integer value k, print all the nodes that are at distance k from the given target node. No parent pointers are available. https://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/https://media.geeksforgeeks.org/wp-content/uploads/20210506121359/BinaryTree4-300Γ—258.pngConsider the tree shown in diagram Input: target = pointer to node with data 8. root = pointer to node with data 20. k = 2. Output : 10 14 22 If target is 14 and k is 3, then output should be β€œ4 20”I told him the logic O(n) solution. Consider the tree shown in diagram Input: target = pointer to node with data 8. root = pointer to node with data 20. k = 2. Output : 10 14 22 If target is 14 and k is 3, then output should be β€œ4 20” I told him the logic O(n) solution. Then a discussion on internship project why using this method only and so on. You have given a list of songs, and you have to play songs randomly how will you implement them.I told him I will use a random function to find a random number then mod it with the size of the list to find an index from 0 to size then I will play the song corresponding to that index.Then he told me that songs should not repeat then I told him to move the current song to the end of the list and then I will decrease the size so that we will not consider the last element we can use vectors for this. I told him I will use a random function to find a random number then mod it with the size of the list to find an index from 0 to size then I will play the song corresponding to that index. Then he told me that songs should not repeat then I told him to move the current song to the end of the list and then I will decrease the size so that we will not consider the last element we can use vectors for this. Technical Interview Round-3 It was both technical and behavioral roundHave You Faced Any Tight Deadline How Did You Handled ItAny difficult situationHow Do You Handle Conflict in the Workplace (with team or manager)The time when you received negative feedback from your managerTell me about the biggest risk you have takenGiven the structure of the train, and given arrival and departure time of the train and initially, each train will have green color now if two train overlap color will change to blue to implement the function. variation of this problem https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/Structure of trainC++C++struct train { string color; int arrival_time; int departure_time; }First I told him the basic O(n^2) solution then I told him O(n) solution and he asked me to write the code for O(n) solution. It was both technical and behavioral round Have You Faced Any Tight Deadline How Did You Handled It Any difficult situation How Do You Handle Conflict in the Workplace (with team or manager) The time when you received negative feedback from your manager Tell me about the biggest risk you have taken Given the structure of the train, and given arrival and departure time of the train and initially, each train will have green color now if two train overlap color will change to blue to implement the function. variation of this problem https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/Structure of trainC++C++struct train { string color; int arrival_time; int departure_time; }First I told him the basic O(n^2) solution then I told him O(n) solution and he asked me to write the code for O(n) solution. Structure of train C++ struct train { string color; int arrival_time; int departure_time; } First I told him the basic O(n^2) solution then I told him O(n) solution and he asked me to write the code for O(n) solution. Tips:- Keep asking for the clarifications of question and edge cases. Try to discuss your approach with the interviewer and think out loud, The interviewer is there to help you out. Keep track of all edged cases and ask your interviewer about them. if the interviewer is not able to understand your approach try to explain with help of pseudo code. Don’t make your own assumptions, tell them that you are making these assumptions, and if they are good with that then only proceed with your solution. Hope this helps, Best of Luck....... Verdict: Selected! Thanks, GeeksforGeeks for helping me throughout my preparation journey, I did my complete preparation from GeeksforGeeks. Amazon Marketing Off-Campus Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) Write It Up: Share Your Interview Experiences Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Google SWE Interview Experience (Google Online Coding Challenge) 2022 Amazon Interview Experience for SDE-1 Nagarro Interview Experience | On-Campus 2021 Nagarro Interview Experience Tiger Analytics Interview Experience for Data Analyst (On-Campus) Goldman Sachs Interview Experience for FTE ( On-Campus) Virtual 2021-22
[ { "code": null, "e": 54, "s": 26, "text": "\n11 May, 2021" }, { "code": null, "e": 142, "s": 54, "text": "I appeared for the amazon’s interview for SDE full-time role, and here is my experience" }, { "code": null, "e": 170, "s": 142, "text": "Technical Interview Round-1" }, { "code": null, "e": 2600, "s": 170, "text": "First question was there are given n ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to the sum of their lengths. We need to connect the ropes at a minimum cost. https://www.geeksforgeeks.org/connect-n-ropes-minimum-cost/For example, if we are given 4 ropes of lengths 8, 5, 1, and 2. We can connect the ropes in the following ways.First, connect ropes of lengths 1 and 2. Now we have three ropes of lengths 3(1+2), 5, and 8.Now connect ropes of lengths 3 and 5. Now we have two ropes of lengths 8(5+3) and 8.Finally connect the two ropes 8+8 and all ropes have connected.Total cost for connecting all ropes is 3+8+16 = 27.I told him solution using a priority queue, and also we can implement using the minimum heap, so he asked me to write code by implementing the whole heap function then he asked me about the time complexity of code, all the function of heap, why the time complexity of heap is log(n) and to explain them each and every function of code. I was able to write the code and to explain the time complexity but he was asking why the time complexity of insertion, deletion is log(n), I told him because the maximum height of heap will be log(n) ( where n is the size of the heap) and each level will have a count of element double then next so first level will have 1 element then next atmost 2 then 4 like this so last element will have 2^h element2^h=nh=log(n)in this way, maximum height will be log(n) but he did not seem to be satisfied, and maybe I was not getting his question so he told me we will move to the next question then later we will discuss this.Next question was robber is planning to rob houses and all houses are connected in form of a tree. Each house has a certain amount of money stashed, the only constraint stopping the robber from robbing each of them is that connected houses have security systems connected and it will automatically contact the police if two connected houses were robbed. you have to find the maximum amount of money robber can collect without calling the policeI was thinking solution, and also I was discussing my solution with the interviewer I was going off track, but the interviewer was helpful he gave me test cases where my logic will fail and gave me some hint, so I come up with a recursive solution, and he was also satisfied with the solution. He asked me about the time and space complexity." }, { "code": null, "e": 4244, "s": 2600, "text": "First question was there are given n ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to the sum of their lengths. We need to connect the ropes at a minimum cost. https://www.geeksforgeeks.org/connect-n-ropes-minimum-cost/For example, if we are given 4 ropes of lengths 8, 5, 1, and 2. We can connect the ropes in the following ways.First, connect ropes of lengths 1 and 2. Now we have three ropes of lengths 3(1+2), 5, and 8.Now connect ropes of lengths 3 and 5. Now we have two ropes of lengths 8(5+3) and 8.Finally connect the two ropes 8+8 and all ropes have connected.Total cost for connecting all ropes is 3+8+16 = 27.I told him solution using a priority queue, and also we can implement using the minimum heap, so he asked me to write code by implementing the whole heap function then he asked me about the time complexity of code, all the function of heap, why the time complexity of heap is log(n) and to explain them each and every function of code. I was able to write the code and to explain the time complexity but he was asking why the time complexity of insertion, deletion is log(n), I told him because the maximum height of heap will be log(n) ( where n is the size of the heap) and each level will have a count of element double then next so first level will have 1 element then next atmost 2 then 4 like this so last element will have 2^h element2^h=nh=log(n)in this way, maximum height will be log(n) but he did not seem to be satisfied, and maybe I was not getting his question so he told me we will move to the next question then later we will discuss this." }, { "code": null, "e": 4356, "s": 4244, "text": "For example, if we are given 4 ropes of lengths 8, 5, 1, and 2. We can connect the ropes in the following ways." }, { "code": null, "e": 4450, "s": 4356, "text": "First, connect ropes of lengths 1 and 2. Now we have three ropes of lengths 3(1+2), 5, and 8." }, { "code": null, "e": 4535, "s": 4450, "text": "Now connect ropes of lengths 3 and 5. Now we have two ropes of lengths 8(5+3) and 8." }, { "code": null, "e": 4599, "s": 4535, "text": "Finally connect the two ropes 8+8 and all ropes have connected." }, { "code": null, "e": 4651, "s": 4599, "text": "Total cost for connecting all ropes is 3+8+16 = 27." }, { "code": null, "e": 5393, "s": 4651, "text": "I told him solution using a priority queue, and also we can implement using the minimum heap, so he asked me to write code by implementing the whole heap function then he asked me about the time complexity of code, all the function of heap, why the time complexity of heap is log(n) and to explain them each and every function of code. I was able to write the code and to explain the time complexity but he was asking why the time complexity of insertion, deletion is log(n), I told him because the maximum height of heap will be log(n) ( where n is the size of the heap) and each level will have a count of element double then next so first level will have 1 element then next atmost 2 then 4 like this so last element will have 2^h element" }, { "code": null, "e": 5399, "s": 5393, "text": "2^h=n" }, { "code": null, "e": 5408, "s": 5399, "text": "h=log(n)" }, { "code": null, "e": 5610, "s": 5408, "text": "in this way, maximum height will be log(n) but he did not seem to be satisfied, and maybe I was not getting his question so he told me we will move to the next question then later we will discuss this." }, { "code": null, "e": 6397, "s": 5610, "text": "Next question was robber is planning to rob houses and all houses are connected in form of a tree. Each house has a certain amount of money stashed, the only constraint stopping the robber from robbing each of them is that connected houses have security systems connected and it will automatically contact the police if two connected houses were robbed. you have to find the maximum amount of money robber can collect without calling the policeI was thinking solution, and also I was discussing my solution with the interviewer I was going off track, but the interviewer was helpful he gave me test cases where my logic will fail and gave me some hint, so I come up with a recursive solution, and he was also satisfied with the solution. He asked me about the time and space complexity." }, { "code": null, "e": 6740, "s": 6397, "text": "I was thinking solution, and also I was discussing my solution with the interviewer I was going off track, but the interviewer was helpful he gave me test cases where my logic will fail and gave me some hint, so I come up with a recursive solution, and he was also satisfied with the solution. He asked me about the time and space complexity." }, { "code": null, "e": 6768, "s": 6740, "text": "Technical Interview Round-2" }, { "code": null, "e": 7996, "s": 6768, "text": "Discussion on the project.Then He asked me coding question Given a binary tree, a target node in the binary tree, and an integer value k, print all the nodes that are at distance k from the given target node. No parent pointers are available. https://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/https://media.geeksforgeeks.org/wp-content/uploads/20210506121359/BinaryTree4-300Γ—258.pngConsider the tree shown in diagram\nInput: target = pointer to node with data 8. \nroot = pointer to node with data 20. \nk = 2. \nOutput : 10 14 22\nIf target is 14 and k is 3, then output \nshould be β€œ4 20”I told him the logic O(n) solution.Then a discussion on internship project why using this method only and so on.You have given a list of songs, and you have to play songs randomly how will you implement them.I told him I will use a random function to find a random number then mod it with the size of the list to find an index from 0 to size then I will play the song corresponding to that index.Then he told me that songs should not repeat then I told him to move the current song to the end of the list and then I will decrease the size so that we will not consider the last element we can use vectors for this." }, { "code": null, "e": 8023, "s": 7996, "text": "Discussion on the project." }, { "code": null, "e": 8647, "s": 8023, "text": "Then He asked me coding question Given a binary tree, a target node in the binary tree, and an integer value k, print all the nodes that are at distance k from the given target node. No parent pointers are available. https://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/https://media.geeksforgeeks.org/wp-content/uploads/20210506121359/BinaryTree4-300Γ—258.pngConsider the tree shown in diagram\nInput: target = pointer to node with data 8. \nroot = pointer to node with data 20. \nk = 2. \nOutput : 10 14 22\nIf target is 14 and k is 3, then output \nshould be β€œ4 20”I told him the logic O(n) solution." }, { "code": null, "e": 8854, "s": 8647, "text": "Consider the tree shown in diagram\nInput: target = pointer to node with data 8. \nroot = pointer to node with data 20. \nk = 2. \nOutput : 10 14 22\nIf target is 14 and k is 3, then output \nshould be β€œ4 20”" }, { "code": null, "e": 8890, "s": 8854, "text": "I told him the logic O(n) solution." }, { "code": null, "e": 8968, "s": 8890, "text": "Then a discussion on internship project why using this method only and so on." }, { "code": null, "e": 9470, "s": 8968, "text": "You have given a list of songs, and you have to play songs randomly how will you implement them.I told him I will use a random function to find a random number then mod it with the size of the list to find an index from 0 to size then I will play the song corresponding to that index.Then he told me that songs should not repeat then I told him to move the current song to the end of the list and then I will decrease the size so that we will not consider the last element we can use vectors for this." }, { "code": null, "e": 9659, "s": 9470, "text": "I told him I will use a random function to find a random number then mod it with the size of the list to find an index from 0 to size then I will play the song corresponding to that index." }, { "code": null, "e": 9877, "s": 9659, "text": "Then he told me that songs should not repeat then I told him to move the current song to the end of the list and then I will decrease the size so that we will not consider the last element we can use vectors for this." }, { "code": null, "e": 9905, "s": 9877, "text": "Technical Interview Round-3" }, { "code": null, "e": 10741, "s": 9905, "text": "It was both technical and behavioral roundHave You Faced Any Tight Deadline How Did You Handled ItAny difficult situationHow Do You Handle Conflict in the Workplace (with team or manager)The time when you received negative feedback from your managerTell me about the biggest risk you have takenGiven the structure of the train, and given arrival and departure time of the train and initially, each train will have green color now if two train overlap color will change to blue to implement the function. variation of this problem https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/Structure of trainC++C++struct train { string color; int arrival_time; int departure_time; }First I told him the basic O(n^2) solution then I told him O(n) solution and he asked me to write the code for O(n) solution." }, { "code": null, "e": 10784, "s": 10741, "text": "It was both technical and behavioral round" }, { "code": null, "e": 10841, "s": 10784, "text": "Have You Faced Any Tight Deadline How Did You Handled It" }, { "code": null, "e": 10865, "s": 10841, "text": "Any difficult situation" }, { "code": null, "e": 10932, "s": 10865, "text": "How Do You Handle Conflict in the Workplace (with team or manager)" }, { "code": null, "e": 10995, "s": 10932, "text": "The time when you received negative feedback from your manager" }, { "code": null, "e": 11041, "s": 10995, "text": "Tell me about the biggest risk you have taken" }, { "code": null, "e": 11583, "s": 11041, "text": "Given the structure of the train, and given arrival and departure time of the train and initially, each train will have green color now if two train overlap color will change to blue to implement the function. variation of this problem https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/Structure of trainC++C++struct train { string color; int arrival_time; int departure_time; }First I told him the basic O(n^2) solution then I told him O(n) solution and he asked me to write the code for O(n) solution." }, { "code": null, "e": 11602, "s": 11583, "text": "Structure of train" }, { "code": null, "e": 11606, "s": 11602, "text": "C++" }, { "code": "struct train { string color; int arrival_time; int departure_time; }", "e": 11680, "s": 11606, "text": null }, { "code": null, "e": 11806, "s": 11680, "text": "First I told him the basic O(n^2) solution then I told him O(n) solution and he asked me to write the code for O(n) solution." }, { "code": null, "e": 11814, "s": 11806, "text": "Tips:- " }, { "code": null, "e": 11877, "s": 11814, "text": "Keep asking for the clarifications of question and edge cases." }, { "code": null, "e": 11989, "s": 11877, "text": "Try to discuss your approach with the interviewer and think out loud, The interviewer is there to help you out." }, { "code": null, "e": 12056, "s": 11989, "text": "Keep track of all edged cases and ask your interviewer about them." }, { "code": null, "e": 12156, "s": 12056, "text": "if the interviewer is not able to understand your approach try to explain with help of pseudo code." }, { "code": null, "e": 12307, "s": 12156, "text": "Don’t make your own assumptions, tell them that you are making these assumptions, and if they are good with that then only proceed with your solution." }, { "code": null, "e": 12344, "s": 12307, "text": "Hope this helps, Best of Luck......." }, { "code": null, "e": 12363, "s": 12344, "text": "Verdict: Selected!" }, { "code": null, "e": 12485, "s": 12363, "text": "Thanks, GeeksforGeeks for helping me throughout my preparation journey, I did my complete preparation from GeeksforGeeks." }, { "code": null, "e": 12492, "s": 12485, "text": "Amazon" }, { "code": null, "e": 12502, "s": 12492, "text": "Marketing" }, { "code": null, "e": 12513, "s": 12502, "text": "Off-Campus" }, { "code": null, "e": 12535, "s": 12513, "text": "Interview Experiences" }, { "code": null, "e": 12542, "s": 12535, "text": "Amazon" }, { "code": null, "e": 12640, "s": 12542, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12678, "s": 12640, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 12734, "s": 12678, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 12780, "s": 12734, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 12853, "s": 12780, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 12923, "s": 12853, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 12961, "s": 12923, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 13007, "s": 12961, "text": "Nagarro Interview Experience | On-Campus 2021" }, { "code": null, "e": 13036, "s": 13007, "text": "Nagarro Interview Experience" }, { "code": null, "e": 13102, "s": 13036, "text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)" } ]
Auto-Fit vs Auto-Fill Property in CSS Grid
17 Nov, 2021 One of the most important features in CSS Grid is that we can create a responsive layout without using a media query. We don’t need to write a media query for each viewport rather it can be adjusted by using some of the properties of CSS-Grid. It can be adjusted by simply using grid-template-columns property, repeat() function along with auto-fit and auto-fill keywords. Pre-requisites: grid-template-columns fr and repeat()unit 1. Auto-fill: The auto-fill property fills the rows with as many columns as it can fit. The newly added column may be empty but it will still occupy a space in the given row. It is an important property in the CSS grid that make a responsive layout without writing a media query for each grid. Syntax: :auto-fill Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } .item1 { background-color: aqua; border: 1px solid black; border-radius: 3px; max-width: 100%; min-height: 250px; height: auto; } .item2 { background-color: pink; border: 1px solid black; max-width: 100%; border-radius: 3px; min-height: 250px; height: auto; } .set { text-align: center; margin-top: 10%; } .item3 { background-color: green; border: 1px solid black; max-width: 100%; border-radius: 3px; min-height: 250px; height: auto; } .item4 { background-color: springgreen; border: 1px solid black; border-radius: 3px; max-width: 100%; min-height: 250px; height: auto; } body { height: 100vh; place-items: center; padding: 100px 0; } .autofill { width: 90vw; margin-top: 4%; border-radius: 3px; border: 1px solid rgb(22, 3, 3); display: grid; /* Use display property as grid*/ gap: 5px; grid-template-columns: repeat( auto-fill, minmax(200px, 1fr)); } </style></head> <body> <div class="autofill"> <div class="item1"> <h1 class="set">1</h1> </div> <div class="item2"> <h1 class="set">2</h1> </div> <div class="item3"> <h1 class="set">3</h1> </div> <div class="item4"> <h1 class="set">4</h1> </div> </div></body> </html> Output: auto-fill property fig-1 As we can see in figure(fig-1) auto-fill automatically gets resized and leave the available space for the addition of new items in it. 2. Auto-fit: Auto-fit behaves same as auto-fill but The auto-fit property fills the currently available space by expanding its size to take up available space according to device width. If all grid items are empty it is treated as a single track of size 0px. For the purpose of finding the number of auto-repeated tracks, we need to keep the track size to a specified value (e.g., 1px), to avoid division by zero. Syntax: :auto-fit Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } .item1 { background-color: aqua; border: 1px solid black; border-radius: 3px; max-width: 100%; min-height: 250px; height: auto; } .item2 { background-color: pink; border: 1px solid black; max-width: 100%; border-radius: 3px; min-height: 250px; height: auto; } .set { text-align: center; margin-top: 10%; } .item3 { background-color: green; border: 1px solid black; max-width: 100%; border-radius: 3px; min-height: 250px; height: auto; } .item4 { background-color: springgreen; border: 1px solid black; border-radius: 3px; max-width: 100%; min-height: 250px; height: auto; } body { height: 100vh; place-items: center; padding: 100px 0; } .auto-fit { width: 90vw; margin-top: 4%; border-radius: 3px; border: 1px solid rgb(22, 3, 3); display: grid; /* Use display property as grid*/ gap: 5px; grid-template-columns: repeat( auto-fit, minmax(200px, 1fr)); } </style> <title>Document</title></head> <body> <div class="auto-fit"> <div class="item1"> <h1 class="set">1</h1> </div> <div class="item2"> <h1 class="set">2</h1> </div> <div class="item3"> <h1 class="set">3</h1> </div> <div class="item4"> <h1 class="set">4</h1> </div> </div></body> </html> Output: auto-fit property (fig-2) The difference between Auto-fill and Auto-fit is given below: Auto-fill Auto-fit prachisoda1234 CSS-Properties CSS-Questions CSS Difference Between Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Nov, 2021" }, { "code": null, "e": 427, "s": 54, "text": "One of the most important features in CSS Grid is that we can create a responsive layout without using a media query. We don’t need to write a media query for each viewport rather it can be adjusted by using some of the properties of CSS-Grid. It can be adjusted by simply using grid-template-columns property, repeat() function along with auto-fit and auto-fill keywords." }, { "code": null, "e": 443, "s": 427, "text": "Pre-requisites:" }, { "code": null, "e": 465, "s": 443, "text": "grid-template-columns" }, { "code": null, "e": 485, "s": 465, "text": "fr and repeat()unit" }, { "code": null, "e": 781, "s": 485, "text": "1. Auto-fill: The auto-fill property fills the rows with as many columns as it can fit. The newly added column may be empty but it will still occupy a space in the given row. It is an important property in the CSS grid that make a responsive layout without writing a media query for each grid." }, { "code": null, "e": 789, "s": 781, "text": "Syntax:" }, { "code": null, "e": 800, "s": 789, "text": ":auto-fill" }, { "code": null, "e": 809, "s": 800, "text": "Example:" }, { "code": null, "e": 814, "s": 809, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } .item1 { background-color: aqua; border: 1px solid black; border-radius: 3px; max-width: 100%; min-height: 250px; height: auto; } .item2 { background-color: pink; border: 1px solid black; max-width: 100%; border-radius: 3px; min-height: 250px; height: auto; } .set { text-align: center; margin-top: 10%; } .item3 { background-color: green; border: 1px solid black; max-width: 100%; border-radius: 3px; min-height: 250px; height: auto; } .item4 { background-color: springgreen; border: 1px solid black; border-radius: 3px; max-width: 100%; min-height: 250px; height: auto; } body { height: 100vh; place-items: center; padding: 100px 0; } .autofill { width: 90vw; margin-top: 4%; border-radius: 3px; border: 1px solid rgb(22, 3, 3); display: grid; /* Use display property as grid*/ gap: 5px; grid-template-columns: repeat( auto-fill, minmax(200px, 1fr)); } </style></head> <body> <div class=\"autofill\"> <div class=\"item1\"> <h1 class=\"set\">1</h1> </div> <div class=\"item2\"> <h1 class=\"set\">2</h1> </div> <div class=\"item3\"> <h1 class=\"set\">3</h1> </div> <div class=\"item4\"> <h1 class=\"set\">4</h1> </div> </div></body> </html>", "e": 2898, "s": 814, "text": null }, { "code": null, "e": 2906, "s": 2898, "text": "Output:" }, { "code": null, "e": 2931, "s": 2906, "text": "auto-fill property fig-1" }, { "code": null, "e": 3066, "s": 2931, "text": "As we can see in figure(fig-1) auto-fill automatically gets resized and leave the available space for the addition of new items in it." }, { "code": null, "e": 3325, "s": 3066, "text": "2. Auto-fit: Auto-fit behaves same as auto-fill but The auto-fit property fills the currently available space by expanding its size to take up available space according to device width. If all grid items are empty it is treated as a single track of size 0px." }, { "code": null, "e": 3480, "s": 3325, "text": "For the purpose of finding the number of auto-repeated tracks, we need to keep the track size to a specified value (e.g., 1px), to avoid division by zero." }, { "code": null, "e": 3488, "s": 3480, "text": "Syntax:" }, { "code": null, "e": 3498, "s": 3488, "text": ":auto-fit" }, { "code": null, "e": 3507, "s": 3498, "text": "Example:" }, { "code": null, "e": 3512, "s": 3507, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } .item1 { background-color: aqua; border: 1px solid black; border-radius: 3px; max-width: 100%; min-height: 250px; height: auto; } .item2 { background-color: pink; border: 1px solid black; max-width: 100%; border-radius: 3px; min-height: 250px; height: auto; } .set { text-align: center; margin-top: 10%; } .item3 { background-color: green; border: 1px solid black; max-width: 100%; border-radius: 3px; min-height: 250px; height: auto; } .item4 { background-color: springgreen; border: 1px solid black; border-radius: 3px; max-width: 100%; min-height: 250px; height: auto; } body { height: 100vh; place-items: center; padding: 100px 0; } .auto-fit { width: 90vw; margin-top: 4%; border-radius: 3px; border: 1px solid rgb(22, 3, 3); display: grid; /* Use display property as grid*/ gap: 5px; grid-template-columns: repeat( auto-fit, minmax(200px, 1fr)); } </style> <title>Document</title></head> <body> <div class=\"auto-fit\"> <div class=\"item1\"> <h1 class=\"set\">1</h1> </div> <div class=\"item2\"> <h1 class=\"set\">2</h1> </div> <div class=\"item3\"> <h1 class=\"set\">3</h1> </div> <div class=\"item4\"> <h1 class=\"set\">4</h1> </div> </div></body> </html>", "e": 5622, "s": 3512, "text": null }, { "code": null, "e": 5630, "s": 5622, "text": "Output:" }, { "code": null, "e": 5656, "s": 5630, "text": "auto-fit property (fig-2)" }, { "code": null, "e": 5718, "s": 5656, "text": "The difference between Auto-fill and Auto-fit is given below:" }, { "code": null, "e": 5728, "s": 5718, "text": "Auto-fill" }, { "code": null, "e": 5737, "s": 5728, "text": "Auto-fit" }, { "code": null, "e": 5752, "s": 5737, "text": "prachisoda1234" }, { "code": null, "e": 5767, "s": 5752, "text": "CSS-Properties" }, { "code": null, "e": 5781, "s": 5767, "text": "CSS-Questions" }, { "code": null, "e": 5785, "s": 5781, "text": "CSS" }, { "code": null, "e": 5804, "s": 5785, "text": "Difference Between" }, { "code": null, "e": 5821, "s": 5804, "text": "Web Technologies" }, { "code": null, "e": 5919, "s": 5821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5958, "s": 5919, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 5997, "s": 5958, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 6036, "s": 5997, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 6073, "s": 6036, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 6102, "s": 6073, "text": "Form validation using jQuery" }, { "code": null, "e": 6142, "s": 6102, "text": "Class method vs Static method in Python" }, { "code": null, "e": 6173, "s": 6142, "text": "Difference between BFS and DFS" }, { "code": null, "e": 6234, "s": 6173, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6302, "s": 6234, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
time.h localtime() function in C with Examples
07 Nov, 2019 The localtime() function is defined in the time.h header file. The localtime( ) function return the local time of the user i.e time present at the task bar in computer. Syntax: tm* localtime(const time_t* t_ptr); Parameter: This function accepts a parameter t_ptr which represents the pointer to time_t object. Return Value: This function returns a pointer to a struct tm object. Below program illustrate the localtime() function in C: // C program to demonstrate// example of localtime() function. #include <stdio.h>#include <time.h> int main(){ struct tm* local; time_t t = time(NULL); // Get the localtime local = localtime(&t); printf("Local time and date: %s\n", asctime(local)); return 0;} Local time and date: Mon Sep 23 08:25:53 2019 Note: To understand this function clearly, change the time and date of your computer system and run the code again. C-Library C Language C Programs C Quiz Competitive Programming Puzzles Quizzes Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Nov, 2019" }, { "code": null, "e": 197, "s": 28, "text": "The localtime() function is defined in the time.h header file. The localtime( ) function return the local time of the user i.e time present at the task bar in computer." }, { "code": null, "e": 205, "s": 197, "text": "Syntax:" }, { "code": null, "e": 241, "s": 205, "text": "tm* localtime(const time_t* t_ptr);" }, { "code": null, "e": 339, "s": 241, "text": "Parameter: This function accepts a parameter t_ptr which represents the pointer to time_t object." }, { "code": null, "e": 408, "s": 339, "text": "Return Value: This function returns a pointer to a struct tm object." }, { "code": null, "e": 464, "s": 408, "text": "Below program illustrate the localtime() function in C:" }, { "code": "// C program to demonstrate// example of localtime() function. #include <stdio.h>#include <time.h> int main(){ struct tm* local; time_t t = time(NULL); // Get the localtime local = localtime(&t); printf(\"Local time and date: %s\\n\", asctime(local)); return 0;}", "e": 762, "s": 464, "text": null }, { "code": null, "e": 809, "s": 762, "text": "Local time and date: Mon Sep 23 08:25:53 2019\n" }, { "code": null, "e": 925, "s": 809, "text": "Note: To understand this function clearly, change the time and date of your computer system and run the code again." }, { "code": null, "e": 935, "s": 925, "text": "C-Library" }, { "code": null, "e": 946, "s": 935, "text": "C Language" }, { "code": null, "e": 957, "s": 946, "text": "C Programs" }, { "code": null, "e": 964, "s": 957, "text": "C Quiz" }, { "code": null, "e": 988, "s": 964, "text": "Competitive Programming" }, { "code": null, "e": 996, "s": 988, "text": "Puzzles" }, { "code": null, "e": 1004, "s": 996, "text": "Quizzes" }, { "code": null, "e": 1012, "s": 1004, "text": "Puzzles" } ]
Send message to FB friend using Python
22 Jan, 2022 The power of Python comes because of the large number of modules it has. This time we are going to use one of those. Every one of us, one time or another, has a wish of the message (or spamming -.-) our Facebook friend. This is a program that can do something similar. So without further delay, let’s jump right in. Python3 import fbchatfrom getpass import getpassusername = input("Username: ")client = fbchat.Client(username, getpass())no_of_friends = int(raw_input("Number of friends: "))for i in range(no_of_friends): name = input("Name: ") friends = client.getUsers(name) # return a list of names friend = friends[0] msg = input("Message: ") sent = client.send(friend.uid, msg) if sent: print("Message sent successfully!") Now, let’s try to understand the program step by step...Modules required – fbchat (Can be downloaded from here: Github link); getpass (usually it is pre-installed)fbchat Installation: sudo pip install fbchat In case you get the error: ** make sure the development packages of libxml2 and libxslt are installed **In Ubuntu, installing the following packages might help: sudo apt-get install python-dev libxml2-dev libxslt1-dev zlib1g-dev Program explanation: The program can be broken down into several steps:Step – 1: Getting the user credentialsThis part is very easy. Using raw_input() and getpass() we can get the username and password. There are some things to keep in mind in this step. Your Facebook account should have a username. You can check that (or set that) by going to your general settings.We are not using raw_input to get a password because as soon as the characters (or even the password length) are out, we have got a security breach. Your Facebook account should have a username. You can check that (or set that) by going to your general settings. We are not using raw_input to get a password because as soon as the characters (or even the password length) are out, we have got a security breach. Step – 2: Entering the Facebook friend’s name Now that we have signed in, we can enter the number of friends we want to send the message to, and for each of those friends, we can enter the custom message.Step – 3: Spamming *evil* Caution – I am not responsible for extensive usage of the program which can get you banned from Facebook or getting blocked by your friend. Get your own list of guinea pigs! Because of some reason, if you want to send the same message several times, you can use a simple for loop. Nothing difficult about that What you can try out now? Send a message to a group chat. Instead of text only, send images as well. Create your own β€˜desktop’ messenger. Facebook hack – Send a blank message Using the normal Facebook chat or messenger, it is not possible to send a blank message unless you are aware of the alt+0173 trick. But, with this program, you can send blank messages as well!! All you have to do is enter a blank message. That is, when the program asks for the message to be sent, just press enter, and voila!! Your friend will be receiving a series of blank messages...This new code works fine for now : Python3 import fbchatfrom getpass import getpassusername = input("Username: ")client = fbchat.Client(username, getpass())no_of_friends = int(raw_input("Number of friends: "))for i in range(no_of_friends): name = input("Name: ") friends = client.searchForUsers(name) # return a list of names friend = friends[0] msg = input("Message: ") sent = client.sendMessage(msg, thread_id=friend.uid) if sent: print("Message sent successfully!") If you have any other projects in mind concerned with this or if you have prepared some similar to this one, please do share in the comments section!This article is contributed by Vishwesh Ravi Shrimali. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. SunchitSharma punamsingh628700 amartyaghoshgfg Python-projects TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jan, 2022" }, { "code": null, "e": 369, "s": 52, "text": "The power of Python comes because of the large number of modules it has. This time we are going to use one of those. Every one of us, one time or another, has a wish of the message (or spamming -.-) our Facebook friend. This is a program that can do something similar. So without further delay, let’s jump right in. " }, { "code": null, "e": 377, "s": 369, "text": "Python3" }, { "code": "import fbchatfrom getpass import getpassusername = input(\"Username: \")client = fbchat.Client(username, getpass())no_of_friends = int(raw_input(\"Number of friends: \"))for i in range(no_of_friends): name = input(\"Name: \") friends = client.getUsers(name) # return a list of names friend = friends[0] msg = input(\"Message: \") sent = client.send(friend.uid, msg) if sent: print(\"Message sent successfully!\")", "e": 806, "s": 377, "text": null }, { "code": null, "e": 991, "s": 806, "text": "Now, let’s try to understand the program step by step...Modules required – fbchat (Can be downloaded from here: Github link); getpass (usually it is pre-installed)fbchat Installation: " }, { "code": null, "e": 1015, "s": 991, "text": "sudo pip install fbchat" }, { "code": null, "e": 1177, "s": 1015, "text": "In case you get the error: ** make sure the development packages of libxml2 and libxslt are installed **In Ubuntu, installing the following packages might help: " }, { "code": null, "e": 1245, "s": 1177, "text": "sudo apt-get install python-dev libxml2-dev libxslt1-dev zlib1g-dev" }, { "code": null, "e": 1502, "s": 1245, "text": "Program explanation: The program can be broken down into several steps:Step – 1: Getting the user credentialsThis part is very easy. Using raw_input() and getpass() we can get the username and password. There are some things to keep in mind in this step. " }, { "code": null, "e": 1764, "s": 1502, "text": "Your Facebook account should have a username. You can check that (or set that) by going to your general settings.We are not using raw_input to get a password because as soon as the characters (or even the password length) are out, we have got a security breach." }, { "code": null, "e": 1878, "s": 1764, "text": "Your Facebook account should have a username. You can check that (or set that) by going to your general settings." }, { "code": null, "e": 2027, "s": 1878, "text": "We are not using raw_input to get a password because as soon as the characters (or even the password length) are out, we have got a security breach." }, { "code": null, "e": 2259, "s": 2027, "text": "Step – 2: Entering the Facebook friend’s name Now that we have signed in, we can enter the number of friends we want to send the message to, and for each of those friends, we can enter the custom message.Step – 3: Spamming *evil* " }, { "code": null, "e": 2433, "s": 2259, "text": "Caution – I am not responsible for extensive usage of the program which can get you banned from Facebook or getting blocked by your friend. Get your own list of guinea pigs!" }, { "code": null, "e": 2597, "s": 2433, "text": "Because of some reason, if you want to send the same message several times, you can use a simple for loop. Nothing difficult about that What you can try out now? " }, { "code": null, "e": 2629, "s": 2597, "text": "Send a message to a group chat." }, { "code": null, "e": 2672, "s": 2629, "text": "Instead of text only, send images as well." }, { "code": null, "e": 2709, "s": 2672, "text": "Create your own β€˜desktop’ messenger." }, { "code": null, "e": 3170, "s": 2709, "text": "Facebook hack – Send a blank message Using the normal Facebook chat or messenger, it is not possible to send a blank message unless you are aware of the alt+0173 trick. But, with this program, you can send blank messages as well!! All you have to do is enter a blank message. That is, when the program asks for the message to be sent, just press enter, and voila!! Your friend will be receiving a series of blank messages...This new code works fine for now : " }, { "code": null, "e": 3178, "s": 3170, "text": "Python3" }, { "code": "import fbchatfrom getpass import getpassusername = input(\"Username: \")client = fbchat.Client(username, getpass())no_of_friends = int(raw_input(\"Number of friends: \"))for i in range(no_of_friends): name = input(\"Name: \") friends = client.searchForUsers(name) # return a list of names friend = friends[0] msg = input(\"Message: \") sent = client.sendMessage(msg, thread_id=friend.uid) if sent: print(\"Message sent successfully!\")", "e": 3630, "s": 3178, "text": null }, { "code": null, "e": 4086, "s": 3630, "text": "If you have any other projects in mind concerned with this or if you have prepared some similar to this one, please do share in the comments section!This article is contributed by Vishwesh Ravi Shrimali. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 4100, "s": 4086, "text": "SunchitSharma" }, { "code": null, "e": 4117, "s": 4100, "text": "punamsingh628700" }, { "code": null, "e": 4133, "s": 4117, "text": "amartyaghoshgfg" }, { "code": null, "e": 4149, "s": 4133, "text": "Python-projects" }, { "code": null, "e": 4158, "s": 4149, "text": "TechTips" } ]
Knapsack with Duplicate Items | Practice | GeeksforGeeks
Given a set of N items, each with a weight and a value, represented by the array w[] and val[] respectively. Also, a knapsack with weight limit W. The task is to fill the knapsack in such a way that we can get the maximum profit. Return the maximum profit. Note: Each item can be taken any number of times. Example 1: Input: N = 2, W = 3 val[] = {1, 1} wt[] = {2, 1} Output: 3 Explanation: 1.Pick the 2nd element thrice. 2.Total profit = 1 + 1 + 1 = 3. Also the total weight = 1 + 1 + 1 = 3 which is <= W. Example 2: Input: N = 4, W = 8 val[] = {1, 4, 5, 7} wt[] = {1, 3, 4, 5} Output: 11 Explanation: The optimal choice is to pick the 2nd and 4th element. Your Task: You do not need to read input or print anything. Your task is to complete the function knapSack() which takes the values N, W and the arrays val[] and wt[] as input parameters and returns the maximum possible value. Expected Time Complexity: O(N*W) Expected Auxiliary Space: O(W) Constraints: 1 ≀ N, W ≀ 1000 1 ≀ val[i], wt[i] ≀ 100 0 akkeshri14042001in 8 hours int knapSack(int N, int W, int val[], int wt[]) { // code here vector<vector<int>>dp(N+1,vector<int>(W+1)); for(int i=0;i<N+1;i++){ for(int j=0;j<W+1;j++){ if(i==0 or j==0){ dp[i][j]=0; } } } for(int i=1;i<N+1;i++){ for(int j=1;j<W+1;j++){ if(j>=wt[i-1]){ dp[i][j]=max(val[i-1]+dp[i][j-wt[i-1]],dp[i-1][j]); } else{ dp[i][j]=dp[i-1][j]; } } } return dp[N][W]; } 0 sarthakpant31in 59 minutes class Solution{ public: int knapSack(int N, int W, int val[], int wt[]) { // code here vector<vector<int>> dp(N+1,vector<int>(W+1,0)); for(int i=1;i<=N;++i){ for(int j=1;j<=W;++j){ if(wt[i-1]>j){ dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } else{ dp[i][j]=max(dp[i-1][j],dp[i][j-wt[i-1]]+val[i-1]); } } } return dp[N][W]; } }; 0 tanvib20141 day ago class Solution{ public: int knapSack(int N, int W, int val[], int wt[]) { vector<int> dp(W+1, 0); for(int j=0; j<N; j++){ for(int i=1; i<=W; i++){ if(wt[j]<=i)dp[i]=max(dp[i],dp[i-wt[j]]+val[j]); } } return dp[W]; } }; 0 anurondas6762 days ago Clean and simple dp solution: int knapSack(int N, int W, int val[], int wt[]) { // code here vector<int> dp(W+1,INT_MIN); dp[0] = 0; for(int i=1;i<=W;++i){ for(int j=0;j<N;++j){ if(i-wt[j] >= 0){ dp[i] = max(dp[i],val[j]+dp[i-wt[j]]); } } if(dp[i]==INT_MIN) dp[i]=0; } return dp[W]; } 0 chiraggoel162 days ago Can someone add DP to this code please!? int helper(int weightLeft, int profit, int N, int val[], int wt[]){ if(weightLeft == 0) return profit; if(weightLeft < 0) return 0; int ans = INT_MIN; for(int i=0;i<N;i++){ int temp = helper(weightLeft-wt[i],profit+val[i],N,val,wt); ans = max(ans, temp); } return ans; } int knapSack(int N, int W, int val[], int wt[]) { // code here d return helper(W,0,N,val,wt); } 0 2019sushilkumarkori5 days ago int knapSack(int n, int W, int val[], int wt[]) { // Your code here int t[n+1][W+1]; for(int i=0;i<=n;i++){ t[i][0] = 0; } for(int i=1;i<=W;i++){ t[0][i] = 0; } for(int i=1;i<=n;i++){ for(int j=1;j<=W;j++){ if(wt[i-1]<=j){ t[i][j] = max(t[i-1][j],t[i][j-wt[i-1]]+val[i-1]); } else{ t[i][j] = t[i-1][j]; } } } return t[n][W]; } 0 tahabasra925 days ago Top down recursive DP solution in c++ int solve(int val[],int wt[],int i,int W,int curr_w,int n,vector<vector<int>> &dp){ if(curr_w==W){ return 0; } if(i==n){ if(curr_w<W){ return 0; } return INT_MIN; } if(curr_w>W){ return INT_MIN; } if(dp[i][curr_w]!=-1){ return dp[i][curr_w]; } int a=val[i]+solve(val,wt,i,W,curr_w+wt[i],n,dp); int b=solve(val,wt,i+1,W,curr_w,n,dp); return dp[i][curr_w]=max(a,b); } int knapSack(int N, int W, int val[], int wt[]) { // code here vector<vector<int>> dp(N+1, vector<int>(W+1, -1)); int ans= solve(val,wt,0,W,0,N,dp); if(ans<0){ return 0; } return ans; } 0 tkuchchal5305 days ago ##PYTHON class Solution: def knapSack(self, N, W, val, wt): # code here t=[[0 for i in range(W+1)] for j in range(N+1)] for i in range(1,N+1): for j in range(1,W+1): if wt[i-1]<=j: t[i][j]=max(val[i-1]+t[i][j-wt[i-1]],t[i-1][j]) else: t[i][j]=t[i-1][j] return t[N][W] Test Cases Passed: 205 / 205 Total Time Taken: 0.5/2.58 +1 manjunatha_kb1 week ago Java class Solution{ static int knapSack(int N, int W, int val[], int wt[]) { // code here int[][] dp = new int[N+1][W+1]; for(int i=0; i<=N; i++) { for(int j=0; j<=W; j++) { if(i == 0 || j == 0) { dp[i][j] = 0; } else if(wt[i-1] <= j) { dp[i][j] = Math.max(dp[i][j - wt[i-1]] + val[i-1], dp[i-1][j]); } else { dp[i][j] = dp[i-1][j]; } } } return dp[N][W]; } } -1 parasdhanwal2 weeks ago Java Solution | Memoization class Solution{ static int knapSack(int N, int W, int val[], int wt[]) { int dp[][]=new int [N][W+1]; for(int rows[]:dp) Arrays.fill(rows,-1); return knapSack(N-1,W,val,wt,dp); } static int knapSack(int ind, int W, int val[], int wt[],int [][]dp) { if(ind==0) { int ans=(int)((W/wt[ind])*val[ind]); return ans; } if(dp[ind][W]!=-1) return dp[ind][W]; int nt=knapSack(ind-1,W,val,wt,dp); int t=0; if(W-wt[ind]>=0) t=val[ind]+knapSack(ind,W-wt[ind],val,wt,dp); return dp[ind][W]=Math.max(nt,t); } } 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. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems 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": 545, "s": 238, "text": "Given a set of N items, each with a weight and a value, represented by the array w[] and val[] respectively. Also, a knapsack with weight limit W.\nThe task is to fill the knapsack in such a way that we can get the maximum profit. Return the maximum profit.\nNote: Each item can be taken any number of times." }, { "code": null, "e": 558, "s": 547, "text": "Example 1:" }, { "code": null, "e": 752, "s": 558, "text": "Input: N = 2, W = 3\nval[] = {1, 1}\nwt[] = {2, 1}\nOutput: 3\nExplanation: \n1.Pick the 2nd element thrice.\n2.Total profit = 1 + 1 + 1 = 3. Also the total \n weight = 1 + 1 + 1 = 3 which is <= W.\n" }, { "code": null, "e": 765, "s": 754, "text": "Example 2:" }, { "code": null, "e": 906, "s": 765, "text": "Input: N = 4, W = 8\nval[] = {1, 4, 5, 7}\nwt[] = {1, 3, 4, 5}\nOutput: 11\nExplanation: The optimal choice is to \npick the 2nd and 4th element." }, { "code": null, "e": 1135, "s": 908, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function knapSack() which takes the values N, W and the arrays val[] and wt[] as input parameters and returns the maximum possible value." }, { "code": null, "e": 1201, "s": 1137, "text": "Expected Time Complexity: O(N*W)\nExpected Auxiliary Space: O(W)" }, { "code": null, "e": 1256, "s": 1203, "text": "Constraints:\n1 ≀ N, W ≀ 1000\n1 ≀ val[i], wt[i] ≀ 100" }, { "code": null, "e": 1258, "s": 1256, "text": "0" }, { "code": null, "e": 1285, "s": 1258, "text": "akkeshri14042001in 8 hours" }, { "code": null, "e": 1909, "s": 1285, "text": "int knapSack(int N, int W, int val[], int wt[])\n {\n // code here\n vector<vector<int>>dp(N+1,vector<int>(W+1));\n for(int i=0;i<N+1;i++){\n for(int j=0;j<W+1;j++){\n if(i==0 or j==0){\n dp[i][j]=0;\n }\n }\n }\n for(int i=1;i<N+1;i++){\n for(int j=1;j<W+1;j++){\n if(j>=wt[i-1]){\n dp[i][j]=max(val[i-1]+dp[i][j-wt[i-1]],dp[i-1][j]);\n }\n else{\n dp[i][j]=dp[i-1][j];\n }\n \n }\n }\n return dp[N][W];\n }" }, { "code": null, "e": 1911, "s": 1909, "text": "0" }, { "code": null, "e": 1938, "s": 1911, "text": "sarthakpant31in 59 minutes" }, { "code": null, "e": 2475, "s": 1938, "text": "class Solution{\npublic:\n int knapSack(int N, int W, int val[], int wt[])\n {\n // code here\n \n vector<vector<int>> dp(N+1,vector<int>(W+1,0));\n \n \n for(int i=1;i<=N;++i){\n for(int j=1;j<=W;++j){\n if(wt[i-1]>j){\n dp[i][j]=max(dp[i-1][j],dp[i][j-1]);\n }\n else{\n dp[i][j]=max(dp[i-1][j],dp[i][j-wt[i-1]]+val[i-1]);\n }\n }\n }\n \n return dp[N][W];\n }\n};" }, { "code": null, "e": 2477, "s": 2475, "text": "0" }, { "code": null, "e": 2497, "s": 2477, "text": "tanvib20141 day ago" }, { "code": null, "e": 2800, "s": 2497, "text": "class Solution{\npublic:\n int knapSack(int N, int W, int val[], int wt[])\n {\n vector<int> dp(W+1, 0);\n for(int j=0; j<N; j++){\n for(int i=1; i<=W; i++){\n if(wt[j]<=i)dp[i]=max(dp[i],dp[i-wt[j]]+val[j]);\n }\n }\n return dp[W];\n }\n};" }, { "code": null, "e": 2802, "s": 2800, "text": "0" }, { "code": null, "e": 2825, "s": 2802, "text": "anurondas6762 days ago" }, { "code": null, "e": 2855, "s": 2825, "text": "Clean and simple dp solution:" }, { "code": null, "e": 3226, "s": 2855, "text": "int knapSack(int N, int W, int val[], int wt[]) { // code here vector<int> dp(W+1,INT_MIN); dp[0] = 0; for(int i=1;i<=W;++i){ for(int j=0;j<N;++j){ if(i-wt[j] >= 0){ dp[i] = max(dp[i],val[j]+dp[i-wt[j]]); } } if(dp[i]==INT_MIN) dp[i]=0; } return dp[W]; }" }, { "code": null, "e": 3228, "s": 3226, "text": "0" }, { "code": null, "e": 3251, "s": 3228, "text": "chiraggoel162 days ago" }, { "code": null, "e": 3292, "s": 3251, "text": "Can someone add DP to this code please!?" }, { "code": null, "e": 3779, "s": 3292, "text": "int helper(int weightLeft, int profit, int N, int val[], int wt[]){\n if(weightLeft == 0)\n return profit;\n if(weightLeft < 0)\n return 0;\n int ans = INT_MIN;\n for(int i=0;i<N;i++){\n int temp = helper(weightLeft-wt[i],profit+val[i],N,val,wt);\n ans = max(ans, temp);\n }\n return ans;\n }\n\n int knapSack(int N, int W, int val[], int wt[])\n {\n // code here\n d\n return helper(W,0,N,val,wt);\n }" }, { "code": null, "e": 3781, "s": 3779, "text": "0" }, { "code": null, "e": 3811, "s": 3781, "text": "2019sushilkumarkori5 days ago" }, { "code": null, "e": 4352, "s": 3811, "text": "int knapSack(int n, int W, int val[], int wt[])\n { \n // Your code here\n int t[n+1][W+1];\n for(int i=0;i<=n;i++){\n t[i][0] = 0;\n }\n for(int i=1;i<=W;i++){\n t[0][i] = 0;\n }\n for(int i=1;i<=n;i++){\n for(int j=1;j<=W;j++){\n if(wt[i-1]<=j){\n t[i][j] = max(t[i-1][j],t[i][j-wt[i-1]]+val[i-1]);\n }\n else{\n t[i][j] = t[i-1][j];\n }\n }\n }\n return t[n][W];\n }" }, { "code": null, "e": 4354, "s": 4352, "text": "0" }, { "code": null, "e": 4376, "s": 4354, "text": "tahabasra925 days ago" }, { "code": null, "e": 4414, "s": 4376, "text": "Top down recursive DP solution in c++" }, { "code": null, "e": 5174, "s": 4418, "text": "int solve(int val[],int wt[],int i,int W,int curr_w,int n,vector<vector<int>> &dp){ if(curr_w==W){ return 0; } if(i==n){ if(curr_w<W){ return 0; } return INT_MIN; } if(curr_w>W){ return INT_MIN; } if(dp[i][curr_w]!=-1){ return dp[i][curr_w]; } int a=val[i]+solve(val,wt,i,W,curr_w+wt[i],n,dp); int b=solve(val,wt,i+1,W,curr_w,n,dp); return dp[i][curr_w]=max(a,b); } int knapSack(int N, int W, int val[], int wt[]) { // code here vector<vector<int>> dp(N+1, vector<int>(W+1, -1)); int ans= solve(val,wt,0,W,0,N,dp); if(ans<0){ return 0; } return ans; }" }, { "code": null, "e": 5178, "s": 5176, "text": "0" }, { "code": null, "e": 5201, "s": 5178, "text": "tkuchchal5305 days ago" }, { "code": null, "e": 5210, "s": 5201, "text": "##PYTHON" }, { "code": null, "e": 5569, "s": 5210, "text": "class Solution: def knapSack(self, N, W, val, wt): # code here t=[[0 for i in range(W+1)] for j in range(N+1)] for i in range(1,N+1): for j in range(1,W+1): if wt[i-1]<=j: t[i][j]=max(val[i-1]+t[i][j-wt[i-1]],t[i-1][j]) else: t[i][j]=t[i-1][j] return t[N][W]" }, { "code": null, "e": 5588, "s": 5569, "text": "Test Cases Passed:" }, { "code": null, "e": 5598, "s": 5588, "text": "205 / 205" }, { "code": null, "e": 5616, "s": 5598, "text": "Total Time Taken:" }, { "code": null, "e": 5625, "s": 5616, "text": "0.5/2.58" }, { "code": null, "e": 5630, "s": 5627, "text": "+1" }, { "code": null, "e": 5654, "s": 5630, "text": "manjunatha_kb1 week ago" }, { "code": null, "e": 5659, "s": 5654, "text": "Java" }, { "code": null, "e": 6267, "s": 5659, "text": "class Solution{\n static int knapSack(int N, int W, int val[], int wt[])\n {\n // code here\n int[][] dp = new int[N+1][W+1];\n \n for(int i=0; i<=N; i++) {\n for(int j=0; j<=W; j++) {\n \n if(i == 0 || j == 0) {\n dp[i][j] = 0;\n } else if(wt[i-1] <= j) {\n dp[i][j] = Math.max(dp[i][j - wt[i-1]] + val[i-1], dp[i-1][j]);\n } else {\n dp[i][j] = dp[i-1][j];\n }\n \n }\n }\n \n return dp[N][W];\n }\n}" }, { "code": null, "e": 6270, "s": 6267, "text": "-1" }, { "code": null, "e": 6294, "s": 6270, "text": "parasdhanwal2 weeks ago" }, { "code": null, "e": 6322, "s": 6294, "text": "Java Solution | Memoization" }, { "code": null, "e": 7005, "s": 6324, "text": "class Solution{\n static int knapSack(int N, int W, int val[], int wt[])\n {\n int dp[][]=new int [N][W+1];\n for(int rows[]:dp)\n Arrays.fill(rows,-1);\n return knapSack(N-1,W,val,wt,dp);\n }\n \n static int knapSack(int ind, int W, int val[], int wt[],int [][]dp)\n {\n if(ind==0)\n {\n int ans=(int)((W/wt[ind])*val[ind]);\n return ans;\n }\n \n if(dp[ind][W]!=-1) return dp[ind][W];\n \n int nt=knapSack(ind-1,W,val,wt,dp);\n int t=0;\n if(W-wt[ind]>=0)\n t=val[ind]+knapSack(ind,W-wt[ind],val,wt,dp);\n \n return dp[ind][W]=Math.max(nt,t);\n }\n}" }, { "code": null, "e": 7151, "s": 7005, "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": 7187, "s": 7151, "text": " Login to access your submissions. " }, { "code": null, "e": 7197, "s": 7187, "text": "\nProblem\n" }, { "code": null, "e": 7207, "s": 7197, "text": "\nContest\n" }, { "code": null, "e": 7270, "s": 7207, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7455, "s": 7270, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7739, "s": 7455, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 7885, "s": 7739, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 7962, "s": 7885, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 8003, "s": 7962, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 8031, "s": 8003, "text": "Disable browser extensions." }, { "code": null, "e": 8102, "s": 8031, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 8289, "s": 8102, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
How to Create and Use Signals in Django ?
07 Oct, 2021 Signals are used to perform any action on modification of a model instance. The signals are utilities that help us to connect events with actions. We can develop a function that will run when a signal calls it. In other words, Signals are used to perform some action on modification/creation of a particular entry in Database. For example, One would want to create a profile instance, as soon as a new user instance is created in Database There are 3 types of signal. pre_save/post_save: This signal works before/after the method save().pre_delete/post_delete: This signal works before after delete a model’s instance (method delete()) this signal is thrown.pre_init/post_init: This signal is thrown before/after instantiating a model (__init__() method). pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model’s instance (method delete()) this signal is thrown. pre_init/post_init: This signal is thrown before/after instantiating a model (__init__() method). Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? For example, if we want to create a profile of a user as soon as the user is created using post_save signal Models.py Python3 from django.db import modelsfrom django.contrib.auth.models import Userfrom PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' Views.py Python3 from django.shortcuts import render, redirectfrom django.contrib import messagesfrom django.contrib.auth.decorators import login_requiredfrom .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_requireddef profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) Forms.py Python3 from django import formsfrom django.contrib.auth.models import Userfrom django.contrib.auth.forms import UserCreationFormfrom .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] Signals.py(Using receiver method) Python3 # codefrom django.db.models.signals import post_save, pre_deletefrom django.contrib.auth.models import Userfrom django.dispatch import receiverfrom .models import Profile @receiver(post_save, sender=User)def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User)def save_profile(sender, instance, **kwargs): instance.profile.save() You can get confused from this piece of code if you are new to Django, So what is happening is when the User model is saved, a signal is fired called create_profile which creates a Profile instance with a foreign key pointing to the instance of the user. The other method save_profile just saves the instance. Now let’s understand the arguments receiver – The function who receives the signal and does something. sender – Sends the signal created β€” Checks whether the model is created or not instance β€” created model instance **kwargs –wildcard keyword arguments Another way to connect the signal with the function: You need to connect the signals file with the app.py file ready function in order to use them. Python3 from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals Here the signal lives. If we create a user Then his profile is automatically created. You can check it in admin view too Pre_save method is provoked just before the save function is called, Also the model is saved only after successful execution of pre_save method Python3 # codefrom django.db.models.signals import post_save, pre_delete,pre_savefrom django.contrib.auth.models import Userfrom django.dispatch import receiverfrom .models import Profile @receiver(pre_save, sender=User)def checker(sender, instance, **kwargs): if instance.id is None: pass else: current=instance previous=User.objects.get(id=instance.id) if previous.reaction!= current.reaction: #save method can be called We use this if reaction is changed. Using signals Connect Method The alternative way of above method is to use connect method to fire signals. If you just use post_save.connect(my_function), then it will get fired as soon as any save method is fired. post_save.connect(my_function_post_save, sender=MyModel) pre_save.connect(my_function, sender= UserTextMessage) sagar0719kumar Python Django Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Oct, 2021" }, { "code": null, "e": 493, "s": 54, "text": "Signals are used to perform any action on modification of a model instance. The signals are utilities that help us to connect events with actions. We can develop a function that will run when a signal calls it. In other words, Signals are used to perform some action on modification/creation of a particular entry in Database. For example, One would want to create a profile instance, as soon as a new user instance is created in Database" }, { "code": null, "e": 522, "s": 493, "text": "There are 3 types of signal." }, { "code": null, "e": 812, "s": 522, "text": "pre_save/post_save: This signal works before/after the method save().pre_delete/post_delete: This signal works before after delete a model’s instance (method delete()) this signal is thrown.pre_init/post_init: This signal is thrown before/after instantiating a model (__init__() method)." }, { "code": null, "e": 883, "s": 812, "text": "pre_save/post_save: This signal works before/after the method save()." }, { "code": null, "e": 1006, "s": 883, "text": "pre_delete/post_delete: This signal works before after delete a model’s instance (method delete()) this signal is thrown." }, { "code": null, "e": 1104, "s": 1006, "text": "pre_init/post_init: This signal is thrown before/after instantiating a model (__init__() method)." }, { "code": null, "e": 1195, "s": 1104, "text": " Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 1253, "s": 1195, "text": " How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1293, "s": 1253, "text": " How to Create an App in Django ?" }, { "code": null, "e": 1401, "s": 1293, "text": "For example, if we want to create a profile of a user as soon as the user is created using post_save signal" }, { "code": null, "e": 1411, "s": 1401, "text": "Models.py" }, { "code": null, "e": 1419, "s": 1411, "text": "Python3" }, { "code": "from django.db import modelsfrom django.contrib.auth.models import Userfrom PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile'", "e": 1752, "s": 1419, "text": null }, { "code": null, "e": 1761, "s": 1752, "text": "Views.py" }, { "code": null, "e": 1769, "s": 1761, "text": "Python3" }, { "code": "from django.shortcuts import render, redirectfrom django.contrib import messagesfrom django.contrib.auth.decorators import login_requiredfrom .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_requireddef profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context)", "e": 3194, "s": 1769, "text": null }, { "code": null, "e": 3203, "s": 3194, "text": "Forms.py" }, { "code": null, "e": 3211, "s": 3203, "text": "Python3" }, { "code": "from django import formsfrom django.contrib.auth.models import Userfrom django.contrib.auth.forms import UserCreationFormfrom .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image']", "e": 3784, "s": 3211, "text": null }, { "code": null, "e": 3818, "s": 3784, "text": "Signals.py(Using receiver method)" }, { "code": null, "e": 3826, "s": 3818, "text": "Python3" }, { "code": "# codefrom django.db.models.signals import post_save, pre_deletefrom django.contrib.auth.models import Userfrom django.dispatch import receiverfrom .models import Profile @receiver(post_save, sender=User)def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User)def save_profile(sender, instance, **kwargs): instance.profile.save()", "e": 4259, "s": 3826, "text": null }, { "code": null, "e": 4573, "s": 4263, "text": "You can get confused from this piece of code if you are new to Django, So what is happening is when the User model is saved, a signal is fired called create_profile which creates a Profile instance with a foreign key pointing to the instance of the user. The other method save_profile just saves the instance." }, { "code": null, "e": 4610, "s": 4575, "text": "Now let’s understand the arguments" }, { "code": null, "e": 4680, "s": 4612, "text": "receiver – The function who receives the signal and does something." }, { "code": null, "e": 4706, "s": 4680, "text": "sender – Sends the signal" }, { "code": null, "e": 4759, "s": 4706, "text": "created β€” Checks whether the model is created or not" }, { "code": null, "e": 4793, "s": 4759, "text": "instance β€” created model instance" }, { "code": null, "e": 4830, "s": 4793, "text": "**kwargs –wildcard keyword arguments" }, { "code": null, "e": 4885, "s": 4832, "text": "Another way to connect the signal with the function:" }, { "code": null, "e": 4982, "s": 4887, "text": "You need to connect the signals file with the app.py file ready function in order to use them." }, { "code": null, "e": 4992, "s": 4984, "text": "Python3" }, { "code": "from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals", "e": 5123, "s": 4992, "text": null }, { "code": null, "e": 5150, "s": 5127, "text": "Here the signal lives." }, { "code": null, "e": 5173, "s": 5152, "text": "If we create a user " }, { "code": null, "e": 5221, "s": 5177, "text": " Then his profile is automatically created." }, { "code": null, "e": 5260, "s": 5225, "text": "You can check it in admin view too" }, { "code": null, "e": 5408, "s": 5264, "text": "Pre_save method is provoked just before the save function is called, Also the model is saved only after successful execution of pre_save method" }, { "code": null, "e": 5418, "s": 5410, "text": "Python3" }, { "code": "# codefrom django.db.models.signals import post_save, pre_delete,pre_savefrom django.contrib.auth.models import Userfrom django.dispatch import receiverfrom .models import Profile @receiver(pre_save, sender=User)def checker(sender, instance, **kwargs): if instance.id is None: pass else: current=instance previous=User.objects.get(id=instance.id) if previous.reaction!= current.reaction: #save method can be called", "e": 5876, "s": 5418, "text": null }, { "code": null, "e": 5913, "s": 5876, "text": "We use this if reaction is changed." }, { "code": null, "e": 5942, "s": 5913, "text": "Using signals Connect Method" }, { "code": null, "e": 6020, "s": 5942, "text": "The alternative way of above method is to use connect method to fire signals." }, { "code": null, "e": 6128, "s": 6020, "text": "If you just use post_save.connect(my_function), then it will get fired as soon as any save method is fired." }, { "code": null, "e": 6240, "s": 6128, "text": "post_save.connect(my_function_post_save, sender=MyModel)\npre_save.connect(my_function, sender= UserTextMessage)" }, { "code": null, "e": 6255, "s": 6240, "text": "sagar0719kumar" }, { "code": null, "e": 6269, "s": 6255, "text": "Python Django" }, { "code": null, "e": 6293, "s": 6269, "text": "Technical Scripter 2020" }, { "code": null, "e": 6300, "s": 6293, "text": "Python" }, { "code": null, "e": 6319, "s": 6300, "text": "Technical Scripter" }, { "code": null, "e": 6417, "s": 6319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6449, "s": 6417, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6476, "s": 6449, "text": "Python Classes and Objects" }, { "code": null, "e": 6497, "s": 6476, "text": "Python OOPs Concepts" }, { "code": null, "e": 6528, "s": 6497, "text": "Python | os.path.join() method" }, { "code": null, "e": 6584, "s": 6528, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6607, "s": 6584, "text": "Introduction To PYTHON" }, { "code": null, "e": 6649, "s": 6607, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 6691, "s": 6649, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6730, "s": 6691, "text": "Python | datetime.timedelta() function" } ]
Probability of getting at least K heads in N tosses of Coins
25 Mar, 2021 Given N number of coins, the task is to find probability of getting at least K number of heads after tossing all the N coins simultaneously.Example : Suppose we have 3 unbiased coins and we have to find the probability of getting at least 2 heads, so there are 23 = 8 ways to toss these coins, i.e., HHH, HHT, HTH, HTT, THH, THT, TTH, TTT Out of which there are 4 set which contain at least 2 Heads i.e., HHH, HHT, HH, THH So the probability is 4/8 or 0.5 The probability of exactly k success in n trials with probability p of success in any trial is given by: So Probability ( getting at least 4 heads )= Method 1 (Naive) A Naive approach is to store the value of factorial in dp[] array and call it directly whenever it is required. But the problem of this approach is that we can only able to store it up to certain value, after that it will lead to overflow.Below is the implementation of above approach C++ Java Python3 C# PHP Javascript // Naive approach in C++ to find probability of// at least k heads#include<bits/stdc++.h>using namespace std;#define MAX 21 double fact[MAX]; // Returns probability of getting at least k// heads in n tosses.double probability(int k, int n){ double ans = 0; for (int i = k; i <= n; ++i) // Probability of getting exactly i // heads out of n heads ans += fact[n] / (fact[i] * fact[n - i]); // Note: 1 << n = pow(2, n) ans = ans / (1LL << n); return ans;} void precompute(){ // Preprocess all factorial only upto 19, // as after that it will overflow fact[0] = fact[1] = 1; for (int i = 2; i < 20; ++i) fact[i] = fact[i - 1] * i;} // Driver codeint main(){ precompute(); // Probability of getting 2 head out of 3 coins cout << probability(2, 3) << "\n"; // Probability of getting 3 head out of 6 coins cout << probability(3, 6) <<"\n"; // Probability of getting 12 head out of 18 coins cout << probability(12, 18); return 0;} // JAVA Code for Probability of getting// atleast K heads in N tosses of Coinsclass GFG { public static double fact[]; // Returns probability of getting at least k // heads in n tosses. public static double probability(int k, int n) { double ans = 0; for (int i = k; i <= n; ++ i) // Probability of getting exactly i // heads out of n heads ans += fact[n] / (fact[i] * fact[n-i]); // Note: 1 << n = pow(2, n) ans = ans / (1 << n); return ans; } public static void precompute() { // Preprocess all factorial only upto 19, // as after that it will overflow fact[0] = fact[1] = 1; for (int i = 2; i < 20; ++i) fact[i] = fact[i - 1] * i; } // Driver code public static void main(String[] args) { fact = new double[100]; precompute(); // Probability of getting 2 head out // of 3 coins System.out.println(probability(2, 3)); // Probability of getting 3 head out // of 6 coins System.out.println(probability(3, 6)); // Probability of getting 12 head out // of 18 coins System.out.println(probability(12, 18)); } }// This code is contributed by Arnav Kr. Mandal # Naive approach in Python3# to find probability of# at least k heads MAX=21 fact=[0]*MAX # Returns probability of# getting at least k# heads in n tosses.def probability(k, n): ans = 0 for i in range(k,n+1): # Probability of getting exactly i # heads out of n heads ans += fact[n] / (fact[i] * fact[n - i]) # Note: 1 << n = pow(2, n) ans = ans / (1 << n) return ans def precompute(): # Preprocess all factorial # only upto 19, # as after that it # will overflow fact[0] = 1 fact[1] = 1 for i in range(2,20): fact[i] = fact[i - 1] * i # Driver codeif __name__=='__main__': precompute() # Probability of getting 2 # head out of 3 coins print(probability(2, 3)) # Probability of getting # 3 head out of 6 coins print(probability(3, 6)) # Probability of getting # 12 head out of 18 coins print(probability(12, 18)) # This code is contributed by# mits // C# Code for Probability of getting// atleast K heads in N tosses of Coinsusing System; class GFG{ public static double []fact; // Returns probability of getting at least k // heads in n tosses. public static double probability(int k, int n) { double ans = 0; for (int i = k; i <= n; ++ i) // Probability of getting exactly i // heads out of n heads ans += fact[n] / (fact[i] * fact[n - i]); // Note: 1 << n = pow(2, n) ans = ans / (1 << n); return ans; } public static void precompute() { // Preprocess all factorial only upto 19, // as after that it will overflow fact[0] = fact[1] = 1; for (int i = 2; i < 20; ++i) fact[i] = fact[i - 1] * i; } // Driver code public static void Main() { fact = new double[100]; precompute(); // Probability of getting 2 head out // of 3 coins Console.WriteLine(probability(2, 3)); // Probability of getting 3 head out // of 6 coins Console.WriteLine(probability(3, 6)); // Probability of getting 12 head out // of 18 coins Console.Write(probability(12, 18)); }}// This code is contributed by nitin mittal. <?php// Naive approach in PHP to find// probability of at least k heads$MAX = 21; $fact = array_fill(0, $MAX, 0); // Returns probability of getting// at least k heads in n tosses.function probability($k, $n){ global $fact; $ans = 0; for ($i = $k; $i <= $n; ++$i) // Probability of getting exactly // i heads out of n heads $ans += $fact[$n] / ($fact[$i] * $fact[$n - $i]); // Note: 1 << n = pow(2, n) $ans = $ans / (1 << $n); return $ans;} function precompute(){ global $fact; // Preprocess all factorial only // upto 19, as after that it // will overflow $fact[0] = $fact[1] = 1; for ($i = 2; $i < 20; ++$i) $fact[$i] = $fact[$i - 1] * $i;} // Driver codeprecompute(); // Probability of getting 2// head out of 3 coinsecho number_format(probability(2, 3), 6) . "\n"; // Probability of getting 3// head out of 6 coinsecho number_format(probability(3, 6), 6) . "\n"; // Probability of getting 12// head out of 18 coinsecho number_format(probability(12, 18), 6); // This code is contributed by mits?> <script> // javascript Code for Probability of getting// atleast K heads in N tosses of Coins let fact; // Returns probability of getting at least k // heads in n tosses. function probability( k, n) { let ans = 0, i; for ( i = k; i <= n; ++i) // Probability of getting exactly i // heads out of n heads ans += fact[n] / (fact[i] * fact[n - i]); // Note: 1 << n = pow(2, n) ans = ans / (1 << n); return ans; } function precompute() { // Preprocess all factorial only upto 19, // as after that it will overflow fact[0] = fact[1] = 1; for ( let i = 2; i < 20; ++i) fact[i] = fact[i - 1] * i; } // Driver code fact = Array(100).fill(0); precompute(); // Probability of getting 2 head out // of 3 coins document.write(probability(2, 3)+"<br/>"); // Probability of getting 3 head out // of 6 coins document.write(probability(3, 6)+"<br/>"); // Probability of getting 12 head out // of 18 coins document.write(probability(12, 18).toFixed(6)+"<br/>"); // This code is contributed by shikhasingrajput </script> Output: 0.5 0.65625 0.118942 Time Complexity: O(n) where n < 20 Auxiliary space: O(n)Method 2 (Dynamic Programming and Log) Another way is to use Dynamic programming and logarithm. log() is indeed useful to store the factorial of any number without worrying about overflow. Let’s see how we use it: At first let see how n! can be written. n! = n * (n-1) * (n-2) * (n-3) * ... * 3 * 2 * 1 Now take log on base 2 both the sides as: => log(n!) = log(n) + log(n-1) + log(n-2) + ... + log(3) + log(2) + log(1) Now whenever we need to find the factorial of any number, we can use this precomputed value. For example: Suppose if we want to find the value of nCi which can be written as: => nCi = n! / (i! * (n-i)! ) Taking log2() both sides as: => log2 (nCi) = log2 ( n! / (i! * (n-i)! ) ) => log2 (nCi) = log2 ( n! ) - log2(i!) - log2( (n-i)! ) ` Putting dp[num] = log2 (num!), we get: => log2 (nCi) = dp[n] - dp[i] - dp[n-i] But as we see in above relation there is an extra factor of 2n which tells the probability of getting i heads, so => log2 (2n) = n. We will subtract this n from above result to get the final answer: => Pi (log2 (nCi)) = dp[n] - dp[i] - dp[n-i] - n Now: Pi (nCi) = 2 dp[n] - dp[i] - dp[n-i] - n Tada! Now the questions boils down the summation of Pi for all i in [k, n] will yield the answer which can be calculated easily without overflow. Below are the codes to illustrate this: C++ Java Python3 C# PHP Javascript // Dynamic and Logarithm approach find probability of// at least k heads#include<bits/stdc++.h>using namespace std;#define MAX 100001 // dp[i] is going to store Log ( i !) in base 2double dp[MAX]; double probability(int k, int n){ double ans = 0; // Initialize result // Iterate from k heads to n heads for (int i=k; i <= n; ++i) { double res = dp[n] - dp[i] - dp[n-i] - n; ans += pow(2.0, res); } return ans;} void precompute(){ // Preprocess all the logarithm value on base 2 for (int i=2; i < MAX; ++i) dp[i] = log2(i) + dp[i-1];} // Driver codeint main(){ precompute(); // Probability of getting 2 head out of 3 coins cout << probability(2, 3) << "\n"; // Probability of getting 3 head out of 6 coins cout << probability(3, 6) << "\n"; // Probability of getting 500 head out of 10000 coins cout << probability(500, 1000); return 0;} // Dynamic and Logarithm approach find probability of// at least k headsimport java.math.*;class GFG { static int MAX = 100001; // dp[i] is going to store Log ( i !) in base 2static double dp[] = new double[MAX]; static double probability(int k, int n){ double ans = 0.0; // Initialize result // Iterate from k heads to n heads for (int i=k; i <= n; ++i) { double res = dp[n] - dp[i] - dp[n-i] - n; ans += Math.pow(2.0, res); } return ans;} static void precompute(){ // Preprocess all the logarithm value on base 2 for (int i=2; i < MAX; ++i) dp[i] = (Math.log(i)/Math.log(2)) + dp[i-1];} // Driver codepublic static void main(String args[]){ precompute(); // Probability of getting 2 head out of 3 coins System.out.println(probability(2, 3)); // Probability of getting 3 head out of 6 coins System.out.println(probability(3, 6)); // Probability of getting 500 head out of 10000 coins System.out.println(probability(500, 1000));} } # Dynamic and Logarithm approach find probability of# at least k heads from math import log2MAX=100001 # dp[i] is going to store Log ( i !) in base 2dp=[0]*MAX def probability( k, n): ans = 0 # Initialize result # Iterate from k heads to n heads for i in range(k,n+1): res = dp[n] - dp[i] - dp[n-i] - n ans = ans + pow(2.0, res) return ans def precompute(): # Preprocess all the logarithm value on base 2 for i in range(2,MAX): dp[i] = log2(i) + dp[i-1] # Driver codeif __name__=='__main__': precompute() # Probability of getting 2 head out of 3 coins print(probability(2, 3)) # Probability of getting 3 head out of 6 coins print(probability(3, 6)) # Probability of getting 500 head out of 10000 coins print(probability(500, 1000)) #this code is contributed by ash264 // Dynamic and Logarithm approach find probability of// at least k headsusing System; class GFG{ static int MAX = 100001; // dp[i] is going to store Log ( i !) in base 2static double[] dp = new double[MAX]; static double probability(int k, int n){ double ans = 0.0; // Initialize result // Iterate from k heads to n heads for (int i = k; i <= n; ++i) { double res = dp[n] - dp[i] - dp[n-i] - n; ans += Math.Pow(2.0, res); } return ans;} static void precompute(){ // Preprocess all the logarithm value on base 2 for (int i = 2; i < MAX; ++i) dp[i] = (Math.Log(i) / Math.Log(2)) + dp[i - 1];} // Driver codepublic static void Main(){ precompute(); // Probability of getting 2 head out of 3 coins Console.WriteLine(probability(2, 3)); // Probability of getting 3 head out of 6 coins Console.WriteLine(probability(3, 6)); // Probability of getting 500 head out of 10000 coins Console.WriteLine(Math.Round(probability(500, 1000),6));}} // This code is contributed by mits <?php// Dynamic and Logarithm approach// find probability of at least k heads$MAX = 100001; // dp[i] is going to store// Log ( i !) in base 2$dp = array_fill(0, $MAX, 0); function probability($k, $n){ global $MAX, $dp; $ans = 0; // Initialize result // Iterate from k heads to n heads for ($i = $k; $i <= $n; ++$i) { $res = $dp[$n] - $dp[$i] - $dp[$n - $i] - $n; $ans += pow(2.0, $res); } return $ans;} function precompute(){ global $MAX, $dp; // Preprocess all the logarithm // value on base 2 for ($i = 2; $i < $MAX; ++$i) // Note : log2() function is not in php // Some OUTPUT very in their decimal point // Basically log(value,base) is work as // this logic : "log10(value)/log10(2)" // equals to log2(value) $dp[$i] = log($i, 2) + $dp[$i - 1];} // Driver codeprecompute(); // Probability of getting 2// head out of 3 coinsecho probability(2, 3)."\n"; // Probability of getting 3// head out of 6 coinsecho probability(3, 6)."\n"; // Probability of getting 500// head out of 10000 coinsecho probability(500, 1000); // This code is contributed by mits?> <script>// Dynamic and Logarithm approach find probability of// at least k heads let MAX = 100001; // dp[i] is going to store Log ( i !) in base 2 let dp = new Array(MAX).fill(0); function probability(k , n) { var ans = 0.0; // Initialize result // Iterate from k heads to n heads for (let i = k; i <= n; ++i) { var res = dp[n] - dp[i] - dp[n - i] - n; ans += Math.pow(2.0, res); } return ans; } function precompute() { // Preprocess all the logarithm value on base 2 for (let i = 2; i < MAX; ++i) dp[i] = (Math.log(i) / Math.log(2)) + dp[i - 1]; } // Driver code precompute(); // Probability of getting 2 head out of 3 coins document.write(probability(2, 3).toFixed(2)+"<br/>"); // Probability of getting 3 head out of 6 coins document.write(probability(3, 6).toFixed(5)+"<br/>"); // Probability of getting 500 head out of 10000 coins document.write(probability(500, 1000).toFixed(6)+"<br/>"); // This code is contributed by Amit Katiyar</script> Output: 0.5 0.65625 0.512613 Time Complexity: O(n) Auxiliary space: O(n) This approach is beneficial for large value of n ranging from 1 to 106This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal ash264 Mithun Kumar Kirti_Mangal nidhi_biet shikhasingrajput amit143katiyar Dynamic Programming Mathematical Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Mar, 2021" }, { "code": null, "e": 204, "s": 52, "text": "Given N number of coins, the task is to find probability of getting at least K number of heads after tossing all the N coins simultaneously.Example : " }, { "code": null, "e": 513, "s": 204, "text": "Suppose we have 3 unbiased coins and we have to\nfind the probability of getting at least 2 heads,\nso there are 23 = 8 ways to toss these\ncoins, i.e.,\nHHH, HHT, HTH, HTT, THH, THT, TTH, TTT \n\nOut of which there are 4 set which contain at\nleast 2 Heads i.e.,\nHHH, HHT, HH, THH\n\nSo the probability is 4/8 or 0.5" }, { "code": null, "e": 969, "s": 515, "text": "The probability of exactly k success in n trials with probability p of success in any trial is given by: So Probability ( getting at least 4 heads )= Method 1 (Naive) A Naive approach is to store the value of factorial in dp[] array and call it directly whenever it is required. But the problem of this approach is that we can only able to store it up to certain value, after that it will lead to overflow.Below is the implementation of above approach " }, { "code": null, "e": 973, "s": 969, "text": "C++" }, { "code": null, "e": 978, "s": 973, "text": "Java" }, { "code": null, "e": 986, "s": 978, "text": "Python3" }, { "code": null, "e": 989, "s": 986, "text": "C#" }, { "code": null, "e": 993, "s": 989, "text": "PHP" }, { "code": null, "e": 1004, "s": 993, "text": "Javascript" }, { "code": "// Naive approach in C++ to find probability of// at least k heads#include<bits/stdc++.h>using namespace std;#define MAX 21 double fact[MAX]; // Returns probability of getting at least k// heads in n tosses.double probability(int k, int n){ double ans = 0; for (int i = k; i <= n; ++i) // Probability of getting exactly i // heads out of n heads ans += fact[n] / (fact[i] * fact[n - i]); // Note: 1 << n = pow(2, n) ans = ans / (1LL << n); return ans;} void precompute(){ // Preprocess all factorial only upto 19, // as after that it will overflow fact[0] = fact[1] = 1; for (int i = 2; i < 20; ++i) fact[i] = fact[i - 1] * i;} // Driver codeint main(){ precompute(); // Probability of getting 2 head out of 3 coins cout << probability(2, 3) << \"\\n\"; // Probability of getting 3 head out of 6 coins cout << probability(3, 6) <<\"\\n\"; // Probability of getting 12 head out of 18 coins cout << probability(12, 18); return 0;}", "e": 2013, "s": 1004, "text": null }, { "code": "// JAVA Code for Probability of getting// atleast K heads in N tosses of Coinsclass GFG { public static double fact[]; // Returns probability of getting at least k // heads in n tosses. public static double probability(int k, int n) { double ans = 0; for (int i = k; i <= n; ++ i) // Probability of getting exactly i // heads out of n heads ans += fact[n] / (fact[i] * fact[n-i]); // Note: 1 << n = pow(2, n) ans = ans / (1 << n); return ans; } public static void precompute() { // Preprocess all factorial only upto 19, // as after that it will overflow fact[0] = fact[1] = 1; for (int i = 2; i < 20; ++i) fact[i] = fact[i - 1] * i; } // Driver code public static void main(String[] args) { fact = new double[100]; precompute(); // Probability of getting 2 head out // of 3 coins System.out.println(probability(2, 3)); // Probability of getting 3 head out // of 6 coins System.out.println(probability(3, 6)); // Probability of getting 12 head out // of 18 coins System.out.println(probability(12, 18)); } }// This code is contributed by Arnav Kr. Mandal", "e": 3356, "s": 2013, "text": null }, { "code": "# Naive approach in Python3# to find probability of# at least k heads MAX=21 fact=[0]*MAX # Returns probability of# getting at least k# heads in n tosses.def probability(k, n): ans = 0 for i in range(k,n+1): # Probability of getting exactly i # heads out of n heads ans += fact[n] / (fact[i] * fact[n - i]) # Note: 1 << n = pow(2, n) ans = ans / (1 << n) return ans def precompute(): # Preprocess all factorial # only upto 19, # as after that it # will overflow fact[0] = 1 fact[1] = 1 for i in range(2,20): fact[i] = fact[i - 1] * i # Driver codeif __name__=='__main__': precompute() # Probability of getting 2 # head out of 3 coins print(probability(2, 3)) # Probability of getting # 3 head out of 6 coins print(probability(3, 6)) # Probability of getting # 12 head out of 18 coins print(probability(12, 18)) # This code is contributed by# mits", "e": 4312, "s": 3356, "text": null }, { "code": "// C# Code for Probability of getting// atleast K heads in N tosses of Coinsusing System; class GFG{ public static double []fact; // Returns probability of getting at least k // heads in n tosses. public static double probability(int k, int n) { double ans = 0; for (int i = k; i <= n; ++ i) // Probability of getting exactly i // heads out of n heads ans += fact[n] / (fact[i] * fact[n - i]); // Note: 1 << n = pow(2, n) ans = ans / (1 << n); return ans; } public static void precompute() { // Preprocess all factorial only upto 19, // as after that it will overflow fact[0] = fact[1] = 1; for (int i = 2; i < 20; ++i) fact[i] = fact[i - 1] * i; } // Driver code public static void Main() { fact = new double[100]; precompute(); // Probability of getting 2 head out // of 3 coins Console.WriteLine(probability(2, 3)); // Probability of getting 3 head out // of 6 coins Console.WriteLine(probability(3, 6)); // Probability of getting 12 head out // of 18 coins Console.Write(probability(12, 18)); }}// This code is contributed by nitin mittal.", "e": 5634, "s": 4312, "text": null }, { "code": "<?php// Naive approach in PHP to find// probability of at least k heads$MAX = 21; $fact = array_fill(0, $MAX, 0); // Returns probability of getting// at least k heads in n tosses.function probability($k, $n){ global $fact; $ans = 0; for ($i = $k; $i <= $n; ++$i) // Probability of getting exactly // i heads out of n heads $ans += $fact[$n] / ($fact[$i] * $fact[$n - $i]); // Note: 1 << n = pow(2, n) $ans = $ans / (1 << $n); return $ans;} function precompute(){ global $fact; // Preprocess all factorial only // upto 19, as after that it // will overflow $fact[0] = $fact[1] = 1; for ($i = 2; $i < 20; ++$i) $fact[$i] = $fact[$i - 1] * $i;} // Driver codeprecompute(); // Probability of getting 2// head out of 3 coinsecho number_format(probability(2, 3), 6) . \"\\n\"; // Probability of getting 3// head out of 6 coinsecho number_format(probability(3, 6), 6) . \"\\n\"; // Probability of getting 12// head out of 18 coinsecho number_format(probability(12, 18), 6); // This code is contributed by mits?>", "e": 6737, "s": 5634, "text": null }, { "code": "<script> // javascript Code for Probability of getting// atleast K heads in N tosses of Coins let fact; // Returns probability of getting at least k // heads in n tosses. function probability( k, n) { let ans = 0, i; for ( i = k; i <= n; ++i) // Probability of getting exactly i // heads out of n heads ans += fact[n] / (fact[i] * fact[n - i]); // Note: 1 << n = pow(2, n) ans = ans / (1 << n); return ans; } function precompute() { // Preprocess all factorial only upto 19, // as after that it will overflow fact[0] = fact[1] = 1; for ( let i = 2; i < 20; ++i) fact[i] = fact[i - 1] * i; } // Driver code fact = Array(100).fill(0); precompute(); // Probability of getting 2 head out // of 3 coins document.write(probability(2, 3)+\"<br/>\"); // Probability of getting 3 head out // of 6 coins document.write(probability(3, 6)+\"<br/>\"); // Probability of getting 12 head out // of 18 coins document.write(probability(12, 18).toFixed(6)+\"<br/>\"); // This code is contributed by shikhasingrajput </script>", "e": 7963, "s": 6737, "text": null }, { "code": null, "e": 7972, "s": 7963, "text": "Output: " }, { "code": null, "e": 7993, "s": 7972, "text": "0.5\n0.65625\n0.118942" }, { "code": null, "e": 8264, "s": 7993, "text": "Time Complexity: O(n) where n < 20 Auxiliary space: O(n)Method 2 (Dynamic Programming and Log) Another way is to use Dynamic programming and logarithm. log() is indeed useful to store the factorial of any number without worrying about overflow. Let’s see how we use it: " }, { "code": null, "e": 9345, "s": 8264, "text": "At first let see how n! can be written.\nn! = n * (n-1) * (n-2) * (n-3) * ... * 3 * 2 * 1\n\nNow take log on base 2 both the sides as:\n=> log(n!) = log(n) + log(n-1) + log(n-2) + ... + log(3) \n + log(2) + log(1)\n\nNow whenever we need to find the factorial of any number, we can use\nthis precomputed value. For example:\nSuppose if we want to find the value of nCi which can be written as:\n=> nCi = n! / (i! * (n-i)! )\n\nTaking log2() both sides as:\n=> log2 (nCi) = log2 ( n! / (i! * (n-i)! ) )\n=> log2 (nCi) = log2 ( n! ) - log2(i!) - log2( (n-i)! ) `\n\nPutting dp[num] = log2 (num!), we get:\n=> log2 (nCi) = dp[n] - dp[i] - dp[n-i] \n\nBut as we see in above relation there is an extra factor of 2n which\ntells the probability of getting i heads, so\n=> log2 (2n) = n.\n\nWe will subtract this n from above result to get the final answer:\n=> Pi (log2 (nCi)) = dp[n] - dp[i] - dp[n-i] - n\n\nNow: Pi (nCi) = 2 dp[n] - dp[i] - dp[n-i] - n\n\nTada! Now the questions boils down the summation of Pi for all i in\n[k, n] will yield the answer which can be calculated easily without\noverflow." }, { "code": null, "e": 9386, "s": 9345, "text": "Below are the codes to illustrate this: " }, { "code": null, "e": 9390, "s": 9386, "text": "C++" }, { "code": null, "e": 9395, "s": 9390, "text": "Java" }, { "code": null, "e": 9403, "s": 9395, "text": "Python3" }, { "code": null, "e": 9406, "s": 9403, "text": "C#" }, { "code": null, "e": 9410, "s": 9406, "text": "PHP" }, { "code": null, "e": 9421, "s": 9410, "text": "Javascript" }, { "code": "// Dynamic and Logarithm approach find probability of// at least k heads#include<bits/stdc++.h>using namespace std;#define MAX 100001 // dp[i] is going to store Log ( i !) in base 2double dp[MAX]; double probability(int k, int n){ double ans = 0; // Initialize result // Iterate from k heads to n heads for (int i=k; i <= n; ++i) { double res = dp[n] - dp[i] - dp[n-i] - n; ans += pow(2.0, res); } return ans;} void precompute(){ // Preprocess all the logarithm value on base 2 for (int i=2; i < MAX; ++i) dp[i] = log2(i) + dp[i-1];} // Driver codeint main(){ precompute(); // Probability of getting 2 head out of 3 coins cout << probability(2, 3) << \"\\n\"; // Probability of getting 3 head out of 6 coins cout << probability(3, 6) << \"\\n\"; // Probability of getting 500 head out of 10000 coins cout << probability(500, 1000); return 0;}", "e": 10333, "s": 9421, "text": null }, { "code": "// Dynamic and Logarithm approach find probability of// at least k headsimport java.math.*;class GFG { static int MAX = 100001; // dp[i] is going to store Log ( i !) in base 2static double dp[] = new double[MAX]; static double probability(int k, int n){ double ans = 0.0; // Initialize result // Iterate from k heads to n heads for (int i=k; i <= n; ++i) { double res = dp[n] - dp[i] - dp[n-i] - n; ans += Math.pow(2.0, res); } return ans;} static void precompute(){ // Preprocess all the logarithm value on base 2 for (int i=2; i < MAX; ++i) dp[i] = (Math.log(i)/Math.log(2)) + dp[i-1];} // Driver codepublic static void main(String args[]){ precompute(); // Probability of getting 2 head out of 3 coins System.out.println(probability(2, 3)); // Probability of getting 3 head out of 6 coins System.out.println(probability(3, 6)); // Probability of getting 500 head out of 10000 coins System.out.println(probability(500, 1000));} }", "e": 11340, "s": 10333, "text": null }, { "code": "# Dynamic and Logarithm approach find probability of# at least k heads from math import log2MAX=100001 # dp[i] is going to store Log ( i !) in base 2dp=[0]*MAX def probability( k, n): ans = 0 # Initialize result # Iterate from k heads to n heads for i in range(k,n+1): res = dp[n] - dp[i] - dp[n-i] - n ans = ans + pow(2.0, res) return ans def precompute(): # Preprocess all the logarithm value on base 2 for i in range(2,MAX): dp[i] = log2(i) + dp[i-1] # Driver codeif __name__=='__main__': precompute() # Probability of getting 2 head out of 3 coins print(probability(2, 3)) # Probability of getting 3 head out of 6 coins print(probability(3, 6)) # Probability of getting 500 head out of 10000 coins print(probability(500, 1000)) #this code is contributed by ash264", "e": 12183, "s": 11340, "text": null }, { "code": "// Dynamic and Logarithm approach find probability of// at least k headsusing System; class GFG{ static int MAX = 100001; // dp[i] is going to store Log ( i !) in base 2static double[] dp = new double[MAX]; static double probability(int k, int n){ double ans = 0.0; // Initialize result // Iterate from k heads to n heads for (int i = k; i <= n; ++i) { double res = dp[n] - dp[i] - dp[n-i] - n; ans += Math.Pow(2.0, res); } return ans;} static void precompute(){ // Preprocess all the logarithm value on base 2 for (int i = 2; i < MAX; ++i) dp[i] = (Math.Log(i) / Math.Log(2)) + dp[i - 1];} // Driver codepublic static void Main(){ precompute(); // Probability of getting 2 head out of 3 coins Console.WriteLine(probability(2, 3)); // Probability of getting 3 head out of 6 coins Console.WriteLine(probability(3, 6)); // Probability of getting 500 head out of 10000 coins Console.WriteLine(Math.Round(probability(500, 1000),6));}} // This code is contributed by mits", "e": 13224, "s": 12183, "text": null }, { "code": "<?php// Dynamic and Logarithm approach// find probability of at least k heads$MAX = 100001; // dp[i] is going to store// Log ( i !) in base 2$dp = array_fill(0, $MAX, 0); function probability($k, $n){ global $MAX, $dp; $ans = 0; // Initialize result // Iterate from k heads to n heads for ($i = $k; $i <= $n; ++$i) { $res = $dp[$n] - $dp[$i] - $dp[$n - $i] - $n; $ans += pow(2.0, $res); } return $ans;} function precompute(){ global $MAX, $dp; // Preprocess all the logarithm // value on base 2 for ($i = 2; $i < $MAX; ++$i) // Note : log2() function is not in php // Some OUTPUT very in their decimal point // Basically log(value,base) is work as // this logic : \"log10(value)/log10(2)\" // equals to log2(value) $dp[$i] = log($i, 2) + $dp[$i - 1];} // Driver codeprecompute(); // Probability of getting 2// head out of 3 coinsecho probability(2, 3).\"\\n\"; // Probability of getting 3// head out of 6 coinsecho probability(3, 6).\"\\n\"; // Probability of getting 500// head out of 10000 coinsecho probability(500, 1000); // This code is contributed by mits?>", "e": 14395, "s": 13224, "text": null }, { "code": "<script>// Dynamic and Logarithm approach find probability of// at least k heads let MAX = 100001; // dp[i] is going to store Log ( i !) in base 2 let dp = new Array(MAX).fill(0); function probability(k , n) { var ans = 0.0; // Initialize result // Iterate from k heads to n heads for (let i = k; i <= n; ++i) { var res = dp[n] - dp[i] - dp[n - i] - n; ans += Math.pow(2.0, res); } return ans; } function precompute() { // Preprocess all the logarithm value on base 2 for (let i = 2; i < MAX; ++i) dp[i] = (Math.log(i) / Math.log(2)) + dp[i - 1]; } // Driver code precompute(); // Probability of getting 2 head out of 3 coins document.write(probability(2, 3).toFixed(2)+\"<br/>\"); // Probability of getting 3 head out of 6 coins document.write(probability(3, 6).toFixed(5)+\"<br/>\"); // Probability of getting 500 head out of 10000 coins document.write(probability(500, 1000).toFixed(6)+\"<br/>\"); // This code is contributed by Amit Katiyar</script>", "e": 15500, "s": 14395, "text": null }, { "code": null, "e": 15510, "s": 15500, "text": "Output: " }, { "code": null, "e": 15531, "s": 15510, "text": "0.5\n0.65625\n0.512613" }, { "code": null, "e": 16072, "s": 15531, "text": "Time Complexity: O(n) Auxiliary space: O(n) This approach is beneficial for large value of n ranging from 1 to 106This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 16085, "s": 16072, "text": "nitin mittal" }, { "code": null, "e": 16092, "s": 16085, "text": "ash264" }, { "code": null, "e": 16105, "s": 16092, "text": "Mithun Kumar" }, { "code": null, "e": 16118, "s": 16105, "text": "Kirti_Mangal" }, { "code": null, "e": 16129, "s": 16118, "text": "nidhi_biet" }, { "code": null, "e": 16146, "s": 16129, "text": "shikhasingrajput" }, { "code": null, "e": 16161, "s": 16146, "text": "amit143katiyar" }, { "code": null, "e": 16181, "s": 16161, "text": "Dynamic Programming" }, { "code": null, "e": 16194, "s": 16181, "text": "Mathematical" }, { "code": null, "e": 16214, "s": 16194, "text": "Dynamic Programming" }, { "code": null, "e": 16227, "s": 16214, "text": "Mathematical" } ]
SQL Query to Get Column Names From a Table
10 Oct, 2021 SQL stands for Structured Query Language. It is a language used to interact with the database, i.e to create a database, to create a table in the database, to retrieve data or update a table in the database, etc. SQL is an ANSI(American National Standards Institute) standard. Using SQL, we can do many things. For example – we can execute queries, we can insert records into a table, we can update records, we can create a database, we can create a table, we can delete a table, etc. In this article, we will look at how to get column names from a table. Step 1: Creating Database We are creating the database using CREATE query. Query: CREATE DATABASE Test Output: The command is completed successfully. It means the Database named Test is created. The next step is to create a table. Step 2: Creating table The Data table will have three fields FirstName, LastName, and Age. Using the below query we will be creating a table. Query: CREATE TABLE Data(FirstName varchar(40), LastName varchar(30),Age int, ); Output: The Data table is created in the database. Step 3: Insert Data into the Table Using the below query we will be adding the data to our table. Query: INSERT INTO Data VALUES ('Rahul','Sharma',15), ('Soha','Shaikh',24), ('Vivek','Rao',18), ('Sonali ','Rane',20); Output: We have added the data to our table. We can verify the data in the table using the SELECT query as below. Step 4: View Table Data Query: SELECT * FROM Data Output: Step 5: Getting column names from the table We will be using sys. columns to get the column names in a table. It is a system table and used for maintaining column information. It contains the following information about columns: Name – Name of the column. Object_id – ID of the object for the table in which column belongs. Column_id – ID of the column. user_type_id – ID of the user-defined column type. max_length – Maximum length of the column (In bytes). is_nullable – 1=Column is nullable. Query: SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('Data') Output: Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL | DROP, TRUNCATE
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Oct, 2021" }, { "code": null, "e": 538, "s": 52, "text": "SQL stands for Structured Query Language. It is a language used to interact with the database, i.e to create a database, to create a table in the database, to retrieve data or update a table in the database, etc. SQL is an ANSI(American National Standards Institute) standard. Using SQL, we can do many things. For example – we can execute queries, we can insert records into a table, we can update records, we can create a database, we can create a table, we can delete a table, etc. " }, { "code": null, "e": 609, "s": 538, "text": "In this article, we will look at how to get column names from a table." }, { "code": null, "e": 635, "s": 609, "text": "Step 1: Creating Database" }, { "code": null, "e": 684, "s": 635, "text": "We are creating the database using CREATE query." }, { "code": null, "e": 691, "s": 684, "text": "Query:" }, { "code": null, "e": 712, "s": 691, "text": "CREATE DATABASE Test" }, { "code": null, "e": 720, "s": 712, "text": "Output:" }, { "code": null, "e": 840, "s": 720, "text": "The command is completed successfully. It means the Database named Test is created. The next step is to create a table." }, { "code": null, "e": 863, "s": 840, "text": "Step 2: Creating table" }, { "code": null, "e": 982, "s": 863, "text": "The Data table will have three fields FirstName, LastName, and Age. Using the below query we will be creating a table." }, { "code": null, "e": 989, "s": 982, "text": "Query:" }, { "code": null, "e": 1063, "s": 989, "text": "CREATE TABLE Data(FirstName varchar(40),\nLastName varchar(30),Age int, );" }, { "code": null, "e": 1071, "s": 1063, "text": "Output:" }, { "code": null, "e": 1114, "s": 1071, "text": "The Data table is created in the database." }, { "code": null, "e": 1150, "s": 1114, "text": "Step 3: Insert Data into the Table" }, { "code": null, "e": 1213, "s": 1150, "text": "Using the below query we will be adding the data to our table." }, { "code": null, "e": 1220, "s": 1213, "text": "Query:" }, { "code": null, "e": 1341, "s": 1220, "text": "INSERT INTO Data\nVALUES ('Rahul','Sharma',15),\n ('Soha','Shaikh',24),\n ('Vivek','Rao',18),\n ('Sonali ','Rane',20);" }, { "code": null, "e": 1349, "s": 1341, "text": "Output:" }, { "code": null, "e": 1455, "s": 1349, "text": "We have added the data to our table. We can verify the data in the table using the SELECT query as below." }, { "code": null, "e": 1479, "s": 1455, "text": "Step 4: View Table Data" }, { "code": null, "e": 1486, "s": 1479, "text": "Query:" }, { "code": null, "e": 1505, "s": 1486, "text": "SELECT * FROM Data" }, { "code": null, "e": 1513, "s": 1505, "text": "Output:" }, { "code": null, "e": 1557, "s": 1513, "text": "Step 5: Getting column names from the table" }, { "code": null, "e": 1742, "s": 1557, "text": "We will be using sys. columns to get the column names in a table. It is a system table and used for maintaining column information. It contains the following information about columns:" }, { "code": null, "e": 1769, "s": 1742, "text": "Name – Name of the column." }, { "code": null, "e": 1837, "s": 1769, "text": "Object_id – ID of the object for the table in which column belongs." }, { "code": null, "e": 1867, "s": 1837, "text": "Column_id – ID of the column." }, { "code": null, "e": 1918, "s": 1867, "text": "user_type_id – ID of the user-defined column type." }, { "code": null, "e": 1972, "s": 1918, "text": "max_length – Maximum length of the column (In bytes)." }, { "code": null, "e": 2008, "s": 1972, "text": "is_nullable – 1=Column is nullable." }, { "code": null, "e": 2015, "s": 2008, "text": "Query:" }, { "code": null, "e": 2082, "s": 2015, "text": "SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('Data') " }, { "code": null, "e": 2090, "s": 2082, "text": "Output:" }, { "code": null, "e": 2097, "s": 2090, "text": "Picked" }, { "code": null, "e": 2107, "s": 2097, "text": "SQL-Query" }, { "code": null, "e": 2118, "s": 2107, "text": "SQL-Server" }, { "code": null, "e": 2122, "s": 2118, "text": "SQL" }, { "code": null, "e": 2126, "s": 2122, "text": "SQL" }, { "code": null, "e": 2224, "s": 2126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2290, "s": 2224, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2314, "s": 2290, "text": "Window functions in SQL" }, { "code": null, "e": 2346, "s": 2314, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2363, "s": 2346, "text": "SQL using Python" }, { "code": null, "e": 2396, "s": 2363, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2474, "s": 2396, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2504, "s": 2474, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2540, "s": 2504, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2571, "s": 2540, "text": "SQL Query to Compare Two Dates" } ]
How to create a ComboBox using JavaFX?
A combo box is similar to a choice box it holds multiple items and, allows you to select one of them. It can be formed by adding scrolling to a drop-down list. You can create a combo box by instantiating the javafx.scene.control.ComboBox class. The following Example demonstrates the creation of a ComboBox. import javafx.application.Application; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.stage.Stage; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; public class ComboBoxExample extends Application { public void start(Stage stage) { //Setting the label Label label = new Label("Select Desired Course:"); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12); label.setFont(font); //Creating a combo box ComboBox<String> combo = new ComboBox<String>(); //Setting the prompt text of the combo box combo.setPromptText("Select Course"); //Getting the observable list of the combo box ObservableList<String> list = combo.getItems(); //Adding items to the combo box list.add("Java"); list.add("C++"); list.add("Python"); list.add("Big Data"); list.add("Machine Learning"); HBox hbox = new HBox(15); //Setting the space between the nodes of a HBox pane hbox.setPadding(new Insets(75, 150, 50, 60)); hbox.getChildren().addAll(label, combo); //Creating a scene object Scene scene = new Scene(new Group(hbox), 595, 280, Color.BEIGE); stage.setTitle("Combo Box"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1432, "s": 1187, "text": "A combo box is similar to a choice box it holds multiple items and, allows you to select one of them. It can be formed by adding scrolling to a drop-down list. You can create a combo box by instantiating the javafx.scene.control.ComboBox class." }, { "code": null, "e": 1495, "s": 1432, "text": "The following Example demonstrates the creation of a ComboBox." }, { "code": null, "e": 3123, "s": 1495, "text": "import javafx.application.Application;\nimport javafx.collections.ObservableList;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ComboBox;\nimport javafx.scene.control.Label;\nimport javafx.stage.Stage;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.paint.Color;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\npublic class ComboBoxExample extends Application {\n public void start(Stage stage) {\n //Setting the label\n Label label = new Label(\"Select Desired Course:\");\n Font font = Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 12);\n label.setFont(font);\n //Creating a combo box\n ComboBox<String> combo = new ComboBox<String>();\n //Setting the prompt text of the combo box\n combo.setPromptText(\"Select Course\");\n //Getting the observable list of the combo box\n ObservableList<String> list = combo.getItems();\n //Adding items to the combo box\n list.add(\"Java\");\n list.add(\"C++\");\n list.add(\"Python\");\n list.add(\"Big Data\");\n list.add(\"Machine Learning\");\n HBox hbox = new HBox(15);\n //Setting the space between the nodes of a HBox pane\n hbox.setPadding(new Insets(75, 150, 50, 60));\n hbox.getChildren().addAll(label, combo);\n //Creating a scene object\n Scene scene = new Scene(new Group(hbox), 595, 280, Color.BEIGE);\n stage.setTitle(\"Combo Box\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
SWING - WindowEvent Class
The object of this class represents the change in state of a window.This low-level event is generated by a Window object when it is opened, closed, activated, deactivated, iconified, or deiconified, or when the focus is transfered into or out of the Window. Following is the declaration for java.awt.event.WindowEvent class βˆ’ public class WindowEvent extends ComponentEvent Following are the fields for java.awt.event.WindowEvent class βˆ’ static int WINDOW_ACTIVATED βˆ’ The window-activated event type. static int WINDOW_ACTIVATED βˆ’ The window-activated event type. static int WINDOW_CLOSED βˆ’ The window closed event. static int WINDOW_CLOSED βˆ’ The window closed event. static int WINDOW_CLOSING βˆ’ The "window is closing" event. static int WINDOW_CLOSING βˆ’ The "window is closing" event. static int WINDOW_DEACTIVATED βˆ’ The window-deactivated event type. static int WINDOW_DEACTIVATED βˆ’ The window-deactivated event type. static int WINDOW_DEICONIFIED βˆ’ The window deiconified event type. static int WINDOW_DEICONIFIED βˆ’ The window deiconified event type. static int WINDOW_FIRST βˆ’ The first number in the range of IDs used for window events. static int WINDOW_FIRST βˆ’ The first number in the range of IDs used for window events. static int WINDOW_GAINED_FOCUS βˆ’ The window-gained-focus event type. static int WINDOW_GAINED_FOCUS βˆ’ The window-gained-focus event type. static int WINDOW_ICONIFIED βˆ’ The window iconified event. static int WINDOW_ICONIFIED βˆ’ The window iconified event. static int WINDOW_LAST βˆ’ The last number in the range of IDs used for window events. static int WINDOW_LAST βˆ’ The last number in the range of IDs used for window events. static int WINDOW_LOST_FOCUS βˆ’ The window-lost-focus event type. static int WINDOW_LOST_FOCUS βˆ’ The window-lost-focus event type. static int WINDOW_OPENED βˆ’ The window opened event. static int WINDOW_OPENED βˆ’ The window opened event. static int WINDOW_STATE_CHANGED βˆ’ The window-state-changed event type. static int WINDOW_STATE_CHANGED βˆ’ The window-state-changed event type. WindowEvent(Window source, int id) Constructs a WindowEvent object. WindowEvent(Window source, int id, int oldState, int newState) Constructs a WindowEvent object with the specified previous and new window states. WindowEvent(Window source, int id, Window opposite) Constructs a WindowEvent object with the specified opposite Window. WindowEvent(Window source, int id, Window opposite, int oldState, int newState) Constructs a WindowEvent object. int getNewState() For WINDOW_STATE_CHANGED events returns the new state of the window. int getOldState() For WINDOW_STATE_CHANGED events returns the previous state of the window. Window getOppositeWindow() Returns the other Window involved in this focus or activation change. Window getWindow() Returns the originator of the event. String paramString() Returns a parameter string identifying this event. This class inherits methods from the following classes βˆ’
[ { "code": null, "e": 2155, "s": 1897, "text": "The object of this class represents the change in state of a window.This low-level event is generated by a Window object when it is opened, closed, activated, deactivated, iconified, or deiconified, or when the focus is transfered into or out of the Window." }, { "code": null, "e": 2223, "s": 2155, "text": "Following is the declaration for java.awt.event.WindowEvent class βˆ’" }, { "code": null, "e": 2275, "s": 2223, "text": "public class WindowEvent\n extends ComponentEvent\n" }, { "code": null, "e": 2339, "s": 2275, "text": "Following are the fields for java.awt.event.WindowEvent class βˆ’" }, { "code": null, "e": 2402, "s": 2339, "text": "static int WINDOW_ACTIVATED βˆ’ The window-activated event type." }, { "code": null, "e": 2465, "s": 2402, "text": "static int WINDOW_ACTIVATED βˆ’ The window-activated event type." }, { "code": null, "e": 2517, "s": 2465, "text": "static int WINDOW_CLOSED βˆ’ The window closed event." }, { "code": null, "e": 2569, "s": 2517, "text": "static int WINDOW_CLOSED βˆ’ The window closed event." }, { "code": null, "e": 2628, "s": 2569, "text": "static int WINDOW_CLOSING βˆ’ The \"window is closing\" event." }, { "code": null, "e": 2687, "s": 2628, "text": "static int WINDOW_CLOSING βˆ’ The \"window is closing\" event." }, { "code": null, "e": 2754, "s": 2687, "text": "static int WINDOW_DEACTIVATED βˆ’ The window-deactivated event type." }, { "code": null, "e": 2821, "s": 2754, "text": "static int WINDOW_DEACTIVATED βˆ’ The window-deactivated event type." }, { "code": null, "e": 2888, "s": 2821, "text": "static int WINDOW_DEICONIFIED βˆ’ The window deiconified event type." }, { "code": null, "e": 2955, "s": 2888, "text": "static int WINDOW_DEICONIFIED βˆ’ The window deiconified event type." }, { "code": null, "e": 3042, "s": 2955, "text": "static int WINDOW_FIRST βˆ’ The first number in the range of IDs used for window events." }, { "code": null, "e": 3129, "s": 3042, "text": "static int WINDOW_FIRST βˆ’ The first number in the range of IDs used for window events." }, { "code": null, "e": 3198, "s": 3129, "text": "static int WINDOW_GAINED_FOCUS βˆ’ The window-gained-focus event type." }, { "code": null, "e": 3267, "s": 3198, "text": "static int WINDOW_GAINED_FOCUS βˆ’ The window-gained-focus event type." }, { "code": null, "e": 3325, "s": 3267, "text": "static int WINDOW_ICONIFIED βˆ’ The window iconified event." }, { "code": null, "e": 3383, "s": 3325, "text": "static int WINDOW_ICONIFIED βˆ’ The window iconified event." }, { "code": null, "e": 3468, "s": 3383, "text": "static int WINDOW_LAST βˆ’ The last number in the range of IDs used for window events." }, { "code": null, "e": 3553, "s": 3468, "text": "static int WINDOW_LAST βˆ’ The last number in the range of IDs used for window events." }, { "code": null, "e": 3618, "s": 3553, "text": "static int WINDOW_LOST_FOCUS βˆ’ The window-lost-focus event type." }, { "code": null, "e": 3683, "s": 3618, "text": "static int WINDOW_LOST_FOCUS βˆ’ The window-lost-focus event type." }, { "code": null, "e": 3735, "s": 3683, "text": "static int WINDOW_OPENED βˆ’ The window opened event." }, { "code": null, "e": 3787, "s": 3735, "text": "static int WINDOW_OPENED βˆ’ The window opened event." }, { "code": null, "e": 3858, "s": 3787, "text": "static int WINDOW_STATE_CHANGED βˆ’ The window-state-changed event type." }, { "code": null, "e": 3929, "s": 3858, "text": "static int WINDOW_STATE_CHANGED βˆ’ The window-state-changed event type." }, { "code": null, "e": 3964, "s": 3929, "text": "WindowEvent(Window source, int id)" }, { "code": null, "e": 3997, "s": 3964, "text": "Constructs a WindowEvent object." }, { "code": null, "e": 4060, "s": 3997, "text": "WindowEvent(Window source, int id, int oldState, int newState)" }, { "code": null, "e": 4143, "s": 4060, "text": "Constructs a WindowEvent object with the specified previous and new window states." }, { "code": null, "e": 4195, "s": 4143, "text": "WindowEvent(Window source, int id, Window opposite)" }, { "code": null, "e": 4263, "s": 4195, "text": "Constructs a WindowEvent object with the specified opposite Window." }, { "code": null, "e": 4343, "s": 4263, "text": "WindowEvent(Window source, int id, Window opposite, int oldState, int newState)" }, { "code": null, "e": 4376, "s": 4343, "text": "Constructs a WindowEvent object." }, { "code": null, "e": 4394, "s": 4376, "text": "int getNewState()" }, { "code": null, "e": 4463, "s": 4394, "text": "For WINDOW_STATE_CHANGED events returns the new state of the window." }, { "code": null, "e": 4481, "s": 4463, "text": "int getOldState()" }, { "code": null, "e": 4555, "s": 4481, "text": "For WINDOW_STATE_CHANGED events returns the previous state of the window." }, { "code": null, "e": 4582, "s": 4555, "text": "Window getOppositeWindow()" }, { "code": null, "e": 4652, "s": 4582, "text": "Returns the other Window involved in this focus or activation change." }, { "code": null, "e": 4671, "s": 4652, "text": "Window getWindow()" }, { "code": null, "e": 4708, "s": 4671, "text": "Returns the originator of the event." }, { "code": null, "e": 4729, "s": 4708, "text": "String paramString()" }, { "code": null, "e": 4780, "s": 4729, "text": "Returns a parameter string identifying this event." } ]
p5.js | hide() Function
08 Jun, 2021 The hide() function is an inbuilt function which is used to hide the current element. Essentially display: none is used for this style.This function requires p5.dom library. So add the following line in the head section of the index.html file. javascript <script language="javascript" type="text/javascript" src="path/to/p5.dom.js"></script> Syntax: hide() Parameters: This function does not accepts any parameters.Below examples illustrate the hide() function in p5.js:Example 1: This example uses hide() function to hide the div element. javascript function setup() { // Create Canvas of given size var cvs = createCanvas(600, 250);} function draw() { // Set the background color background('green'); // Use createDiv() function to // create a div element var myDiv1 = createDiv('GeeksforGeeks'); // Set the position of div element myDiv1.position(170, 30); // Set the div size myDiv1.size(200, 100); // Set the font-size of text myDiv1.style('font-size', '36px'); // Use createDiv() function to // create a div element var myDiv = createDiv('A computer science portal for geeks'); // Set the position of div element myDiv.position(180, 80); // Set the div size myDiv.size(200, 100); // Set the font-size of text myDiv.style('font-size', '24px'); // Set the font-size of text myDiv.style('border', '1px solid black'); // Set the font-size of text myDiv.style('text-align', 'center'); // Set the font color myDiv.style('color', 'white'); // Hide the div element myDiv.hide(); } Output: Example 2: This example uses hide() and show() function to display the div element. javascript function setup() { // Create Canvas of given size var cvs = createCanvas(600, 250);} function draw() { // Set the background color background('green'); // Use createDiv() function to // create a div element var myDiv1 = createDiv('GeeksforGeeks'); // Set the position of div element myDiv1.position(170, 30); // Set the div size myDiv1.size(200, 100); // Set the font-size of text myDiv1.style('font-size', '36px'); // Use createDiv() function to // create a div element var myDiv = createDiv('A computer science portal for geeks'); // Set the position of div element myDiv.position(180, 80); // Set the div size myDiv.size(200, 100); // Set the font-size of text myDiv.style('font-size', '24px'); // Set the font-size of text myDiv.style('border', '1px solid black'); // Set the font-size of text myDiv.style('text-align', 'center'); // Set the font color myDiv.style('color', 'white'); // Hide the div element myDiv.hide(); // Show the div element myDiv.show();} Output: anikaseth98 JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2021" }, { "code": null, "e": 274, "s": 28, "text": "The hide() function is an inbuilt function which is used to hide the current element. Essentially display: none is used for this style.This function requires p5.dom library. So add the following line in the head section of the index.html file. " }, { "code": null, "e": 285, "s": 274, "text": "javascript" }, { "code": "<script language=\"javascript\" type=\"text/javascript\" src=\"path/to/p5.dom.js\"></script>", "e": 375, "s": 285, "text": null }, { "code": null, "e": 385, "s": 375, "text": "Syntax: " }, { "code": null, "e": 392, "s": 385, "text": "hide()" }, { "code": null, "e": 577, "s": 392, "text": "Parameters: This function does not accepts any parameters.Below examples illustrate the hide() function in p5.js:Example 1: This example uses hide() function to hide the div element. " }, { "code": null, "e": 588, "s": 577, "text": "javascript" }, { "code": "function setup() { // Create Canvas of given size var cvs = createCanvas(600, 250);} function draw() { // Set the background color background('green'); // Use createDiv() function to // create a div element var myDiv1 = createDiv('GeeksforGeeks'); // Set the position of div element myDiv1.position(170, 30); // Set the div size myDiv1.size(200, 100); // Set the font-size of text myDiv1.style('font-size', '36px'); // Use createDiv() function to // create a div element var myDiv = createDiv('A computer science portal for geeks'); // Set the position of div element myDiv.position(180, 80); // Set the div size myDiv.size(200, 100); // Set the font-size of text myDiv.style('font-size', '24px'); // Set the font-size of text myDiv.style('border', '1px solid black'); // Set the font-size of text myDiv.style('text-align', 'center'); // Set the font color myDiv.style('color', 'white'); // Hide the div element myDiv.hide(); }", "e": 1601, "s": 588, "text": null }, { "code": null, "e": 1611, "s": 1601, "text": "Output: " }, { "code": null, "e": 1697, "s": 1611, "text": "Example 2: This example uses hide() and show() function to display the div element. " }, { "code": null, "e": 1708, "s": 1697, "text": "javascript" }, { "code": "function setup() { // Create Canvas of given size var cvs = createCanvas(600, 250);} function draw() { // Set the background color background('green'); // Use createDiv() function to // create a div element var myDiv1 = createDiv('GeeksforGeeks'); // Set the position of div element myDiv1.position(170, 30); // Set the div size myDiv1.size(200, 100); // Set the font-size of text myDiv1.style('font-size', '36px'); // Use createDiv() function to // create a div element var myDiv = createDiv('A computer science portal for geeks'); // Set the position of div element myDiv.position(180, 80); // Set the div size myDiv.size(200, 100); // Set the font-size of text myDiv.style('font-size', '24px'); // Set the font-size of text myDiv.style('border', '1px solid black'); // Set the font-size of text myDiv.style('text-align', 'center'); // Set the font color myDiv.style('color', 'white'); // Hide the div element myDiv.hide(); // Show the div element myDiv.show();}", "e": 2761, "s": 1708, "text": null }, { "code": null, "e": 2771, "s": 2761, "text": "Output: " }, { "code": null, "e": 2785, "s": 2773, "text": "anikaseth98" }, { "code": null, "e": 2802, "s": 2785, "text": "JavaScript-p5.js" }, { "code": null, "e": 2813, "s": 2802, "text": "JavaScript" }, { "code": null, "e": 2830, "s": 2813, "text": "Web Technologies" } ]
Python List Comprehensions vs Generator Expressions
29 Jun, 2018 What is List Comprehension?It is an elegant way of defining and creating a list. List Comprehension allows us to create a list using for loop with lesser code. What normally takes 3-4 lines of code, can be compressed into just a single line. Example: # initializing the listlist = [] for i in range(11): if i % 2 == 0: list.append(i) # print elementsprint(list) Output: 0 2 4 6 8 10 Now, the same output can be derived from just a single line of code. list = [i for i in range(11) if i % 2 == 0]print(list) Output: 0 2 4 6 8 10 What are Generator Expressions?Generator Expressions are somewhat similar to list comprehensions, but the former doesn’t construct list object. Instead of creating a list and keeping the whole sequence in the memory, the generator generates the next element in demand.When a normal function with a return statement is called, it terminates whenever it gets a return statement. But a function with a yield statement saves the state of the function and can be picked up from the same state, next time the function is called.The Generator Expression allows us to create a generator without the yield keyword. Syntax Difference: Parenthesis are used in place of square brackets. # List Comprehensionlist_comprehension = [i for i in range(11) if i % 2 == 0] print(list_comprehension) Output: 0 2 4 6 8 10 # Generator Expressiongenerator_expression = (i for i in range(11) if i % 2 == 0) print(generator_expression) Output: <generator object at 0x000001452B1EEC50> In the above example, if we want to print the output for generator expressions, we can simply iterate it over generator object. for i in generator_expression: print(i, end=" ") Output: 0 2 4 6 8 10 So what’s the difference between Generator Expressions and List Comprehensions?The generator yields one item at a time and generates item only when in demand. Whereas, in a list comprehension, Python reserves memory for the whole list. Thus we can say that the generator expressions are memory efficient than the lists.We can see this in the example below. # import getsizeof from sys modulefrom sys import getsizeof comp = [i for i in range(10000)]gen = (i for i in range(10000)) #gives size for list comprehensionx = getsizeof(comp) print("x = ", x) #gives size for generator expressiony = getsizeof(gen) print("y = ", y) Output: x = 87624 y = 88 We just saw that generator expression are memory efficient. But, are they time efficient too? Let’s check this with an example. #List Comprehension: import timeit print(timeit.timeit('''list_com = [i for i in range(100) if i % 2 == 0]''', number=1000000)) Output: 8.118047142050102 #Generator Expression:import timeit print(timeit.timeit('''gen_exp = (i for i in range(100) if i % 2 == 0)''', number=1000000)) Output: 0.7548244756850693 There is a remarkable difference in the execution time. Thus, generator expressions are faster than list comprehension and hence time efficient. python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jun, 2018" }, { "code": null, "e": 296, "s": 54, "text": "What is List Comprehension?It is an elegant way of defining and creating a list. List Comprehension allows us to create a list using for loop with lesser code. What normally takes 3-4 lines of code, can be compressed into just a single line." }, { "code": null, "e": 305, "s": 296, "text": "Example:" }, { "code": "# initializing the listlist = [] for i in range(11): if i % 2 == 0: list.append(i) # print elementsprint(list)", "e": 428, "s": 305, "text": null }, { "code": null, "e": 436, "s": 428, "text": "Output:" }, { "code": null, "e": 450, "s": 436, "text": " 0 2 4 6 8 10" }, { "code": null, "e": 519, "s": 450, "text": "Now, the same output can be derived from just a single line of code." }, { "code": "list = [i for i in range(11) if i % 2 == 0]print(list)", "e": 574, "s": 519, "text": null }, { "code": null, "e": 582, "s": 574, "text": "Output:" }, { "code": null, "e": 596, "s": 582, "text": " 0 2 4 6 8 10" }, { "code": null, "e": 1202, "s": 596, "text": "What are Generator Expressions?Generator Expressions are somewhat similar to list comprehensions, but the former doesn’t construct list object. Instead of creating a list and keeping the whole sequence in the memory, the generator generates the next element in demand.When a normal function with a return statement is called, it terminates whenever it gets a return statement. But a function with a yield statement saves the state of the function and can be picked up from the same state, next time the function is called.The Generator Expression allows us to create a generator without the yield keyword." }, { "code": null, "e": 1271, "s": 1202, "text": "Syntax Difference: Parenthesis are used in place of square brackets." }, { "code": "# List Comprehensionlist_comprehension = [i for i in range(11) if i % 2 == 0] print(list_comprehension)", "e": 1376, "s": 1271, "text": null }, { "code": null, "e": 1384, "s": 1376, "text": "Output:" }, { "code": null, "e": 1398, "s": 1384, "text": " 0 2 4 6 8 10" }, { "code": "# Generator Expressiongenerator_expression = (i for i in range(11) if i % 2 == 0) print(generator_expression)", "e": 1509, "s": 1398, "text": null }, { "code": null, "e": 1517, "s": 1509, "text": "Output:" }, { "code": null, "e": 1560, "s": 1517, "text": "<generator object at 0x000001452B1EEC50>\n" }, { "code": null, "e": 1688, "s": 1560, "text": "In the above example, if we want to print the output for generator expressions, we can simply iterate it over generator object." }, { "code": "for i in generator_expression: print(i, end=\" \")", "e": 1740, "s": 1688, "text": null }, { "code": null, "e": 1748, "s": 1740, "text": "Output:" }, { "code": null, "e": 1761, "s": 1748, "text": "0 2 4 6 8 10" }, { "code": null, "e": 2118, "s": 1761, "text": "So what’s the difference between Generator Expressions and List Comprehensions?The generator yields one item at a time and generates item only when in demand. Whereas, in a list comprehension, Python reserves memory for the whole list. Thus we can say that the generator expressions are memory efficient than the lists.We can see this in the example below." }, { "code": "# import getsizeof from sys modulefrom sys import getsizeof comp = [i for i in range(10000)]gen = (i for i in range(10000)) #gives size for list comprehensionx = getsizeof(comp) print(\"x = \", x) #gives size for generator expressiony = getsizeof(gen) print(\"y = \", y)", "e": 2388, "s": 2118, "text": null }, { "code": null, "e": 2396, "s": 2388, "text": "Output:" }, { "code": null, "e": 2416, "s": 2396, "text": "x = 87624\ny = 88\n" }, { "code": null, "e": 2544, "s": 2416, "text": "We just saw that generator expression are memory efficient. But, are they time efficient too? Let’s check this with an example." }, { "code": "#List Comprehension: import timeit print(timeit.timeit('''list_com = [i for i in range(100) if i % 2 == 0]''', number=1000000))", "e": 2673, "s": 2544, "text": null }, { "code": null, "e": 2681, "s": 2673, "text": "Output:" }, { "code": null, "e": 2699, "s": 2681, "text": "8.118047142050102" }, { "code": "#Generator Expression:import timeit print(timeit.timeit('''gen_exp = (i for i in range(100) if i % 2 == 0)''', number=1000000))", "e": 2828, "s": 2699, "text": null }, { "code": null, "e": 2836, "s": 2828, "text": "Output:" }, { "code": null, "e": 2855, "s": 2836, "text": "0.7548244756850693" }, { "code": null, "e": 3000, "s": 2855, "text": "There is a remarkable difference in the execution time. Thus, generator expressions are faster than list comprehension and hence time efficient." }, { "code": null, "e": 3012, "s": 3000, "text": "python-list" }, { "code": null, "e": 3019, "s": 3012, "text": "Python" }, { "code": null, "e": 3031, "s": 3019, "text": "python-list" }, { "code": null, "e": 3129, "s": 3031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3161, "s": 3129, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3188, "s": 3161, "text": "Python Classes and Objects" }, { "code": null, "e": 3209, "s": 3188, "text": "Python OOPs Concepts" }, { "code": null, "e": 3232, "s": 3209, "text": "Introduction To PYTHON" }, { "code": null, "e": 3288, "s": 3232, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3319, "s": 3288, "text": "Python | os.path.join() method" }, { "code": null, "e": 3361, "s": 3319, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3403, "s": 3361, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3442, "s": 3403, "text": "Python | Get unique values from a list" } ]
Nested Classes in Java
12 Apr, 2022 In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and creates more readable and maintainable code. The scope of a nested class is bounded by the scope of its enclosing class. Thus in below example, class NestedClass does not exist independently of class OuterClass. A nested class has access to the members, including private members, of the class in which it is nested. The reverse is also true i.e., the enclosing class can access the members of the nested class. A nested class is also a member of its enclosing class. As a member of its enclosing class, a nested class can be declared private, public, protected, or package private(default). Nested classes are divided into two categories:static nested class : Nested classes that are declared static are called static nested classes.inner class : An inner class is a non-static nested class. static nested class : Nested classes that are declared static are called static nested classes.inner class : An inner class is a non-static nested class. static nested class : Nested classes that are declared static are called static nested classes. inner class : An inner class is a non-static nested class. Syntax: class OuterClass { ... class NestedClass { ... } } Static nested classes In the case of normal or regular inner classes, without an outer class object existing, there cannot be an inner class object. i.e., an object of the inner class is always strongly associated with an outer class object. But in the case of static nested class, Without an outer class object existing, there may be a static nested class object. i.e., an object of a static nested class is not strongly associated with the outer class object.As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.They are accessed using the enclosing class name. OuterClass.StaticNestedClass For example, to create an object for the static nested class, use this syntax: OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); // Java program to demonstrate accessing// a static nested class // outer classclass OuterClass{ // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private static int outer_private = 30; // static nested class static class StaticNestedClass { void display() { // can access static member of outer class System.out.println("outer_x = " + outer_x); // can access display private static member of outer class System.out.println("outer_private = " + outer_private); // The following statement will give compilation error // as static nested class cannot directly access non-static members // System.out.println("outer_y = " + outer_y); } }} // Driver classpublic class StaticNestedClassDemo{ public static void main(String[] args) { // accessing a static nested class OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); nestedObject.display(); }} Output: outer_x = 10 outer_private = 30 Inner classes To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass.InnerClass innerObject = outerObject.new InnerClass(); There are two special kinds of inner classes : Local inner classesAnonymous inner classes Local inner classes Anonymous inner classes // Java program to demonstrate accessing// a inner class // outer classclass OuterClass{ // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private int outer_private = 30; // inner class class InnerClass { void display() { // can access static member of outer class System.out.println("outer_x = " + outer_x); // can also access non-static member of outer class System.out.println("outer_y = " + outer_y); // can also access a private member of the outer class System.out.println("outer_private = " + outer_private); } }} // Driver classpublic class InnerClassDemo{ public static void main(String[] args) { // accessing an inner class OuterClass outerObject = new OuterClass(); OuterClass.InnerClass innerObject = outerObject.new InnerClass(); innerObject.display(); }} Output: outer_x = 10 outer_y = 20 outer_private = 30 Comparison between normal or regular class and static nested class gauravmoney26 somanshreddy rayyash08 bhuwanesh codewithkush Java-Class and Object Java Java-Class and Object Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Apr, 2022" }, { "code": null, "e": 329, "s": 52, "text": "In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and creates more readable and maintainable code." }, { "code": null, "e": 496, "s": 329, "text": "The scope of a nested class is bounded by the scope of its enclosing class. Thus in below example, class NestedClass does not exist independently of class OuterClass." }, { "code": null, "e": 696, "s": 496, "text": "A nested class has access to the members, including private members, of the class in which it is nested. The reverse is also true i.e., the enclosing class can access the members of the nested class." }, { "code": null, "e": 752, "s": 696, "text": "A nested class is also a member of its enclosing class." }, { "code": null, "e": 876, "s": 752, "text": "As a member of its enclosing class, a nested class can be declared private, public, protected, or package private(default)." }, { "code": null, "e": 1077, "s": 876, "text": "Nested classes are divided into two categories:static nested class : Nested classes that are declared static are called static nested classes.inner class : An inner class is a non-static nested class." }, { "code": null, "e": 1231, "s": 1077, "text": "static nested class : Nested classes that are declared static are called static nested classes.inner class : An inner class is a non-static nested class." }, { "code": null, "e": 1327, "s": 1231, "text": "static nested class : Nested classes that are declared static are called static nested classes." }, { "code": null, "e": 1386, "s": 1327, "text": "inner class : An inner class is a non-static nested class." }, { "code": null, "e": 1394, "s": 1386, "text": "Syntax:" }, { "code": null, "e": 1465, "s": 1394, "text": "class OuterClass\n{\n...\n class NestedClass\n {\n ...\n }\n}" }, { "code": null, "e": 1487, "s": 1465, "text": "Static nested classes" }, { "code": null, "e": 2260, "s": 1487, "text": "In the case of normal or regular inner classes, without an outer class object existing, there cannot be an inner class object. i.e., an object of the inner class is always strongly associated with an outer class object. But in the case of static nested class, Without an outer class object existing, there may be a static nested class object. i.e., an object of a static nested class is not strongly associated with the outer class object.As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.They are accessed using the enclosing class name." }, { "code": null, "e": 2290, "s": 2260, "text": "OuterClass.StaticNestedClass\n" }, { "code": null, "e": 2369, "s": 2290, "text": "For example, to create an object for the static nested class, use this syntax:" }, { "code": null, "e": 2455, "s": 2369, "text": "OuterClass.StaticNestedClass nestedObject =\n new OuterClass.StaticNestedClass();\n" }, { "code": "// Java program to demonstrate accessing// a static nested class // outer classclass OuterClass{ // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private static int outer_private = 30; // static nested class static class StaticNestedClass { void display() { // can access static member of outer class System.out.println(\"outer_x = \" + outer_x); // can access display private static member of outer class System.out.println(\"outer_private = \" + outer_private); // The following statement will give compilation error // as static nested class cannot directly access non-static members // System.out.println(\"outer_y = \" + outer_y); } }} // Driver classpublic class StaticNestedClassDemo{ public static void main(String[] args) { // accessing a static nested class OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); nestedObject.display(); }}", "e": 3610, "s": 2455, "text": null }, { "code": null, "e": 3618, "s": 3610, "text": "Output:" }, { "code": null, "e": 3651, "s": 3618, "text": "outer_x = 10\nouter_private = 30\n" }, { "code": null, "e": 3665, "s": 3651, "text": "Inner classes" }, { "code": null, "e": 3812, "s": 3665, "text": "To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:" }, { "code": null, "e": 3879, "s": 3812, "text": "OuterClass.InnerClass innerObject = outerObject.new InnerClass();\n" }, { "code": null, "e": 3926, "s": 3879, "text": "There are two special kinds of inner classes :" }, { "code": null, "e": 3969, "s": 3926, "text": "Local inner classesAnonymous inner classes" }, { "code": null, "e": 3989, "s": 3969, "text": "Local inner classes" }, { "code": null, "e": 4013, "s": 3989, "text": "Anonymous inner classes" }, { "code": "// Java program to demonstrate accessing// a inner class // outer classclass OuterClass{ // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private int outer_private = 30; // inner class class InnerClass { void display() { // can access static member of outer class System.out.println(\"outer_x = \" + outer_x); // can also access non-static member of outer class System.out.println(\"outer_y = \" + outer_y); // can also access a private member of the outer class System.out.println(\"outer_private = \" + outer_private); } }} // Driver classpublic class InnerClassDemo{ public static void main(String[] args) { // accessing an inner class OuterClass outerObject = new OuterClass(); OuterClass.InnerClass innerObject = outerObject.new InnerClass(); innerObject.display(); }}", "e": 5063, "s": 4013, "text": null }, { "code": null, "e": 5071, "s": 5063, "text": "Output:" }, { "code": null, "e": 5117, "s": 5071, "text": "outer_x = 10\nouter_y = 20\nouter_private = 30\n" }, { "code": null, "e": 5184, "s": 5117, "text": "Comparison between normal or regular class and static nested class" }, { "code": null, "e": 5198, "s": 5184, "text": "gauravmoney26" }, { "code": null, "e": 5211, "s": 5198, "text": "somanshreddy" }, { "code": null, "e": 5221, "s": 5211, "text": "rayyash08" }, { "code": null, "e": 5231, "s": 5221, "text": "bhuwanesh" }, { "code": null, "e": 5244, "s": 5231, "text": "codewithkush" }, { "code": null, "e": 5266, "s": 5244, "text": "Java-Class and Object" }, { "code": null, "e": 5271, "s": 5266, "text": "Java" }, { "code": null, "e": 5293, "s": 5271, "text": "Java-Class and Object" }, { "code": null, "e": 5298, "s": 5293, "text": "Java" }, { "code": null, "e": 5396, "s": 5298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5411, "s": 5396, "text": "Arrays in Java" }, { "code": null, "e": 5455, "s": 5411, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5491, "s": 5455, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5542, "s": 5491, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 5567, "s": 5542, "text": "Reverse a string in Java" }, { "code": null, "e": 5589, "s": 5567, "text": "For-each loop in Java" }, { "code": null, "e": 5620, "s": 5589, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5639, "s": 5620, "text": "Interfaces in Java" }, { "code": null, "e": 5669, "s": 5639, "text": "HashMap in Java with Examples" } ]
What is Box plot and the condition of outliers?
21 Apr, 2020 Box plot is a data visualization plotting function. It shows the min, max, median, first quartile, and third quartile. All of the things will be explained briefly. All of the property of box plot can be accessed by dataframe.column_name.describe() function. Here is a well distributed data-set. data = [0, 1, 2, 3, 4, 5, 6] df = pd.DataFrame(data, columns = ['Num']) df Output: Now plotting the data frame using box plot, plt.figure(figsize = (10, 7)) df.boxplot() The maximum and the minimum is the max and min value of the data-set. 50 percentile is the median of the data-set. The first quartile is the median of the data between the min to 50% and the third quartile is the median of the data between 50% to max. The outliers will be the values that are out of the (1.5*interquartile range) from the 25 or 75 percentile. Use the median to divide the ordered data set into two halves.1) If there is an odd number of data points in the original ordered data set, do not include the median (the central value in the ordered list) in either half.2) If there is an even number of data points in the original ordered data set, split this data set exactly in half. The lower quartile value is the median of the lower half of the data. The upper quartile value is the median of the upper half of the data. An extreme value is considered to be an outlier if it is at least 1.5 interquartile ranges below the first quartile, or at least 1.5 interquartile ranges above the third quartile. Let us see different cases of box plots with different examples and let’s try to understand each one of them. Now for the data = [0, 1, 2, 3, 6, 6, 6]Here the median of the data is 3, min is 0 and max is 6. The first quartile is 1.5 but after 50% to max values, all of the data is 6. So the third quartile and the max values are the same. Now for the data = [0, 1, 2, 3, 6, 6, 6] Here the median of the data is 3, min is 0 and max is 6. The first quartile is 1.5 but after 50% to max values, all of the data is 6. So the third quartile and the max values are the same. For the data = [0, 1, 2, 3, 4, 5, 9] Here the median is 3. For the third quartile, the values are 4, 5 and 9. So the third quartile is 5 and the max value is 9. For the data = [0, 1, 2, 3, 4, 5, 9] Here the median is 3. For the third quartile, the values are 4, 5 and 9. So the third quartile is 5 and the max value is 9. For the data = [0, 1, 2, 3, 4, 5, 10]Unlike the previous one, the max value is 5 because the third quartile is 4.5 and the interquartile range is (4.5-1.5)=>3. So, 1.5*3 is 4.5 and third quartile(4.5)+4.5=>9. So 10 is larger than the limit 9, thus it becomes an outlier. For the data = [0, 1, 2, 3, 4, 5, 10] Unlike the previous one, the max value is 5 because the third quartile is 4.5 and the interquartile range is (4.5-1.5)=>3. So, 1.5*3 is 4.5 and third quartile(4.5)+4.5=>9. So 10 is larger than the limit 9, thus it becomes an outlier. The box plot seem useful to detect outliers but it has several other uses too. Box plots take up less space and are therefore particularly useful for comparing distributions between several groups or sets of data. It is a direct representation of the Probability Density Function which indicates the distribution of data. Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Factory method design pattern in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 286, "s": 28, "text": "Box plot is a data visualization plotting function. It shows the min, max, median, first quartile, and third quartile. All of the things will be explained briefly. All of the property of box plot can be accessed by dataframe.column_name.describe() function." }, { "code": null, "e": 323, "s": 286, "text": "Here is a well distributed data-set." }, { "code": "data = [0, 1, 2, 3, 4, 5, 6] df = pd.DataFrame(data, columns = ['Num']) df", "e": 399, "s": 323, "text": null }, { "code": null, "e": 407, "s": 399, "text": "Output:" }, { "code": null, "e": 451, "s": 407, "text": "Now plotting the data frame using box plot," }, { "code": "plt.figure(figsize = (10, 7)) df.boxplot() ", "e": 497, "s": 451, "text": null }, { "code": null, "e": 857, "s": 497, "text": "The maximum and the minimum is the max and min value of the data-set. 50 percentile is the median of the data-set. The first quartile is the median of the data between the min to 50% and the third quartile is the median of the data between 50% to max. The outliers will be the values that are out of the (1.5*interquartile range) from the 25 or 75 percentile." }, { "code": null, "e": 1194, "s": 857, "text": "Use the median to divide the ordered data set into two halves.1) If there is an odd number of data points in the original ordered data set, do not include the median (the central value in the ordered list) in either half.2) If there is an even number of data points in the original ordered data set, split this data set exactly in half." }, { "code": null, "e": 1334, "s": 1194, "text": "The lower quartile value is the median of the lower half of the data. The upper quartile value is the median of the upper half of the data." }, { "code": null, "e": 1514, "s": 1334, "text": "An extreme value is considered to be an outlier if it is at least 1.5 interquartile ranges below the first quartile, or at least 1.5 interquartile ranges above the third quartile." }, { "code": null, "e": 1624, "s": 1514, "text": "Let us see different cases of box plots with different examples and let’s try to understand each one of them." }, { "code": null, "e": 1853, "s": 1624, "text": "Now for the data = [0, 1, 2, 3, 6, 6, 6]Here the median of the data is 3, min is 0 and max is 6. The first quartile is 1.5 but after 50% to max values, all of the data is 6. So the third quartile and the max values are the same." }, { "code": null, "e": 1894, "s": 1853, "text": "Now for the data = [0, 1, 2, 3, 6, 6, 6]" }, { "code": null, "e": 2083, "s": 1894, "text": "Here the median of the data is 3, min is 0 and max is 6. The first quartile is 1.5 but after 50% to max values, all of the data is 6. So the third quartile and the max values are the same." }, { "code": null, "e": 2244, "s": 2083, "text": "For the data = [0, 1, 2, 3, 4, 5, 9] Here the median is 3. For the third quartile, the values are 4, 5 and 9. So the third quartile is 5 and the max value is 9." }, { "code": null, "e": 2282, "s": 2244, "text": "For the data = [0, 1, 2, 3, 4, 5, 9] " }, { "code": null, "e": 2406, "s": 2282, "text": "Here the median is 3. For the third quartile, the values are 4, 5 and 9. So the third quartile is 5 and the max value is 9." }, { "code": null, "e": 2677, "s": 2406, "text": "For the data = [0, 1, 2, 3, 4, 5, 10]Unlike the previous one, the max value is 5 because the third quartile is 4.5 and the interquartile range is (4.5-1.5)=>3. So, 1.5*3 is 4.5 and third quartile(4.5)+4.5=>9. So 10 is larger than the limit 9, thus it becomes an outlier." }, { "code": null, "e": 2715, "s": 2677, "text": "For the data = [0, 1, 2, 3, 4, 5, 10]" }, { "code": null, "e": 2949, "s": 2715, "text": "Unlike the previous one, the max value is 5 because the third quartile is 4.5 and the interquartile range is (4.5-1.5)=>3. So, 1.5*3 is 4.5 and third quartile(4.5)+4.5=>9. So 10 is larger than the limit 9, thus it becomes an outlier." }, { "code": null, "e": 3271, "s": 2949, "text": "The box plot seem useful to detect outliers but it has several other uses too. Box plots take up less space and are therefore particularly useful for comparing distributions between several groups or sets of data. It is a direct representation of the Probability Density Function which indicates the distribution of data." }, { "code": null, "e": 3289, "s": 3271, "text": "Python-matplotlib" }, { "code": null, "e": 3296, "s": 3289, "text": "Python" }, { "code": null, "e": 3312, "s": 3296, "text": "Write From Home" }, { "code": null, "e": 3410, "s": 3312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3428, "s": 3410, "text": "Python Dictionary" }, { "code": null, "e": 3470, "s": 3428, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3492, "s": 3470, "text": "Enumerate() in Python" }, { "code": null, "e": 3527, "s": 3492, "text": "Read a file line by line in Python" }, { "code": null, "e": 3553, "s": 3527, "text": "Python String | replace()" }, { "code": null, "e": 3589, "s": 3553, "text": "Convert integer to string in Python" }, { "code": null, "e": 3625, "s": 3589, "text": "Convert string to integer in Python" }, { "code": null, "e": 3686, "s": 3625, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 3702, "s": 3686, "text": "Python infinity" } ]
How to count the frequency of unique values in NumPy array?
02 Sep, 2020 Let’s see How to count the frequency of unique values in NumPy array. Python’s numpy library provides a numpy.unique() function to find the unique elements and it’s corresponding frequency in a numpy array. Syntax: numpy.unique(arr, return_counts=False) Return: Sorted unique elements of an array with their corresponding frequency counts NumPy array. Now, Let’s see examples: Example 1: Python3 # import libraryimport numpy as np ini_array = np.array([10, 20, 5, 10, 8, 20, 8, 9]) # Get a tuple of unique values # and their frequency in# numpy arrayunique, frequency = np.unique(ini_array, return_counts = True)# print unique values arrayprint("Unique Values:", unique) # print frequency arrayprint("Frequency Values:", frequency) Output: Unique Values: [ 5 8 9 10 20] Frequency Values: [1 2 1 2 2] Example 2: Python3 # import libraryimport numpy as np # create a 1d-arrayini_array = np.array([10, 20, 5, 10, 8, 20, 8, 9]) # Get a tuple of unique values # amnd their frequency # in numpy arrayunique, frequency = np.unique(ini_array, return_counts = True) # convert both into one numpy arraycount = np.asarray((unique, frequency )) print("The values and their frequency are:\n", count) Output: The values and their frequency are: [[ 5 8 9 10 20] [ 1 2 1 2 2]] Example 3: Python3 # import libraryimport numpy as np # create a 1d-arrayini_array = np.array([10, 20, 5, 10, 8, 20, 8, 9]) # Get a tuple of unique values # and their frequency in# numpy arrayunique, frequency = np.unique(ini_array, return_counts = True) # convert both into one numpy array # and then transpose itcount = np.asarray((unique,frequency )).T print("The values and their frequency are in transpose form:\n", count) Output: The values and their frequency are in transpose form: [[ 5 1] [ 8 2] [ 9 1] [10 2] [20 2]] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 235, "s": 28, "text": "Let’s see How to count the frequency of unique values in NumPy array. Python’s numpy library provides a numpy.unique() function to find the unique elements and it’s corresponding frequency in a numpy array." }, { "code": null, "e": 282, "s": 235, "text": "Syntax: numpy.unique(arr, return_counts=False)" }, { "code": null, "e": 380, "s": 282, "text": "Return: Sorted unique elements of an array with their corresponding frequency counts NumPy array." }, { "code": null, "e": 405, "s": 380, "text": "Now, Let’s see examples:" }, { "code": null, "e": 416, "s": 405, "text": "Example 1:" }, { "code": null, "e": 424, "s": 416, "text": "Python3" }, { "code": "# import libraryimport numpy as np ini_array = np.array([10, 20, 5, 10, 8, 20, 8, 9]) # Get a tuple of unique values # and their frequency in# numpy arrayunique, frequency = np.unique(ini_array, return_counts = True)# print unique values arrayprint(\"Unique Values:\", unique) # print frequency arrayprint(\"Frequency Values:\", frequency)", "e": 846, "s": 424, "text": null }, { "code": null, "e": 854, "s": 846, "text": "Output:" }, { "code": null, "e": 917, "s": 854, "text": "Unique Values: [ 5 8 9 10 20]\nFrequency Values: [1 2 1 2 2]\n" }, { "code": null, "e": 928, "s": 917, "text": "Example 2:" }, { "code": null, "e": 936, "s": 928, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create a 1d-arrayini_array = np.array([10, 20, 5, 10, 8, 20, 8, 9]) # Get a tuple of unique values # amnd their frequency # in numpy arrayunique, frequency = np.unique(ini_array, return_counts = True) # convert both into one numpy arraycount = np.asarray((unique, frequency )) print(\"The values and their frequency are:\\n\", count)", "e": 1380, "s": 936, "text": null }, { "code": null, "e": 1388, "s": 1380, "text": "Output:" }, { "code": null, "e": 1460, "s": 1388, "text": "The values and their frequency are:\n[[ 5 8 9 10 20]\n[ 1 2 1 2 2]]" }, { "code": null, "e": 1471, "s": 1460, "text": "Example 3:" }, { "code": null, "e": 1479, "s": 1471, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create a 1d-arrayini_array = np.array([10, 20, 5, 10, 8, 20, 8, 9]) # Get a tuple of unique values # and their frequency in# numpy arrayunique, frequency = np.unique(ini_array, return_counts = True) # convert both into one numpy array # and then transpose itcount = np.asarray((unique,frequency )).T print(\"The values and their frequency are in transpose form:\\n\", count)", "e": 1969, "s": 1479, "text": null }, { "code": null, "e": 1977, "s": 1969, "text": "Output:" }, { "code": null, "e": 2073, "s": 1977, "text": "The values and their frequency are in transpose form:\n[[ 5 1]\n[ 8 2]\n[ 9 1]\n[10 2]\n[20 2]]" }, { "code": null, "e": 2102, "s": 2073, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 2115, "s": 2102, "text": "Python-numpy" }, { "code": null, "e": 2122, "s": 2115, "text": "Python" } ]
GAN by Example using Keras on Tensorflow Backend | by Rowel Atienza | Towards Data Science
Generative Adversarial Networks (GAN) is one of the most promising recent developments in Deep Learning. GAN, introduced by Ian Goodfellow in 2014, attacks the problem of unsupervised learning by training two deep networks, called Generator and Discriminator, that compete and cooperate with each other. In the course of training, both networks eventually learn how to perform their tasks. GAN is almost always explained like the case of a counterfeiter (Generative) and the police (Discriminator). Initially, the counterfeiter will show the police a fake money. The police says it is fake. The police gives feedback to the counterfeiter why the money is fake. The counterfeiter attempts to make a new fake money based on the feedback it received. The police says the money is still fake and offers a new set of feedback. The counterfeiter attempts to make a new fake money based on the latest feedback. The cycle continues indefinitely until the police is fooled by the fake money because it looks real. While the idea of GAN is simple in theory, it is very difficult to build a model that works. In GAN, there are two deep networks coupled together making back propagation of gradients twice as challenging. Deep Convolutional GAN (DCGAN) is one of the models that demonstrated how to build a practical GAN that is able to learn by itself how to synthesize new images. In this article, we discuss how a working DCGAN can be built using Keras 2.0 on Tensorflow 1.0 backend in less than 200 lines of code. We will train a DCGAN to learn how to write handwritten digits, the MNIST way. A discriminator that tells how real an image is, is basically a deep Convolutional Neural Network (CNN) as shown in Figure 1. For MNIST Dataset, the input is an image (28 pixel x 28 pixel x 1 channel). The sigmoid output is a scalar value of the probability of how real the image is (0.0 is certainly fake, 1.0 is certainly real, anything in between is a gray area). The difference from a typical CNN is the absence of max-pooling in between layers. Instead, a strided convolution is used for downsampling. The activation function used in each CNN layer is a leaky ReLU. A dropout between 0.4 and 0.7 between layers prevent over fitting and memorization. Listing 1 shows the implementation in Keras. self.D = Sequential()depth = 64dropout = 0.4# In: 28 x 28 x 1, depth = 1# Out: 14 x 14 x 1, depth=64input_shape = (self.img_rows, self.img_cols, self.channel)self.D.add(Conv2D(depth*1, 5, strides=2, input_shape=input_shape,\padding='same', activation=LeakyReLU(alpha=0.2)))self.D.add(Dropout(dropout))self.D.add(Conv2D(depth*2, 5, strides=2, padding='same',\activation=LeakyReLU(alpha=0.2)))self.D.add(Dropout(dropout))self.D.add(Conv2D(depth*4, 5, strides=2, padding='same',\activation=LeakyReLU(alpha=0.2)))self.D.add(Dropout(dropout))self.D.add(Conv2D(depth*8, 5, strides=1, padding='same',\activation=LeakyReLU(alpha=0.2)))self.D.add(Dropout(dropout))# Out: 1-dim probabilityself.D.add(Flatten())self.D.add(Dense(1))self.D.add(Activation('sigmoid'))self.D.summary() Listing 1. Keras code for the Discriminator in Figure 1. The generator synthesizes fake images. In Figure 2, the fake image is generated from a 100-dimensional noise (uniform distribution between -1.0 to 1.0) using the inverse of convolution, called transposed convolution. Instead of fractionally-strided convolution as suggested in DCGAN, upsampling between the first three layers is used since it synthesizes more realistic handwriting images. In between layers, batch normalization stabilizes learning. The activation function after each layer is a ReLU. The output of the sigmoid at the last layer produces the fake image. Dropout of between 0.3 and 0.5 at the first layer prevents overfitting. Listing 2 shows the implementation in Keras. self.G = Sequential()dropout = 0.4depth = 64+64+64+64dim = 7# In: 100# Out: dim x dim x depthself.G.add(Dense(dim*dim*depth, input_dim=100))self.G.add(BatchNormalization(momentum=0.9))self.G.add(Activation('relu'))self.G.add(Reshape((dim, dim, depth)))self.G.add(Dropout(dropout))# In: dim x dim x depth# Out: 2*dim x 2*dim x depth/2self.G.add(UpSampling2D())self.G.add(Conv2DTranspose(int(depth/2), 5, padding='same'))self.G.add(BatchNormalization(momentum=0.9))self.G.add(Activation('relu'))self.G.add(UpSampling2D())self.G.add(Conv2DTranspose(int(depth/4), 5, padding='same'))self.G.add(BatchNormalization(momentum=0.9))self.G.add(Activation('relu'))self.G.add(Conv2DTranspose(int(depth/8), 5, padding='same'))self.G.add(BatchNormalization(momentum=0.9))self.G.add(Activation('relu'))# Out: 28 x 28 x 1 grayscale image [0.0,1.0] per pixself.G.add(Conv2DTranspose(1, 5, padding='same'))self.G.add(Activation('sigmoid'))self.G.summary()return self.G Listing 2. Keras code for the generator in Figure 2. So far, there are no models yet. It is time to build the models for training. We need two models: 1) Discriminator Model (the police) and 2) Adversarial Model or Generator-Discriminator (the counterfeiter learning from the police). Listing 3 shows the Keras code for the Discriminator Model. It is the Discriminator described above with the loss function defined for training. Since the output of the Discriminator is sigmoid, we use binary cross entropy for the loss. RMSProp as optimizer generates more realistic fake images compared to Adam for this case. Learning rate is 0.0008. Weight decay and clip value stabilize learning during the latter part of the training. You have to adjust the decay if you adjust the learning rate. optimizer = RMSprop(lr=0.0008, clipvalue=1.0, decay=6e-8)self.DM = Sequential()self.DM.add(self.discriminator())self.DM.compile(loss='binary_crossentropy', optimizer=optimizer,\metrics=['accuracy']) Listing 3. Discriminator Model implemented in Keras. The adversarial model is just the generator-discriminator stacked together as shown in Figure 3. The Generator part is trying to fool the Discriminator and learning from its feedback at the same time. Listing 4 shows the implementation using Keras code. The training parameters are the same as in the Discriminator model except for a reduced learning rate and corresponding weight decay. optimizer = RMSprop(lr=0.0004, clipvalue=1.0, decay=3e-8)self.AM = Sequential()self.AM.add(self.generator())self.AM.add(self.discriminator())self.AM.compile(loss='binary_crossentropy', optimizer=optimizer,\metrics=['accuracy']) Listing 4. Adversarial Model as shown in Figure 3 implemented in Keras. Training is the hardest part. We determine first if Discriminator model is correct by training it alone with real and fake images. Afterwards, the Discriminator and Adversarial models are trained one after the other. Figure 4 shows the Discriminator Model while Figure 3 shows the Adversarial Model during training. Listing 5 shows the training code in Keras. images_train = self.x_train[np.random.randint(0,self.x_train.shape[0], size=batch_size), :, :, :]noise = np.random.uniform(-1.0, 1.0, size=[batch_size, 100])images_fake = self.generator.predict(noise)x = np.concatenate((images_train, images_fake))y = np.ones([2*batch_size, 1])y[batch_size:, :] = 0d_loss = self.discriminator.train_on_batch(x, y)y = np.ones([batch_size, 1])noise = np.random.uniform(-1.0, 1.0, size=[batch_size, 100])a_loss = self.adversarial.train_on_batch(noise, y) Listing 5. Sequential training of Discriminator Model and Adversarial Model. Training steps above 1000 generates respectable outputs. Training GAN models requires a lot of patience due to its depth. Here are some pointers: Problem: generated images look like noise. Solution: use dropout on both Discriminator and Generator. Low dropout values (0.3 to 0.6) generate more realistic images.Problem: Discriminator loss converges rapidly to zero thus preventing the Generator from learning. Solution: Do not pre-train the Discriminator. Instead make its learning rate bigger than the Adversarial model learning rate. Use a different training noise sample for the Generator.Problem: generator images still look like noise. Solution: check if the activation, batch normalization and dropout are applied in the correct sequence.Problem: figuring out the correct training/model parameters. Solution: start with some known working values from published papers and codes and adjust one parameter at a time. Before training for 2000 or more steps, observe the effect of parameter value adjustment at about 500 or 1000 steps. Problem: generated images look like noise. Solution: use dropout on both Discriminator and Generator. Low dropout values (0.3 to 0.6) generate more realistic images. Problem: Discriminator loss converges rapidly to zero thus preventing the Generator from learning. Solution: Do not pre-train the Discriminator. Instead make its learning rate bigger than the Adversarial model learning rate. Use a different training noise sample for the Generator. Problem: generator images still look like noise. Solution: check if the activation, batch normalization and dropout are applied in the correct sequence. Problem: figuring out the correct training/model parameters. Solution: start with some known working values from published papers and codes and adjust one parameter at a time. Before training for 2000 or more steps, observe the effect of parameter value adjustment at about 500 or 1000 steps. Figure 5 shows the evolution of output images during training. Observing Figure 5 is fascinating. The GAN is learning how to write handwritten digits on its own! The Keras complete code can be found here.
[ { "code": null, "e": 562, "s": 172, "text": "Generative Adversarial Networks (GAN) is one of the most promising recent developments in Deep Learning. GAN, introduced by Ian Goodfellow in 2014, attacks the problem of unsupervised learning by training two deep networks, called Generator and Discriminator, that compete and cooperate with each other. In the course of training, both networks eventually learn how to perform their tasks." }, { "code": null, "e": 1177, "s": 562, "text": "GAN is almost always explained like the case of a counterfeiter (Generative) and the police (Discriminator). Initially, the counterfeiter will show the police a fake money. The police says it is fake. The police gives feedback to the counterfeiter why the money is fake. The counterfeiter attempts to make a new fake money based on the feedback it received. The police says the money is still fake and offers a new set of feedback. The counterfeiter attempts to make a new fake money based on the latest feedback. The cycle continues indefinitely until the police is fooled by the fake money because it looks real." }, { "code": null, "e": 1543, "s": 1177, "text": "While the idea of GAN is simple in theory, it is very difficult to build a model that works. In GAN, there are two deep networks coupled together making back propagation of gradients twice as challenging. Deep Convolutional GAN (DCGAN) is one of the models that demonstrated how to build a practical GAN that is able to learn by itself how to synthesize new images." }, { "code": null, "e": 1757, "s": 1543, "text": "In this article, we discuss how a working DCGAN can be built using Keras 2.0 on Tensorflow 1.0 backend in less than 200 lines of code. We will train a DCGAN to learn how to write handwritten digits, the MNIST way." }, { "code": null, "e": 2457, "s": 1757, "text": "A discriminator that tells how real an image is, is basically a deep Convolutional Neural Network (CNN) as shown in Figure 1. For MNIST Dataset, the input is an image (28 pixel x 28 pixel x 1 channel). The sigmoid output is a scalar value of the probability of how real the image is (0.0 is certainly fake, 1.0 is certainly real, anything in between is a gray area). The difference from a typical CNN is the absence of max-pooling in between layers. Instead, a strided convolution is used for downsampling. The activation function used in each CNN layer is a leaky ReLU. A dropout between 0.4 and 0.7 between layers prevent over fitting and memorization. Listing 1 shows the implementation in Keras." }, { "code": null, "e": 3227, "s": 2457, "text": "self.D = Sequential()depth = 64dropout = 0.4# In: 28 x 28 x 1, depth = 1# Out: 14 x 14 x 1, depth=64input_shape = (self.img_rows, self.img_cols, self.channel)self.D.add(Conv2D(depth*1, 5, strides=2, input_shape=input_shape,\\padding='same', activation=LeakyReLU(alpha=0.2)))self.D.add(Dropout(dropout))self.D.add(Conv2D(depth*2, 5, strides=2, padding='same',\\activation=LeakyReLU(alpha=0.2)))self.D.add(Dropout(dropout))self.D.add(Conv2D(depth*4, 5, strides=2, padding='same',\\activation=LeakyReLU(alpha=0.2)))self.D.add(Dropout(dropout))self.D.add(Conv2D(depth*8, 5, strides=1, padding='same',\\activation=LeakyReLU(alpha=0.2)))self.D.add(Dropout(dropout))# Out: 1-dim probabilityself.D.add(Flatten())self.D.add(Dense(1))self.D.add(Activation('sigmoid'))self.D.summary()" }, { "code": null, "e": 3284, "s": 3227, "text": "Listing 1. Keras code for the Discriminator in Figure 1." }, { "code": null, "e": 3972, "s": 3284, "text": "The generator synthesizes fake images. In Figure 2, the fake image is generated from a 100-dimensional noise (uniform distribution between -1.0 to 1.0) using the inverse of convolution, called transposed convolution. Instead of fractionally-strided convolution as suggested in DCGAN, upsampling between the first three layers is used since it synthesizes more realistic handwriting images. In between layers, batch normalization stabilizes learning. The activation function after each layer is a ReLU. The output of the sigmoid at the last layer produces the fake image. Dropout of between 0.3 and 0.5 at the first layer prevents overfitting. Listing 2 shows the implementation in Keras." }, { "code": null, "e": 4923, "s": 3972, "text": "self.G = Sequential()dropout = 0.4depth = 64+64+64+64dim = 7# In: 100# Out: dim x dim x depthself.G.add(Dense(dim*dim*depth, input_dim=100))self.G.add(BatchNormalization(momentum=0.9))self.G.add(Activation('relu'))self.G.add(Reshape((dim, dim, depth)))self.G.add(Dropout(dropout))# In: dim x dim x depth# Out: 2*dim x 2*dim x depth/2self.G.add(UpSampling2D())self.G.add(Conv2DTranspose(int(depth/2), 5, padding='same'))self.G.add(BatchNormalization(momentum=0.9))self.G.add(Activation('relu'))self.G.add(UpSampling2D())self.G.add(Conv2DTranspose(int(depth/4), 5, padding='same'))self.G.add(BatchNormalization(momentum=0.9))self.G.add(Activation('relu'))self.G.add(Conv2DTranspose(int(depth/8), 5, padding='same'))self.G.add(BatchNormalization(momentum=0.9))self.G.add(Activation('relu'))# Out: 28 x 28 x 1 grayscale image [0.0,1.0] per pixself.G.add(Conv2DTranspose(1, 5, padding='same'))self.G.add(Activation('sigmoid'))self.G.summary()return self.G" }, { "code": null, "e": 4976, "s": 4923, "text": "Listing 2. Keras code for the generator in Figure 2." }, { "code": null, "e": 5208, "s": 4976, "text": "So far, there are no models yet. It is time to build the models for training. We need two models: 1) Discriminator Model (the police) and 2) Adversarial Model or Generator-Discriminator (the counterfeiter learning from the police)." }, { "code": null, "e": 5709, "s": 5208, "text": "Listing 3 shows the Keras code for the Discriminator Model. It is the Discriminator described above with the loss function defined for training. Since the output of the Discriminator is sigmoid, we use binary cross entropy for the loss. RMSProp as optimizer generates more realistic fake images compared to Adam for this case. Learning rate is 0.0008. Weight decay and clip value stabilize learning during the latter part of the training. You have to adjust the decay if you adjust the learning rate." }, { "code": null, "e": 5908, "s": 5709, "text": "optimizer = RMSprop(lr=0.0008, clipvalue=1.0, decay=6e-8)self.DM = Sequential()self.DM.add(self.discriminator())self.DM.compile(loss='binary_crossentropy', optimizer=optimizer,\\metrics=['accuracy'])" }, { "code": null, "e": 5961, "s": 5908, "text": "Listing 3. Discriminator Model implemented in Keras." }, { "code": null, "e": 6349, "s": 5961, "text": "The adversarial model is just the generator-discriminator stacked together as shown in Figure 3. The Generator part is trying to fool the Discriminator and learning from its feedback at the same time. Listing 4 shows the implementation using Keras code. The training parameters are the same as in the Discriminator model except for a reduced learning rate and corresponding weight decay." }, { "code": null, "e": 6577, "s": 6349, "text": "optimizer = RMSprop(lr=0.0004, clipvalue=1.0, decay=3e-8)self.AM = Sequential()self.AM.add(self.generator())self.AM.add(self.discriminator())self.AM.compile(loss='binary_crossentropy', optimizer=optimizer,\\metrics=['accuracy'])" }, { "code": null, "e": 6649, "s": 6577, "text": "Listing 4. Adversarial Model as shown in Figure 3 implemented in Keras." }, { "code": null, "e": 7009, "s": 6649, "text": "Training is the hardest part. We determine first if Discriminator model is correct by training it alone with real and fake images. Afterwards, the Discriminator and Adversarial models are trained one after the other. Figure 4 shows the Discriminator Model while Figure 3 shows the Adversarial Model during training. Listing 5 shows the training code in Keras." }, { "code": null, "e": 7494, "s": 7009, "text": "images_train = self.x_train[np.random.randint(0,self.x_train.shape[0], size=batch_size), :, :, :]noise = np.random.uniform(-1.0, 1.0, size=[batch_size, 100])images_fake = self.generator.predict(noise)x = np.concatenate((images_train, images_fake))y = np.ones([2*batch_size, 1])y[batch_size:, :] = 0d_loss = self.discriminator.train_on_batch(x, y)y = np.ones([batch_size, 1])noise = np.random.uniform(-1.0, 1.0, size=[batch_size, 100])a_loss = self.adversarial.train_on_batch(noise, y)" }, { "code": null, "e": 7628, "s": 7494, "text": "Listing 5. Sequential training of Discriminator Model and Adversarial Model. Training steps above 1000 generates respectable outputs." }, { "code": null, "e": 7717, "s": 7628, "text": "Training GAN models requires a lot of patience due to its depth. Here are some pointers:" }, { "code": null, "e": 8608, "s": 7717, "text": "Problem: generated images look like noise. Solution: use dropout on both Discriminator and Generator. Low dropout values (0.3 to 0.6) generate more realistic images.Problem: Discriminator loss converges rapidly to zero thus preventing the Generator from learning. Solution: Do not pre-train the Discriminator. Instead make its learning rate bigger than the Adversarial model learning rate. Use a different training noise sample for the Generator.Problem: generator images still look like noise. Solution: check if the activation, batch normalization and dropout are applied in the correct sequence.Problem: figuring out the correct training/model parameters. Solution: start with some known working values from published papers and codes and adjust one parameter at a time. Before training for 2000 or more steps, observe the effect of parameter value adjustment at about 500 or 1000 steps." }, { "code": null, "e": 8774, "s": 8608, "text": "Problem: generated images look like noise. Solution: use dropout on both Discriminator and Generator. Low dropout values (0.3 to 0.6) generate more realistic images." }, { "code": null, "e": 9056, "s": 8774, "text": "Problem: Discriminator loss converges rapidly to zero thus preventing the Generator from learning. Solution: Do not pre-train the Discriminator. Instead make its learning rate bigger than the Adversarial model learning rate. Use a different training noise sample for the Generator." }, { "code": null, "e": 9209, "s": 9056, "text": "Problem: generator images still look like noise. Solution: check if the activation, batch normalization and dropout are applied in the correct sequence." }, { "code": null, "e": 9502, "s": 9209, "text": "Problem: figuring out the correct training/model parameters. Solution: start with some known working values from published papers and codes and adjust one parameter at a time. Before training for 2000 or more steps, observe the effect of parameter value adjustment at about 500 or 1000 steps." }, { "code": null, "e": 9664, "s": 9502, "text": "Figure 5 shows the evolution of output images during training. Observing Figure 5 is fascinating. The GAN is learning how to write handwritten digits on its own!" } ]
Machine Learning 102: Logistic Regression With Polynomial Features | by Leihua Ye, PhD | Towards Data Science
Data Scientists are rock stars! Rock and Roll! In my previous ML 101 article, I explained how we could apply logistic regression to classify linear questions. In this post, I want to complicate things a little bit by including nonlinear features. Just like the real world, things are intertwined and messy. Let’s delve into the R. # Load the dataset library(tidyverse)data5 = read_csv("nonlinear.csv")require(ggplot2)qplot(X1,X2,colour = Y,data=data5) As we can see, black dots are surrounded by blue dots. Our job is to find a ML technique to neatly separate these two types of dots. # build a regular logistic regressionglm_5b = glm(Y~X1+X2,data=data5)summary(glm_5b)Call:glm(formula = Y ~ X1 + X2, data = data5)Deviance Residuals: Min 1Q Median 3Q Max -0.6944 -0.5504 0.1937 0.3584 0.6213 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.71038 0.05672 12.524 <2e-16 ***X1 -0.05446 0.02496 -2.182 0.0325 * X2 0.04278 0.02708 1.580 0.1187 ---Signif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1(Dispersion parameter for gaussian family taken to be 0.2109993) Null deviance: 16.000 on 71 degrees of freedomResidual deviance: 14.559 on 69 degrees of freedomAIC: 97.238Number of Fisher Scoring iterations: 2 As can be seen, the regular logistic regression fails to consider the nonlinear feature and performs poorly. Next, let’s project class labels over to finely sampled grid points and plot predictions at each point on the grid colored by class labels. # grid of points over sample spacegr <- expand.grid(X1=seq(-5, 5, by=0.1), # sample points in X1 X2=seq(-5, 5, by=0.1)) # sample points in X2#predict class labelprobability_pred = predict(glm_5b,gr,type=”response”)# set the cutoff point at 0.5class_pred = as.factor(ifelse(probability_pred<=0.5, β€œ0”, β€œ1”))color_array <- c(β€œred”, β€œblue”)[as.numeric(class_pred)] plot(gr,col=color_array,pch=20,cex=0.25) From the above plot, a regular logistic regression model does not work that well. Let’s include 2nd degree polynomial terms of x1 and x2. glm_5c =glm(Y~poly(X1,deg=2)*poly(X2,deg=2),data=data5)summary(glm_5c) probability_pred_5c = predict(glm_5c,gr,type=”response”)class_pred_5c = as.factor(ifelse(probability_pred_5c<=0.5, β€œ0”, β€œ1”))color_array_5c <- c(β€œred”, β€œblue”)[as.numeric(class_pred_5c)] plot(gr,col=color_array_5c,pch=20,cex=0.25) As can be seen from the ANOVA outputs, the following variables are statistically significant: X1, X1 2, X2, X2 2, X1*(X2)2, and (X1)2*(X2)2. Since the second-order terms are significant, we can’t fit a simple linear classification. Besides, the logistic model with higher terms performs better than the simple model, as can be seen from the plot. To play a safe card, let’s try a logistic model with 5-th degree polynomials without any interaction terms. glm_5d =glm(Y~poly(data5$X1,deg=5)+poly(data5$X2,deg=5),data=data5)summary(glm_5d)Call:glm(formula = Y ~ poly(data5$X1, deg = 5) + poly(data5$X2, deg = 5), data = data5)Deviance Residuals: Min 1Q Median 3Q Max -0.51652 -0.15930 -0.06256 0.17439 0.73943 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.66667 0.03309 20.145 < 2e-16 ***poly(data5$X1, deg = 5)1 -0.70547 0.30163 -2.339 0.02264 * poly(data5$X1, deg = 5)2 0.94681 0.28791 3.289 0.00167 ** poly(data5$X1, deg = 5)3 0.82225 0.28386 2.897 0.00523 ** poly(data5$X1, deg = 5)4 -0.24777 0.29833 -0.831 0.40948 poly(data5$X1, deg = 5)5 -0.00171 0.29624 -0.006 0.99541 poly(data5$X2, deg = 5)1 0.62673 0.28989 2.162 0.03456 * poly(data5$X2, deg = 5)2 1.70311 0.30479 5.588 5.69e-07 ***poly(data5$X2, deg = 5)3 -1.60001 0.29074 -5.503 7.84e-07 ***poly(data5$X2, deg = 5)4 -0.83690 0.28945 -2.891 0.00531 ** poly(data5$X2, deg = 5)5 0.88545 0.29321 3.020 0.00369 ** ---Signif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1(Dispersion parameter for gaussian family taken to be 0.07885262) Null deviance: 16.00 on 71 degrees of freedomResidual deviance: 4.81 on 61 degrees of freedomAIC: 33.498Number of Fisher Scoring iterations: 2probability_pred_5d = predict(glm_5d,gr,type=”response”)class_pred_5d = as.factor(ifelse(probability_pred_5d<=0.5, β€œ0”, β€œ1”))color_array_5d <- c(β€œred”, β€œblue”)[as.numeric(class_pred_5d)]plot(gr,col=color_array_5d,pch=20,cex=0.25) The 5th degree polynomials do not improve the performance. In summary, let’s compare the models compared in terms of bias and variance tradeoff. The general logistic model without interaction and higher-order terms has the lowest variance but the highest bias. The model with the 5th order polynomial term has the highest variance and lowest bias. The model with the 2nd order polynomial and interaction terms performs the best in terms of bias-variance tradeoff. # let's create three additional bootstrap replicates of the original dataset and fit regression models to the replicates.Boot_sample_5f <- lapply(1:3,function(i)data5[sample(1:nrow(data5),replace = TRUE),])for (i in 1:3) { glm_5b = glm(Y~X1+X2,data=Boot_sample_5f[[i]]) probability_pred_5f = predict(glm_5b,gr,type=”response”) class_pred_5f = as.factor(ifelse(probability_pred_5f<=0.5, β€œ0”, β€œ1”))#plot class predictions on the grid of values for each of both linear and 5th order modelscolor_array_5f <- c(β€œred”, β€œblue”)[as.numeric(class_pred_5f)] plot(gr,col=color_array_5f,pch=20,cex=0.25)}# the 5th order polynomial term.Boot_sample_5f_2 <- lapply(1:3,function(i)data5[sample(1:nrow(data5),replace = TRUE),])for (i in 1:3) { glm_5order = glm(Y~poly(data5$X1,deg=5)+poly(data5$X2,deg=5),data=Boot_sample_5f_2[[i]]) probability_pred_5order = predict(glm_5order,gr,type=”response”) class_pred_5order = as.factor(ifelse(probability_pred_5order<=0.5, β€œ0”, β€œ1”)) color_array_5order <- c(β€œred”, β€œblue”)[as.numeric(class_pred_5order)] plot(gr,col=color_array_5order,pch=20,cex=0.25)} From Plots 1–3, the grid was divided into two parts by a straight line, referring to a large bias and a small variance. From Plots 4–6, we observe a reversed pattern: it has a small bias as there are more variables to minimize the distance between predictions and true values. It has a large variance because the dots distributed all over the diagram. Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees. leihua-ye.medium.com Please find me on LinkedIn and Youtube. Also, check my other posts on Artificial Intelligence and Machine Learning.
[ { "code": null, "e": 203, "s": 171, "text": "Data Scientists are rock stars!" }, { "code": null, "e": 218, "s": 203, "text": "Rock and Roll!" }, { "code": null, "e": 478, "s": 218, "text": "In my previous ML 101 article, I explained how we could apply logistic regression to classify linear questions. In this post, I want to complicate things a little bit by including nonlinear features. Just like the real world, things are intertwined and messy." }, { "code": null, "e": 502, "s": 478, "text": "Let’s delve into the R." }, { "code": null, "e": 623, "s": 502, "text": "# Load the dataset library(tidyverse)data5 = read_csv(\"nonlinear.csv\")require(ggplot2)qplot(X1,X2,colour = Y,data=data5)" }, { "code": null, "e": 756, "s": 623, "text": "As we can see, black dots are surrounded by blue dots. Our job is to find a ML technique to neatly separate these two types of dots." }, { "code": null, "e": 1499, "s": 756, "text": "# build a regular logistic regressionglm_5b = glm(Y~X1+X2,data=data5)summary(glm_5b)Call:glm(formula = Y ~ X1 + X2, data = data5)Deviance Residuals: Min 1Q Median 3Q Max -0.6944 -0.5504 0.1937 0.3584 0.6213 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.71038 0.05672 12.524 <2e-16 ***X1 -0.05446 0.02496 -2.182 0.0325 * X2 0.04278 0.02708 1.580 0.1187 ---Signif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1(Dispersion parameter for gaussian family taken to be 0.2109993) Null deviance: 16.000 on 71 degrees of freedomResidual deviance: 14.559 on 69 degrees of freedomAIC: 97.238Number of Fisher Scoring iterations: 2" }, { "code": null, "e": 1608, "s": 1499, "text": "As can be seen, the regular logistic regression fails to consider the nonlinear feature and performs poorly." }, { "code": null, "e": 1748, "s": 1608, "text": "Next, let’s project class labels over to finely sampled grid points and plot predictions at each point on the grid colored by class labels." }, { "code": null, "e": 2151, "s": 1748, "text": "# grid of points over sample spacegr <- expand.grid(X1=seq(-5, 5, by=0.1), # sample points in X1 X2=seq(-5, 5, by=0.1)) # sample points in X2#predict class labelprobability_pred = predict(glm_5b,gr,type=”response”)# set the cutoff point at 0.5class_pred = as.factor(ifelse(probability_pred<=0.5, β€œ0”, β€œ1”))color_array <- c(β€œred”, β€œblue”)[as.numeric(class_pred)] plot(gr,col=color_array,pch=20,cex=0.25)" }, { "code": null, "e": 2233, "s": 2151, "text": "From the above plot, a regular logistic regression model does not work that well." }, { "code": null, "e": 2289, "s": 2233, "text": "Let’s include 2nd degree polynomial terms of x1 and x2." }, { "code": null, "e": 2360, "s": 2289, "text": "glm_5c =glm(Y~poly(X1,deg=2)*poly(X2,deg=2),data=data5)summary(glm_5c)" }, { "code": null, "e": 2591, "s": 2360, "text": "probability_pred_5c = predict(glm_5c,gr,type=”response”)class_pred_5c = as.factor(ifelse(probability_pred_5c<=0.5, β€œ0”, β€œ1”))color_array_5c <- c(β€œred”, β€œblue”)[as.numeric(class_pred_5c)] plot(gr,col=color_array_5c,pch=20,cex=0.25)" }, { "code": null, "e": 2823, "s": 2591, "text": "As can be seen from the ANOVA outputs, the following variables are statistically significant: X1, X1 2, X2, X2 2, X1*(X2)2, and (X1)2*(X2)2. Since the second-order terms are significant, we can’t fit a simple linear classification." }, { "code": null, "e": 2938, "s": 2823, "text": "Besides, the logistic model with higher terms performs better than the simple model, as can be seen from the plot." }, { "code": null, "e": 3046, "s": 2938, "text": "To play a safe card, let’s try a logistic model with 5-th degree polynomials without any interaction terms." }, { "code": null, "e": 4643, "s": 3046, "text": "glm_5d =glm(Y~poly(data5$X1,deg=5)+poly(data5$X2,deg=5),data=data5)summary(glm_5d)Call:glm(formula = Y ~ poly(data5$X1, deg = 5) + poly(data5$X2, deg = 5), data = data5)Deviance Residuals: Min 1Q Median 3Q Max -0.51652 -0.15930 -0.06256 0.17439 0.73943 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.66667 0.03309 20.145 < 2e-16 ***poly(data5$X1, deg = 5)1 -0.70547 0.30163 -2.339 0.02264 * poly(data5$X1, deg = 5)2 0.94681 0.28791 3.289 0.00167 ** poly(data5$X1, deg = 5)3 0.82225 0.28386 2.897 0.00523 ** poly(data5$X1, deg = 5)4 -0.24777 0.29833 -0.831 0.40948 poly(data5$X1, deg = 5)5 -0.00171 0.29624 -0.006 0.99541 poly(data5$X2, deg = 5)1 0.62673 0.28989 2.162 0.03456 * poly(data5$X2, deg = 5)2 1.70311 0.30479 5.588 5.69e-07 ***poly(data5$X2, deg = 5)3 -1.60001 0.29074 -5.503 7.84e-07 ***poly(data5$X2, deg = 5)4 -0.83690 0.28945 -2.891 0.00531 ** poly(data5$X2, deg = 5)5 0.88545 0.29321 3.020 0.00369 ** ---Signif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1(Dispersion parameter for gaussian family taken to be 0.07885262) Null deviance: 16.00 on 71 degrees of freedomResidual deviance: 4.81 on 61 degrees of freedomAIC: 33.498Number of Fisher Scoring iterations: 2probability_pred_5d = predict(glm_5d,gr,type=”response”)class_pred_5d = as.factor(ifelse(probability_pred_5d<=0.5, β€œ0”, β€œ1”))color_array_5d <- c(β€œred”, β€œblue”)[as.numeric(class_pred_5d)]plot(gr,col=color_array_5d,pch=20,cex=0.25)" }, { "code": null, "e": 4702, "s": 4643, "text": "The 5th degree polynomials do not improve the performance." }, { "code": null, "e": 4788, "s": 4702, "text": "In summary, let’s compare the models compared in terms of bias and variance tradeoff." }, { "code": null, "e": 4904, "s": 4788, "text": "The general logistic model without interaction and higher-order terms has the lowest variance but the highest bias." }, { "code": null, "e": 4991, "s": 4904, "text": "The model with the 5th order polynomial term has the highest variance and lowest bias." }, { "code": null, "e": 5107, "s": 4991, "text": "The model with the 2nd order polynomial and interaction terms performs the best in terms of bias-variance tradeoff." }, { "code": null, "e": 6188, "s": 5107, "text": "# let's create three additional bootstrap replicates of the original dataset and fit regression models to the replicates.Boot_sample_5f <- lapply(1:3,function(i)data5[sample(1:nrow(data5),replace = TRUE),])for (i in 1:3) { glm_5b = glm(Y~X1+X2,data=Boot_sample_5f[[i]]) probability_pred_5f = predict(glm_5b,gr,type=”response”) class_pred_5f = as.factor(ifelse(probability_pred_5f<=0.5, β€œ0”, β€œ1”))#plot class predictions on the grid of values for each of both linear and 5th order modelscolor_array_5f <- c(β€œred”, β€œblue”)[as.numeric(class_pred_5f)] plot(gr,col=color_array_5f,pch=20,cex=0.25)}# the 5th order polynomial term.Boot_sample_5f_2 <- lapply(1:3,function(i)data5[sample(1:nrow(data5),replace = TRUE),])for (i in 1:3) { glm_5order = glm(Y~poly(data5$X1,deg=5)+poly(data5$X2,deg=5),data=Boot_sample_5f_2[[i]]) probability_pred_5order = predict(glm_5order,gr,type=”response”) class_pred_5order = as.factor(ifelse(probability_pred_5order<=0.5, β€œ0”, β€œ1”)) color_array_5order <- c(β€œred”, β€œblue”)[as.numeric(class_pred_5order)] plot(gr,col=color_array_5order,pch=20,cex=0.25)}" }, { "code": null, "e": 6308, "s": 6188, "text": "From Plots 1–3, the grid was divided into two parts by a straight line, referring to a large bias and a small variance." }, { "code": null, "e": 6540, "s": 6308, "text": "From Plots 4–6, we observe a reversed pattern: it has a small bias as there are more variables to minimize the distance between predictions and true values. It has a large variance because the dots distributed all over the diagram." }, { "code": null, "e": 6752, "s": 6540, "text": "Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees." }, { "code": null, "e": 6773, "s": 6752, "text": "leihua-ye.medium.com" }, { "code": null, "e": 6813, "s": 6773, "text": "Please find me on LinkedIn and Youtube." } ]
Data Classes in Python (dataclasses)
The dataclasses is a new module added in Python's standard library since version 3.7. It defines @dataclass decorator that automatically generates constructor magic method __init__(), string representation method __repr__(), the __eq__() method which overloads == operator (and a few more) for a user defined class. The dataclass decorator has following signature dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) All the arguments take a Boolean value indicating whether a respective magic method or methods will be automatically generated or not. The 'init' argument is True by default. It will automatically generate __init__() method for the class. Let us define Student class using dataclass decorator as follows from dataclasses import dataclass @dataclass class Student(object): name : str age : int percent : float The auto-generated __init__() method is like def __init__(self, name: str, age: int, percent: float): self.name = name self.age = age self.percent = percent If the class explicitly defines __init__() method, then init parameter is ignored. The repr argument is true also by default. Hence __repr__() method will be generated automatically. The __repr__() is a formal string representation of object. If the class already defines __repr__(), this parameter is ignored. The eq argument is by default true . This will auto-generate the __eq__() method. This method gets called in response to equals comparison operator (==). Again, if the class already defines __eq__(), this parameter is ignored. If the 'order' parameter is true (the default is False), the magic methods for comparison, __lt__(), __le__(), __gt__(), and __ge__() methods will beauto- generated, they implement comparison operators < <= > ans >= respectively. If order is true and eq is false, a ValueError is raised. If the class already defines any ofthese methods), it reults into TypeError. unsafe_hash argument if False (the default), a __hash__() method is generated according to how eq and frozen are set. frozen argument: If true (the default is False), emulates read-only frozen instances. >>> from data_class import Student >>> s1=Student('Naveen', 21, 50.50) >>> s2=Student('Mangesh', 20, 50.00) >>> s1==s2 False This function converts class instance into a dictionary object. >>> import dataclasses >>> dataclasses.asdict(s1) {'name': 'Naveen', 'age': 21, 'percent': 50.5} This function converts class instance into a tuple object. >>> dataclasses.astuple(s2) ('Mahesh', 20, 50.0) This function creates a new dataclass from the list of tuples given as fields argument. >>> NewClass=dataclasses.make_dataclass('NewClass', [('x',int),('y',float)]) >>> n = NewClass(10,20) >>> n NewClass(x=10, y=20)
[ { "code": null, "e": 1378, "s": 1062, "text": "The dataclasses is a new module added in Python's standard library since version 3.7. It defines @dataclass decorator that automatically generates constructor magic method __init__(), string representation method __repr__(), the __eq__() method which overloads == operator (and a few more) for a user defined class." }, { "code": null, "e": 1426, "s": 1378, "text": "The dataclass decorator has following signature" }, { "code": null, "e": 1513, "s": 1426, "text": "dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)" }, { "code": null, "e": 1648, "s": 1513, "text": "All the arguments take a Boolean value indicating whether a respective magic method or methods will be automatically generated or not." }, { "code": null, "e": 1752, "s": 1648, "text": "The 'init' argument is True by default. It will automatically generate __init__() method for the class." }, { "code": null, "e": 1817, "s": 1752, "text": "Let us define Student class using dataclass decorator as follows" }, { "code": null, "e": 1932, "s": 1817, "text": "from dataclasses import dataclass\n\n@dataclass\nclass Student(object):\n name : str\n age : int\n percent : float" }, { "code": null, "e": 1977, "s": 1932, "text": "The auto-generated __init__() method is like" }, { "code": null, "e": 2098, "s": 1977, "text": "def __init__(self, name: str, age: int, percent: float):\n self.name = name\n self.age = age\n self.percent = percent" }, { "code": null, "e": 2181, "s": 2098, "text": "If the class explicitly defines __init__() method, then init parameter is ignored." }, { "code": null, "e": 2409, "s": 2181, "text": "The repr argument is true also by default. Hence __repr__() method will be generated automatically. The __repr__() is a formal string representation of object. If the class already defines __repr__(), this parameter is ignored." }, { "code": null, "e": 2636, "s": 2409, "text": "The eq argument is by default true . This will auto-generate the __eq__() method. This method gets called in response to equals comparison operator (==). Again, if the class already defines __eq__(), this parameter is ignored." }, { "code": null, "e": 3001, "s": 2636, "text": "If the 'order' parameter is true (the default is False), the magic methods for comparison, __lt__(), __le__(), __gt__(), and __ge__() methods will beauto- generated, they implement comparison operators < <= > ans >= respectively. If order is true and eq is false, a ValueError is raised. If the class already defines any ofthese methods), it reults into TypeError." }, { "code": null, "e": 3119, "s": 3001, "text": "unsafe_hash argument if False (the default), a __hash__() method is generated according to how eq and frozen are set." }, { "code": null, "e": 3205, "s": 3119, "text": "frozen argument: If true (the default is False), emulates read-only frozen instances." }, { "code": null, "e": 3330, "s": 3205, "text": ">>> from data_class import Student\n>>> s1=Student('Naveen', 21, 50.50)\n>>> s2=Student('Mangesh', 20, 50.00)\n>>> s1==s2\nFalse" }, { "code": null, "e": 3394, "s": 3330, "text": "This function converts class instance into a dictionary object." }, { "code": null, "e": 3491, "s": 3394, "text": ">>> import dataclasses\n>>> dataclasses.asdict(s1)\n{'name': 'Naveen', 'age': 21, 'percent': 50.5}" }, { "code": null, "e": 3550, "s": 3491, "text": "This function converts class instance into a tuple object." }, { "code": null, "e": 3599, "s": 3550, "text": ">>> dataclasses.astuple(s2)\n('Mahesh', 20, 50.0)" }, { "code": null, "e": 3687, "s": 3599, "text": "This function creates a new dataclass from the list of tuples given as fields argument." }, { "code": null, "e": 3815, "s": 3687, "text": ">>> NewClass=dataclasses.make_dataclass('NewClass', [('x',int),('y',float)])\n>>> n = NewClass(10,20)\n>>> n\nNewClass(x=10, y=20)" } ]
Batch Script - Renaming Folders
For renaming folders, Batch Script provides the REN or RENAME command. RENAME [drive:][path][directoryname1 | filename1] [directoryname2 | filename2] Let’s look at some examples of renaming folders. ren Example Example1 The above command will rename the folder called Example in the current working directory to Example1. ren C:\Example Example1 The above command will rename the folder called Example in C Drive to Example1. Print Add Notes Bookmark this page
[ { "code": null, "e": 2240, "s": 2169, "text": "For renaming folders, Batch Script provides the REN or RENAME command." }, { "code": null, "e": 2320, "s": 2240, "text": "RENAME [drive:][path][directoryname1 | filename1] [directoryname2 | filename2]\n" }, { "code": null, "e": 2369, "s": 2320, "text": "Let’s look at some examples of renaming folders." }, { "code": null, "e": 2391, "s": 2369, "text": "ren Example Example1\n" }, { "code": null, "e": 2493, "s": 2391, "text": "The above command will rename the folder called Example in the current working directory to Example1." }, { "code": null, "e": 2518, "s": 2493, "text": "ren C:\\Example Example1\n" }, { "code": null, "e": 2598, "s": 2518, "text": "The above command will rename the folder called Example in C Drive to Example1." }, { "code": null, "e": 2605, "s": 2598, "text": " Print" }, { "code": null, "e": 2616, "s": 2605, "text": " Add Notes" } ]
Making Your Loss Function Count. Some errors are more costly than... | by Kieran | Towards Data Science
George Orwell’s novella Animal Farm includes the memorable line... all animals are equal, but some animals are more equal than others 1 Orwell may have been referring to hypocrisy, power, and privilege in society, but if you replace the word animals with errors, it starts to become very relevant to machine learning. Now that I’ve finished pretending to be well-read, let’s get more specific. Explaining the concept of false positives and negatives is a popular interview question because they are so important when applying a classification algorithm in practice. I still sometimes find myself hastily consulting Wikipedia just before a meeting to triple-check that I’m using terms like precision and recall the right way round. For this article, you should only need to remember... False positives are when the model predicts that a condition exists, but it does not, in reality (e.g. a fire alarm going off when there is no fire). False negatives are when the model predicts that the condition is not present, but in actual fact, it is (e.g. a smoke alarm fails to go off when there is a fire). With the definitions out of the way, let’s imagine that you work for a bank and your boss has asked you to build a model to identify fraudulent customers. Before any modelling takes place, it would be important to ask... What happens if my model gets it wrong? I don’t mean asking this from a statistical point of view, but instead, really understanding what it means for the business. The answer you receive will determine how you evaluate and deploy your model. In Scenario 1, your model does not need to be as confident when marking a customer as fraudulent given that a more detailed human review will follow, and you would expect false positives to be filtered out by the fraud team. Conversely, in Scenario 2, it is a riskier outcome when a customer is flagged because they are automatically suspended. If too many false positives slip through, then you are suspending innocent customers, giving them a nasty experience, and generating bad press. Identifying the sweet spot for how strict or relaxed your model should be is quite a balancing act because targeting a reduction in false positives inherently leads to an increase in false negatives and vice versa. Given the trade-off between false positive and negative rates, a model’s output can be used more creatively. Binary classification models often classify anything that has over 50% probability, but if you are concerned with the false positive rate being too high, you could use a higher threshold e.g. only classify fraudulent customers if their predicted probability exceeds 80%. Or the business could follow a hybrid approach between Scenario 1 and 2, where customers with a predicted probability of 80% or above are automatically suspended, and anyone between 50% and 80% is shared with the fraud team for more rigorous review. This kind of strategy often works well enough, but ultimately they involve training a machine learning algorithm that assumes all types of error are equally important and then massaging its output to correct that assumption. Fortunately, it is possible to directly influence how a variety of machine learning algorithms learn, and place more importance on a specific error type. Some of the techniques for handling class imbalance can also serve a similar purpose of targeting false positives or negatives, but this article focuses on achieving this goal via the loss function. When it comes to deep learning, the loss function determines what the algorithm is trying to minimise as it learns and iteratively improves. Loss functions often default to mean squared error (regression) and cross-entropy loss (classification), but there is plenty of funkier options which can work better in certain use cases. Regardless of the function itself, however, they all share a purpose in that they provide a feedback mechanism for the model to check how well it is performing, find the gradient of the loss function, and use that gradient to update the network’s weights to reduce loss as quickly as possible. Even though we’re now talking about deep learning and much more complex and powerful models, they would still fail to distinguish between the type of error they are committing. Fortunately, TensorFlow allows you to take control of this. Just before we get to the code, let’s take a new scenario (I promise this is the last one). You are working for a leisure centre where customers pay a monthly subscription, but they have the option of changing which price tier they subscribe to at the end of each month. As with most businesses, it’s helpful to know whether customers are spending more or less over time, and forecast what they are likely to do in the future. To offer that capability, you are asked to build a model which can learn from a customer’s characteristics and predict whether they will trade up, down, or stay on the same price plan. By taking a snapshot of past behaviour i.e. whether a customer was using the gym more or less vs the last month and how long they had spent on the same plan, a model could be trained to predict one of three classes for what the customer will do next month: Spend more and trade Up Stay on the same plan and remain Stable Spend less and trade Down Naturally, you would like the model to be as accurate as possible across the board. Yet the model’s output might be used by the Finance Team to determine how much revenue will be coming in and how much they can afford to reinvest. In this context, it is far more damaging to overestimate how many customers will trade-up, as the business will be expecting more revenue than it achieves. Whilst it isn’t great to overestimate customers trading down, at least it leaves the Finance Team in a nicer position of having more money coming in than expected. Armed with this commercial context, you can directly manipulate how the model trains to reflect the cautiousness the Finance Team desires. We shall use TensorFlow and the Keras API to demonstrate how this can be achieved. If you wish to follow along and execute the code yourself, you can follow the instructions here. Have a read of the code below to get a taste of Tensorflow’s flexibility. This notebook accompanies the medium article Making Your Loss Function Count. The code within highlights how to use a custom loss function in Tensorflow in a hypothetical scenario, in which you work for a leisure centre where customers can sign up for different price tiers each month, and your job is to predict whether they will trade up, trade down, or remain at the same price tier in the next month. import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import seaborn as sns from sklearn import metrics, model_selection, preprocessing import tensorflow as tf from tensorflow.keras import losses from tensorflow.keras import utils as keras_utils from tensorflow.keras.layers import Input, Dense, Dropout from tensorflow.keras.models import Model, Sequential from typing import Tuple number_of_observations_per_class = 10000 dict_trade_down = { 'Shift_In_Visits_Vs_Last_Month': np.random.uniform(low=0.7, high=1.1, size=number_of_observations_per_class), 'Months_On_Price_Tier': np.random.randint(low=0, high=3, size=number_of_observations_per_class), 'Class': np.repeat(a='Down', repeats=number_of_observations_per_class) } df_trade_down = pd.DataFrame(data=dict_trade_down) dict_stable = { 'Shift_In_Visits_Vs_Last_Month': np.random.uniform(low=0.7, high=1.15, size=number_of_observations_per_class), 'Months_On_Price_Tier': np.random.randint(low=0, high=5, size=number_of_observations_per_class), 'Class': np.repeat(a='Stable', repeats=number_of_observations_per_class) } df_stable = pd.DataFrame(data=dict_stable) dict_trade_up = { 'Shift_In_Visits_Vs_Last_Month': np.random.uniform(low=0.7, high=1.2, size=number_of_observations_per_class), 'Months_On_Price_Tier': np.random.randint(low=0, high=3, size=number_of_observations_per_class), 'Class': np.repeat(a='Up', repeats=number_of_observations_per_class) } df_trade_up = pd.DataFrame(data=dict_trade_up) df_all = pd.concat([df_trade_down, df_stable, df_trade_up]).sample(frac=1) df_all.head() label_encoder = preprocessing.LabelEncoder() label_encoder = label_encoder.fit(df_all['Class']) print('Label mapping: ') label_mapping = dict(zip(label_encoder.classes_, range(len(label_encoder.classes_)))) print(label_mapping) # Transform the original datasets df_all['Class_Integer'] = label_encoder.transform(df_all['Class']) df_all[['Class', 'Class_Integer']].head(10) Label mapping: {'Down': 0, 'Stable': 1, 'Up': 2} No test dataset is taken in this demo for simplicity features = df_all.loc[:, ['Shift_In_Visits_Vs_Last_Month', 'Months_On_Price_Tier']] labels = df_all.loc[:, 'Class_Integer'] X_train, X_validation, y_train, y_validation = model_selection.train_test_split(features, labels, test_size=0.2) y_train_encoded = keras_utils.to_categorical(y_train, num_classes=3) y_validation_encoded = keras_utils.to_categorical(y_validation, num_classes=3) scenario_risk = {} scenario_risk['prediction_matches_reality'] = 1.0 scenario_risk['less_spend_than_expected'] = 3.0 scenario_risk['much_less_spend_than_expected'] = 9.0 scenario_risk['more_spend_than_expected'] = 1.25 scenario_risk['much_more_spend_than_expected'] = 1.05 print('Scenario risks: \n') for key, value in scenario_risk.items(): print(f'{key}: {value}') Scenario risks: prediction_matches_reality: 1.0 less_spend_than_expected: 3.0 much_less_spend_than_expected: 9.0 more_spend_than_expected: 1.25 much_more_spend_than_expected: 1.05 We will want to apply these weights to help with back-propagation and forcing the model to place more importance under certain scenarios. We want to avoid having weights greater than 1 as it can distort the learning process and apply weight changes which are too aggressive. As such, divide each weight by the maximum weight to have a normalised version between 0 and 1. scenario_risk_normalised = {} worst_case_scenario_risk = np.array(list(scenario_risk.values())).max() for key, value in scenario_risk.items(): scenario_risk_normalised[key] = value / worst_case_scenario_risk print('New scenario weights: \n') for key, value in scenario_risk_normalised.items(): print(f'{key}: {value}') New scenario weights: prediction_matches_reality: 0.1111111111111111 less_spend_than_expected: 0.3333333333333333 much_less_spend_than_expected: 1.0 more_spend_than_expected: 0.1388888888888889 much_more_spend_than_expected: 0.11666666666666667 def _convert_scenario_risk_to_tensor(scenario: str) -> tf.Tensor: """ Look up how risky the scenario is when comparing the model prediction to reality, and return a weight score indicating how much emphasis the model should place on learning from that particular observation. Parameters ---------- scenario : str Key of dictionary which shows the risk attached to each scenario. Should be one of... 'prediction_matches_reality' 'less_spend_than_expected' 'much_less_spend_than_expected' 'more_spend_than_expected' 'much_more_spend_than_expected' Returns ------- tf.Tensor Weight which signifies how bad the scenario is for the business, and thus how to update the loss which the model is trying to improve. """ return tf.cast(x=tf.constant(scenario_risk_normalised[scenario]), dtype=tf.float32) def _get_loss_adjustment_for_scenario(actual_vs_predicted_class: Tuple[tf.Tensor, tf.Tensor]) -> tf.Tensor: """ Return a weight according to how damaging the scenario is to the business. Parameters ---------- actual_vs_predicted_class : Tuple[tf.Tensor, tf.Tensor] The actual class, actual_vs_predicted_class[0], and the predicted class, actual_vs_predicted_class[1], for an observation. Returns ------- float Weight which signifies how bad the scenario is for the business, and thus how to upweight the loss which the model should be trying to improve. """ actual_class = actual_vs_predicted_class[0] predicted_class = actual_vs_predicted_class[1] # Retrieve the appropriate weighting based on how the prediction compares with reality # The labels are: # 0: Trade Down, 1: Stable, 2: Trade Up return tf.case( [ (tf.equal(actual_class, predicted_class), lambda: _convert_scenario_risk_to_tensor('prediction_matches_reality')), (tf.logical_and(tf.equal(actual_class, 0), tf.equal(predicted_class, 1)), lambda: _convert_scenario_risk_to_tensor('less_spend_than_expected')), (tf.logical_and(tf.equal(actual_class, 1), tf.equal(predicted_class, 2)), lambda: _convert_scenario_risk_to_tensor('less_spend_than_expected')), (tf.logical_and(tf.equal(actual_class, 0), tf.equal(predicted_class, 2)), lambda: _convert_scenario_risk_to_tensor('much_less_spend_than_expected')), (tf.logical_and(tf.equal(actual_class, 1), tf.equal(predicted_class, 0)), lambda: _convert_scenario_risk_to_tensor('more_spend_than_expected')), (tf.logical_and(tf.equal(actual_class, 2), tf.equal(predicted_class, 1)), lambda: _convert_scenario_risk_to_tensor('more_spend_than_expected')), (tf.logical_and(tf.equal(actual_class, 2), tf.equal(predicted_class, 0)), lambda: _convert_scenario_risk_to_tensor('much_more_spend_than_expected')), ] ) def custom_cross_entropy(y_actual: tf.Tensor, y_prediction: tf.Tensor) -> tf.Tensor: """ Calculate cross entropy loss, but weighted according to how risky the scenario is. Parameters ---------- y_actual : tf.Tensor One-hot encoded representation of the true class for each observation. y_prediction : tf.Tensor The predicted probability that the observation belongs to each class. Returns ------- tf.Tensor Weighted version of cross-entropy loss depending on how the prediction compares to reality. """ standard_cross_entropy = losses.categorical_crossentropy(y_true=y_actual, y_pred=y_prediction) # The label is one hot encoded, so identify the true class by which element contains the maximum value (1) actual_class = tf.math.argmax(input=y_actual, axis=1) actual_class = tf.cast(x=actual_class, dtype=tf.float32) # The prediction is a distribution of probabilities per class, # so identify the predicted class by which element contains the maximum probability predicted_class = tf.math.argmax(input=y_prediction, axis=1) predicted_class = tf.cast(x=predicted_class, dtype=tf.float32) actual_vs_predicted_class = tf.stack(values=[actual_class, predicted_class], axis=1) # Calculate the weighting that should be applied to each observation in the data weighting = tf.map_fn(fn=_get_loss_adjustment_for_scenario, elems=actual_vs_predicted_class) # Updated the cross entropy loss based on the weighting return tf.math.multiply(standard_cross_entropy, weighting) # Suppress tensorflow warnings os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' num_features = X_train.shape[1] loss = 'categorical_crossentropy' standard_model = Sequential() standard_model.add(Input(shape=(num_features, ))) standard_model.add(Dense(64, activation='relu')) standard_model.add(Dense(32, activation='relu')) standard_model.add(Dense(len(label_encoder.classes_), activation='softmax')) standard_model.summary() standard_model.compile( optimizer='adam', loss=loss, metrics=['categorical_accuracy', 'categorical_crossentropy'] ) Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) (None, 64) 192 _________________________________________________________________ dense_1 (Dense) (None, 32) 2080 _________________________________________________________________ dense_2 (Dense) (None, 3) 99 ================================================================= Total params: 2,371 Trainable params: 2,371 Non-trainable params: 0 _________________________________________________________________ loss = custom_cross_entropy custom_model = Sequential() custom_model.add(Input(shape=(num_features, ))) custom_model.add(Dense(64, activation='relu')) custom_model.add(Dense(32, activation='relu')) custom_model.add(Dense(len(label_encoder.classes_), activation='softmax')) custom_model.summary() custom_model.compile( optimizer='adam', loss=loss, metrics=['categorical_accuracy', 'categorical_crossentropy'] ) Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_3 (Dense) (None, 64) 192 _________________________________________________________________ dense_4 (Dense) (None, 32) 2080 _________________________________________________________________ dense_5 (Dense) (None, 3) 99 ================================================================= Total params: 2,371 Trainable params: 2,371 Non-trainable params: 0 _________________________________________________________________ epochs = 20 verbosity = 0 standard_model.fit( x=X_train, y=y_train_encoded, epochs=epochs, verbose=verbosity, validation_data=(X_validation, y_validation_encoded), batch_size=2048 ) <tensorflow.python.keras.callbacks.History at 0x141295d00> custom_model.fit( x=X_train, y=y_train_encoded, epochs=epochs, verbose=verbosity, validation_data=(X_validation, y_validation_encoded), batch_size=128 ) <tensorflow.python.keras.callbacks.History at 0x141a0e5e0> validation_standard_predictions = standard_model.predict(X_validation, batch_size=2048) validation_custom_predictions = custom_model.predict(X_validation, batch_size=2048) validation_standard_predictions_class = np.argmax(validation_standard_predictions, axis=1) validation_custom_predictions_class = np.argmax(validation_custom_predictions, axis=1) validation_standard_predictions_class = label_encoder.inverse_transform(validation_standard_predictions_class) validation_custom_predictions_class = label_encoder.inverse_transform(validation_custom_predictions_class) validation_true_class = label_encoder.inverse_transform(y_validation) standard_predicted_class_count = np.unique(ar=validation_standard_predictions_class, return_counts=True) standard_predicted_class_count = pd.DataFrame({ 'Model': ['Standard'] * 3, 'Class': standard_predicted_class_count[0], 'Count': standard_predicted_class_count[1] }) custom_predicted_class_count = np.unique(ar=validation_custom_predictions_class, return_counts=True) custom_predicted_class_count = pd.DataFrame({ 'Model': ['Custom'] * 3, 'Class': custom_predicted_class_count[0], 'Count': custom_predicted_class_count[1] }) predicted_class_count = pd.concat([standard_predicted_class_count, custom_predicted_class_count]) predicted_class_count.head(6) plt.rcParams['figure.figsize'] = [20, 10] plt.rcParams['font.size'] = 20 ax = sns.barplot( x='Class', y='Count', hue='Model', data=predicted_class_count ) ax.set_title(label='Predicted Class by Model Type', pad=20, fontsize=30) ax.set_xlabel(xlabel='Predicted Class', labelpad=20, fontsize=24) ax.set_ylabel(ylabel='Number of Observations', labelpad=20, fontsize=24); Hopefully, this has helped demonstrate the situations in which you may want a custom loss function, and how you go about implementing it. But more importantly, never forget the key question... What happens if my model gets it wrong? Keep this top of mind and you will transform yourself from a Data Scientist who works well in theory to one who works well in practice. Feel free to check out my other articles: A simple trick to avoid running out of memory How to Find the Right Number of Clusters How to Manage a Junior Data Scientist The Power of Permutation Testing [1] G. Orwell. Animal farm: A fairy story (2018). London: Penguin Books.
[ { "code": null, "e": 238, "s": 171, "text": "George Orwell’s novella Animal Farm includes the memorable line..." }, { "code": null, "e": 307, "s": 238, "text": "all animals are equal, but some animals are more equal than others 1" }, { "code": null, "e": 489, "s": 307, "text": "Orwell may have been referring to hypocrisy, power, and privilege in society, but if you replace the word animals with errors, it starts to become very relevant to machine learning." }, { "code": null, "e": 565, "s": 489, "text": "Now that I’ve finished pretending to be well-read, let’s get more specific." }, { "code": null, "e": 737, "s": 565, "text": "Explaining the concept of false positives and negatives is a popular interview question because they are so important when applying a classification algorithm in practice." }, { "code": null, "e": 956, "s": 737, "text": "I still sometimes find myself hastily consulting Wikipedia just before a meeting to triple-check that I’m using terms like precision and recall the right way round. For this article, you should only need to remember..." }, { "code": null, "e": 1106, "s": 956, "text": "False positives are when the model predicts that a condition exists, but it does not, in reality (e.g. a fire alarm going off when there is no fire)." }, { "code": null, "e": 1270, "s": 1106, "text": "False negatives are when the model predicts that the condition is not present, but in actual fact, it is (e.g. a smoke alarm fails to go off when there is a fire)." }, { "code": null, "e": 1491, "s": 1270, "text": "With the definitions out of the way, let’s imagine that you work for a bank and your boss has asked you to build a model to identify fraudulent customers. Before any modelling takes place, it would be important to ask..." }, { "code": null, "e": 1531, "s": 1491, "text": "What happens if my model gets it wrong?" }, { "code": null, "e": 1656, "s": 1531, "text": "I don’t mean asking this from a statistical point of view, but instead, really understanding what it means for the business." }, { "code": null, "e": 1734, "s": 1656, "text": "The answer you receive will determine how you evaluate and deploy your model." }, { "code": null, "e": 1959, "s": 1734, "text": "In Scenario 1, your model does not need to be as confident when marking a customer as fraudulent given that a more detailed human review will follow, and you would expect false positives to be filtered out by the fraud team." }, { "code": null, "e": 2223, "s": 1959, "text": "Conversely, in Scenario 2, it is a riskier outcome when a customer is flagged because they are automatically suspended. If too many false positives slip through, then you are suspending innocent customers, giving them a nasty experience, and generating bad press." }, { "code": null, "e": 2438, "s": 2223, "text": "Identifying the sweet spot for how strict or relaxed your model should be is quite a balancing act because targeting a reduction in false positives inherently leads to an increase in false negatives and vice versa." }, { "code": null, "e": 2547, "s": 2438, "text": "Given the trade-off between false positive and negative rates, a model’s output can be used more creatively." }, { "code": null, "e": 2818, "s": 2547, "text": "Binary classification models often classify anything that has over 50% probability, but if you are concerned with the false positive rate being too high, you could use a higher threshold e.g. only classify fraudulent customers if their predicted probability exceeds 80%." }, { "code": null, "e": 3068, "s": 2818, "text": "Or the business could follow a hybrid approach between Scenario 1 and 2, where customers with a predicted probability of 80% or above are automatically suspended, and anyone between 50% and 80% is shared with the fraud team for more rigorous review." }, { "code": null, "e": 3293, "s": 3068, "text": "This kind of strategy often works well enough, but ultimately they involve training a machine learning algorithm that assumes all types of error are equally important and then massaging its output to correct that assumption." }, { "code": null, "e": 3646, "s": 3293, "text": "Fortunately, it is possible to directly influence how a variety of machine learning algorithms learn, and place more importance on a specific error type. Some of the techniques for handling class imbalance can also serve a similar purpose of targeting false positives or negatives, but this article focuses on achieving this goal via the loss function." }, { "code": null, "e": 3975, "s": 3646, "text": "When it comes to deep learning, the loss function determines what the algorithm is trying to minimise as it learns and iteratively improves. Loss functions often default to mean squared error (regression) and cross-entropy loss (classification), but there is plenty of funkier options which can work better in certain use cases." }, { "code": null, "e": 4269, "s": 3975, "text": "Regardless of the function itself, however, they all share a purpose in that they provide a feedback mechanism for the model to check how well it is performing, find the gradient of the loss function, and use that gradient to update the network’s weights to reduce loss as quickly as possible." }, { "code": null, "e": 4446, "s": 4269, "text": "Even though we’re now talking about deep learning and much more complex and powerful models, they would still fail to distinguish between the type of error they are committing." }, { "code": null, "e": 4506, "s": 4446, "text": "Fortunately, TensorFlow allows you to take control of this." }, { "code": null, "e": 4598, "s": 4506, "text": "Just before we get to the code, let’s take a new scenario (I promise this is the last one)." }, { "code": null, "e": 4777, "s": 4598, "text": "You are working for a leisure centre where customers pay a monthly subscription, but they have the option of changing which price tier they subscribe to at the end of each month." }, { "code": null, "e": 4933, "s": 4777, "text": "As with most businesses, it’s helpful to know whether customers are spending more or less over time, and forecast what they are likely to do in the future." }, { "code": null, "e": 5118, "s": 4933, "text": "To offer that capability, you are asked to build a model which can learn from a customer’s characteristics and predict whether they will trade up, down, or stay on the same price plan." }, { "code": null, "e": 5375, "s": 5118, "text": "By taking a snapshot of past behaviour i.e. whether a customer was using the gym more or less vs the last month and how long they had spent on the same plan, a model could be trained to predict one of three classes for what the customer will do next month:" }, { "code": null, "e": 5399, "s": 5375, "text": "Spend more and trade Up" }, { "code": null, "e": 5439, "s": 5399, "text": "Stay on the same plan and remain Stable" }, { "code": null, "e": 5465, "s": 5439, "text": "Spend less and trade Down" }, { "code": null, "e": 5696, "s": 5465, "text": "Naturally, you would like the model to be as accurate as possible across the board. Yet the model’s output might be used by the Finance Team to determine how much revenue will be coming in and how much they can afford to reinvest." }, { "code": null, "e": 6016, "s": 5696, "text": "In this context, it is far more damaging to overestimate how many customers will trade-up, as the business will be expecting more revenue than it achieves. Whilst it isn’t great to overestimate customers trading down, at least it leaves the Finance Team in a nicer position of having more money coming in than expected." }, { "code": null, "e": 6155, "s": 6016, "text": "Armed with this commercial context, you can directly manipulate how the model trains to reflect the cautiousness the Finance Team desires." }, { "code": null, "e": 6335, "s": 6155, "text": "We shall use TensorFlow and the Keras API to demonstrate how this can be achieved. If you wish to follow along and execute the code yourself, you can follow the instructions here." }, { "code": null, "e": 6409, "s": 6335, "text": "Have a read of the code below to get a taste of Tensorflow’s flexibility." }, { "code": null, "e": 6487, "s": 6409, "text": "This notebook accompanies the medium article Making Your Loss Function Count." }, { "code": null, "e": 6815, "s": 6487, "text": "The code within highlights how to use a custom loss function in Tensorflow in a hypothetical scenario, in which you work for a leisure centre where customers can sign up for different price tiers each month, and your job is to predict whether they will trade up, trade down, or remain at the same price tier in the next month." }, { "code": null, "e": 7226, "s": 6815, "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn import metrics, model_selection, preprocessing\nimport tensorflow as tf\nfrom tensorflow.keras import losses\nfrom tensorflow.keras import utils as keras_utils\nfrom tensorflow.keras.layers import Input, Dense, Dropout\nfrom tensorflow.keras.models import Model, Sequential\nfrom typing import Tuple\n" }, { "code": null, "e": 7268, "s": 7226, "text": "number_of_observations_per_class = 10000\n" }, { "code": null, "e": 7633, "s": 7268, "text": "dict_trade_down = {\n 'Shift_In_Visits_Vs_Last_Month': np.random.uniform(low=0.7, high=1.1, size=number_of_observations_per_class),\n 'Months_On_Price_Tier': np.random.randint(low=0, high=3, size=number_of_observations_per_class),\n 'Class': np.repeat(a='Down', repeats=number_of_observations_per_class)\n}\n\ndf_trade_down = pd.DataFrame(data=dict_trade_down)\n" }, { "code": null, "e": 7989, "s": 7633, "text": "dict_stable = {\n 'Shift_In_Visits_Vs_Last_Month': np.random.uniform(low=0.7, high=1.15, size=number_of_observations_per_class),\n 'Months_On_Price_Tier': np.random.randint(low=0, high=5, size=number_of_observations_per_class),\n 'Class': np.repeat(a='Stable', repeats=number_of_observations_per_class)\n}\n\ndf_stable = pd.DataFrame(data=dict_stable)\n" }, { "code": null, "e": 8346, "s": 7989, "text": "dict_trade_up = {\n 'Shift_In_Visits_Vs_Last_Month': np.random.uniform(low=0.7, high=1.2, size=number_of_observations_per_class),\n 'Months_On_Price_Tier': np.random.randint(low=0, high=3, size=number_of_observations_per_class),\n 'Class': np.repeat(a='Up', repeats=number_of_observations_per_class)\n}\n\ndf_trade_up = pd.DataFrame(data=dict_trade_up)\n" }, { "code": null, "e": 8437, "s": 8346, "text": "df_all = pd.concat([df_trade_down, df_stable, df_trade_up]).sample(frac=1)\n\ndf_all.head()\n" }, { "code": null, "e": 8814, "s": 8437, "text": "label_encoder = preprocessing.LabelEncoder()\nlabel_encoder = label_encoder.fit(df_all['Class'])\n\nprint('Label mapping: ')\nlabel_mapping = dict(zip(label_encoder.classes_, range(len(label_encoder.classes_))))\nprint(label_mapping)\n\n# Transform the original datasets\ndf_all['Class_Integer'] = label_encoder.transform(df_all['Class'])\n\ndf_all[['Class', 'Class_Integer']].head(10)\n" }, { "code": null, "e": 8865, "s": 8814, "text": "Label mapping: \n{'Down': 0, 'Stable': 1, 'Up': 2}\n" }, { "code": null, "e": 8918, "s": 8865, "text": "No test dataset is taken in this demo for simplicity" }, { "code": null, "e": 9306, "s": 8918, "text": "features = df_all.loc[:, ['Shift_In_Visits_Vs_Last_Month', 'Months_On_Price_Tier']]\nlabels = df_all.loc[:, 'Class_Integer']\n\nX_train, X_validation, y_train, y_validation = model_selection.train_test_split(features, labels, test_size=0.2)\n\ny_train_encoded = keras_utils.to_categorical(y_train, num_classes=3)\ny_validation_encoded = keras_utils.to_categorical(y_validation, num_classes=3)\n" }, { "code": null, "e": 9326, "s": 9306, "text": "scenario_risk = {}\n" }, { "code": null, "e": 9377, "s": 9326, "text": "scenario_risk['prediction_matches_reality'] = 1.0\n" }, { "code": null, "e": 9426, "s": 9377, "text": "scenario_risk['less_spend_than_expected'] = 3.0\n" }, { "code": null, "e": 9480, "s": 9426, "text": "scenario_risk['much_less_spend_than_expected'] = 9.0\n" }, { "code": null, "e": 9530, "s": 9480, "text": "scenario_risk['more_spend_than_expected'] = 1.25\n" }, { "code": null, "e": 9585, "s": 9530, "text": "scenario_risk['much_more_spend_than_expected'] = 1.05\n" }, { "code": null, "e": 9680, "s": 9585, "text": "print('Scenario risks: \\n')\nfor key, value in scenario_risk.items(): print(f'{key}: {value}')\n" }, { "code": null, "e": 9863, "s": 9680, "text": "Scenario risks: \n\nprediction_matches_reality: 1.0\nless_spend_than_expected: 3.0\nmuch_less_spend_than_expected: 9.0\nmore_spend_than_expected: 1.25\nmuch_more_spend_than_expected: 1.05\n" }, { "code": null, "e": 10234, "s": 9863, "text": "We will want to apply these weights to help with back-propagation and forcing the model to place more importance under certain scenarios. We want to avoid having weights greater than 1 as it can distort the learning process and apply weight changes which are too aggressive. As such, divide each weight by the maximum weight to have a normalised version between 0 and 1." }, { "code": null, "e": 10564, "s": 10234, "text": "scenario_risk_normalised = {}\nworst_case_scenario_risk = np.array(list(scenario_risk.values())).max()\n\nfor key, value in scenario_risk.items():\n scenario_risk_normalised[key] = value / worst_case_scenario_risk\n \nprint('New scenario weights: \\n')\nfor key, value in scenario_risk_normalised.items(): print(f'{key}: {value}')\n" }, { "code": null, "e": 10812, "s": 10564, "text": "New scenario weights: \n\nprediction_matches_reality: 0.1111111111111111\nless_spend_than_expected: 0.3333333333333333\nmuch_less_spend_than_expected: 1.0\nmore_spend_than_expected: 0.1388888888888889\nmuch_more_spend_than_expected: 0.11666666666666667\n" }, { "code": null, "e": 11739, "s": 10812, "text": "def _convert_scenario_risk_to_tensor(scenario: str) -> tf.Tensor:\n \"\"\"\n Look up how risky the scenario is when comparing the model prediction to reality, and return a weight score\n indicating how much emphasis the model should place on learning from that particular observation.\n\n Parameters\n ----------\n scenario : str\n Key of dictionary which shows the risk attached to each scenario. Should be one of...\n 'prediction_matches_reality'\n 'less_spend_than_expected'\n 'much_less_spend_than_expected'\n 'more_spend_than_expected'\n 'much_more_spend_than_expected'\n\n Returns\n -------\n tf.Tensor\n Weight which signifies how bad the scenario is for the business, and thus how to update the loss which the\n model is trying to improve.\n \"\"\"\n\n return tf.cast(x=tf.constant(scenario_risk_normalised[scenario]), dtype=tf.float32)\n" }, { "code": null, "e": 13846, "s": 11739, "text": "def _get_loss_adjustment_for_scenario(actual_vs_predicted_class: Tuple[tf.Tensor, tf.Tensor]) -> tf.Tensor:\n \"\"\"\n Return a weight according to how damaging the scenario is to the business.\n\n Parameters\n ----------\n actual_vs_predicted_class : Tuple[tf.Tensor, tf.Tensor]\n The actual class, actual_vs_predicted_class[0], and the predicted class, actual_vs_predicted_class[1], for an\n observation.\n\n Returns\n -------\n float\n Weight which signifies how bad the scenario is for the business, and thus how to upweight the loss\n which the model should be trying to improve.\n \"\"\"\n\n actual_class = actual_vs_predicted_class[0]\n predicted_class = actual_vs_predicted_class[1]\n\n # Retrieve the appropriate weighting based on how the prediction compares with reality\n # The labels are:\n # 0: Trade Down, 1: Stable, 2: Trade Up\n return tf.case(\n [\n (tf.equal(actual_class, predicted_class),\n lambda: _convert_scenario_risk_to_tensor('prediction_matches_reality')),\n\n (tf.logical_and(tf.equal(actual_class, 0), tf.equal(predicted_class, 1)),\n lambda: _convert_scenario_risk_to_tensor('less_spend_than_expected')),\n\n (tf.logical_and(tf.equal(actual_class, 1), tf.equal(predicted_class, 2)),\n lambda: _convert_scenario_risk_to_tensor('less_spend_than_expected')),\n\n (tf.logical_and(tf.equal(actual_class, 0), tf.equal(predicted_class, 2)),\n lambda: _convert_scenario_risk_to_tensor('much_less_spend_than_expected')),\n\n (tf.logical_and(tf.equal(actual_class, 1), tf.equal(predicted_class, 0)),\n lambda: _convert_scenario_risk_to_tensor('more_spend_than_expected')),\n\n (tf.logical_and(tf.equal(actual_class, 2), tf.equal(predicted_class, 1)),\n lambda: _convert_scenario_risk_to_tensor('more_spend_than_expected')),\n\n (tf.logical_and(tf.equal(actual_class, 2), tf.equal(predicted_class, 0)),\n lambda: _convert_scenario_risk_to_tensor('much_more_spend_than_expected')),\n ]\n )\n" }, { "code": null, "e": 15440, "s": 13846, "text": "def custom_cross_entropy(y_actual: tf.Tensor, y_prediction: tf.Tensor) -> tf.Tensor:\n \"\"\"\n Calculate cross entropy loss, but weighted according to how risky the scenario is.\n\n Parameters\n ----------\n y_actual : tf.Tensor\n One-hot encoded representation of the true class for each observation.\n y_prediction : tf.Tensor\n The predicted probability that the observation belongs to each class.\n \n Returns\n -------\n tf.Tensor\n Weighted version of cross-entropy loss depending on how the prediction compares to reality.\n \"\"\"\n\n standard_cross_entropy = losses.categorical_crossentropy(y_true=y_actual, y_pred=y_prediction)\n\n # The label is one hot encoded, so identify the true class by which element contains the maximum value (1)\n actual_class = tf.math.argmax(input=y_actual, axis=1)\n actual_class = tf.cast(x=actual_class, dtype=tf.float32)\n\n # The prediction is a distribution of probabilities per class,\n # so identify the predicted class by which element contains the maximum probability\n predicted_class = tf.math.argmax(input=y_prediction, axis=1)\n predicted_class = tf.cast(x=predicted_class, dtype=tf.float32)\n\n actual_vs_predicted_class = tf.stack(values=[actual_class, predicted_class], axis=1)\n\n # Calculate the weighting that should be applied to each observation in the data\n weighting = tf.map_fn(fn=_get_loss_adjustment_for_scenario, elems=actual_vs_predicted_class)\n\n # Updated the cross entropy loss based on the weighting\n return tf.math.multiply(standard_cross_entropy, weighting)\n" }, { "code": null, "e": 15513, "s": 15440, "text": "# Suppress tensorflow warnings\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n" }, { "code": null, "e": 15546, "s": 15513, "text": "num_features = X_train.shape[1]\n" }, { "code": null, "e": 15994, "s": 15546, "text": "loss = 'categorical_crossentropy'\n\nstandard_model = Sequential()\n\nstandard_model.add(Input(shape=(num_features, )))\nstandard_model.add(Dense(64, activation='relu'))\nstandard_model.add(Dense(32, activation='relu'))\nstandard_model.add(Dense(len(label_encoder.classes_), activation='softmax'))\n\nstandard_model.summary()\n\nstandard_model.compile(\n optimizer='adam', \n loss=loss,\n metrics=['categorical_accuracy', 'categorical_crossentropy']\n)\n" }, { "code": null, "e": 16743, "s": 15994, "text": "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 64) 192 \n_________________________________________________________________\ndense_1 (Dense) (None, 32) 2080 \n_________________________________________________________________\ndense_2 (Dense) (None, 3) 99 \n=================================================================\nTotal params: 2,371\nTrainable params: 2,371\nNon-trainable params: 0\n_________________________________________________________________\n" }, { "code": null, "e": 17171, "s": 16743, "text": "loss = custom_cross_entropy\n\ncustom_model = Sequential()\n\ncustom_model.add(Input(shape=(num_features, )))\ncustom_model.add(Dense(64, activation='relu'))\ncustom_model.add(Dense(32, activation='relu'))\ncustom_model.add(Dense(len(label_encoder.classes_), activation='softmax'))\n\ncustom_model.summary()\n\ncustom_model.compile(\n optimizer='adam', \n loss=loss,\n metrics=['categorical_accuracy', 'categorical_crossentropy']\n)\n" }, { "code": null, "e": 17922, "s": 17171, "text": "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_3 (Dense) (None, 64) 192 \n_________________________________________________________________\ndense_4 (Dense) (None, 32) 2080 \n_________________________________________________________________\ndense_5 (Dense) (None, 3) 99 \n=================================================================\nTotal params: 2,371\nTrainable params: 2,371\nNon-trainable params: 0\n_________________________________________________________________\n" }, { "code": null, "e": 17949, "s": 17922, "text": "epochs = 20\nverbosity = 0\n" }, { "code": null, "e": 18133, "s": 17949, "text": "standard_model.fit(\n x=X_train, \n y=y_train_encoded, \n epochs=epochs, \n verbose=verbosity,\n validation_data=(X_validation, y_validation_encoded),\n batch_size=2048\n)\n" }, { "code": null, "e": 18192, "s": 18133, "text": "<tensorflow.python.keras.callbacks.History at 0x141295d00>" }, { "code": null, "e": 18373, "s": 18192, "text": "custom_model.fit(\n x=X_train, \n y=y_train_encoded, \n epochs=epochs, \n verbose=verbosity,\n validation_data=(X_validation, y_validation_encoded),\n batch_size=128\n)\n" }, { "code": null, "e": 18432, "s": 18373, "text": "<tensorflow.python.keras.callbacks.History at 0x141a0e5e0>" }, { "code": null, "e": 18605, "s": 18432, "text": "validation_standard_predictions = standard_model.predict(X_validation, batch_size=2048)\nvalidation_custom_predictions = custom_model.predict(X_validation, batch_size=2048)\n" }, { "code": null, "e": 18784, "s": 18605, "text": "validation_standard_predictions_class = np.argmax(validation_standard_predictions, axis=1)\nvalidation_custom_predictions_class = np.argmax(validation_custom_predictions, axis=1)\n" }, { "code": null, "e": 19003, "s": 18784, "text": "validation_standard_predictions_class = label_encoder.inverse_transform(validation_standard_predictions_class)\nvalidation_custom_predictions_class = label_encoder.inverse_transform(validation_custom_predictions_class)\n" }, { "code": null, "e": 19074, "s": 19003, "text": "validation_true_class = label_encoder.inverse_transform(y_validation)\n" }, { "code": null, "e": 19765, "s": 19074, "text": "standard_predicted_class_count = np.unique(ar=validation_standard_predictions_class, return_counts=True)\n\nstandard_predicted_class_count = pd.DataFrame({\n 'Model': ['Standard'] * 3, \n 'Class': standard_predicted_class_count[0], \n 'Count': standard_predicted_class_count[1]\n})\n\n\ncustom_predicted_class_count = np.unique(ar=validation_custom_predictions_class, return_counts=True)\n\ncustom_predicted_class_count = pd.DataFrame({\n 'Model': ['Custom'] * 3, \n 'Class': custom_predicted_class_count[0], \n 'Count': custom_predicted_class_count[1]\n})\n\npredicted_class_count = pd.concat([standard_predicted_class_count, custom_predicted_class_count])\n\npredicted_class_count.head(6)\n" }, { "code": null, "e": 19839, "s": 19765, "text": "plt.rcParams['figure.figsize'] = [20, 10]\nplt.rcParams['font.size'] = 20\n" }, { "code": null, "e": 20152, "s": 19839, "text": "ax = sns.barplot(\n x='Class',\n y='Count',\n hue='Model',\n data=predicted_class_count\n)\n\nax.set_title(label='Predicted Class by Model Type', pad=20, fontsize=30)\nax.set_xlabel(xlabel='Predicted Class', labelpad=20, fontsize=24)\nax.set_ylabel(ylabel='Number of Observations', labelpad=20, fontsize=24);\n" }, { "code": null, "e": 20293, "s": 20155, "text": "Hopefully, this has helped demonstrate the situations in which you may want a custom loss function, and how you go about implementing it." }, { "code": null, "e": 20348, "s": 20293, "text": "But more importantly, never forget the key question..." }, { "code": null, "e": 20388, "s": 20348, "text": "What happens if my model gets it wrong?" }, { "code": null, "e": 20524, "s": 20388, "text": "Keep this top of mind and you will transform yourself from a Data Scientist who works well in theory to one who works well in practice." }, { "code": null, "e": 20566, "s": 20524, "text": "Feel free to check out my other articles:" }, { "code": null, "e": 20612, "s": 20566, "text": "A simple trick to avoid running out of memory" }, { "code": null, "e": 20653, "s": 20612, "text": "How to Find the Right Number of Clusters" }, { "code": null, "e": 20691, "s": 20653, "text": "How to Manage a Junior Data Scientist" }, { "code": null, "e": 20724, "s": 20691, "text": "The Power of Permutation Testing" } ]
How can I pass arguments to Tkinter button's callback command?
Tkinter Buttons are used for handling certain operations in the application. In order to handle such events, we generally pass the defined function name as the value in the callback command. For a particular event, we can also pass the argument to the function in the button’s command. There are two ways to pass the argument to the tkinter button command βˆ’ Using Lambda or anonymous function Using Partials In this example, we will create a simple application that will contain a text label and a button to change the value of label text. We will pass the label as the argument in the button command by using lambda function. #Import necessary Library from tkinter import * from tkinter import ttk #Create an instance of tkinter window win= Tk() #Set the geometry of tkinter window win.geometry("750x250") #Define the function to change the value in label widget def change_text(label): label.configure(text= "Hey, I am Label-2", background="gray91") #Create a Label label = Label(win, text= "Hey, I am Label-1", font= ('Helvetica 15 underline'), background="gray76") label.pack(pady=20) #Create a button btn= ttk.Button(win, text= "Change", command= lambda:change_text(label)) btn.pack(pady=10) win.mainloop() Running the above code will display a window which contains a text label and a button to change the value of the label. Now click on β€œChange” button to change the value of the label widget.
[ { "code": null, "e": 1348, "s": 1062, "text": "Tkinter Buttons are used for handling certain operations in the application. In order to handle such events, we generally pass the defined function name as the value in the callback command. For a particular event, we can also pass the argument to the function in the button’s command." }, { "code": null, "e": 1420, "s": 1348, "text": "There are two ways to pass the argument to the tkinter button command βˆ’" }, { "code": null, "e": 1455, "s": 1420, "text": "Using Lambda or anonymous function" }, { "code": null, "e": 1470, "s": 1455, "text": "Using Partials" }, { "code": null, "e": 1689, "s": 1470, "text": "In this example, we will create a simple application that will contain a text label and a button to change the value of label text. We will pass the label as the argument in the button command by using lambda function." }, { "code": null, "e": 2277, "s": 1689, "text": "#Import necessary Library\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter window\nwin= Tk()\n#Set the geometry of tkinter window\nwin.geometry(\"750x250\")\n#Define the function to change the value in label widget\ndef change_text(label):\n label.configure(text= \"Hey, I am Label-2\", background=\"gray91\")\n#Create a Label\nlabel = Label(win, text= \"Hey, I am Label-1\", font= ('Helvetica 15 underline'), background=\"gray76\")\nlabel.pack(pady=20)\n#Create a button\nbtn= ttk.Button(win, text= \"Change\", command= lambda:change_text(label))\nbtn.pack(pady=10)\nwin.mainloop()" }, { "code": null, "e": 2397, "s": 2277, "text": "Running the above code will display a window which contains a text label and a button to change the value of the label." }, { "code": null, "e": 2467, "s": 2397, "text": "Now click on β€œChange” button to change the value of the label widget." } ]
MongoDB query for capped sub-collection in an array
In MongoDB, you cannot use capped for sub-collection. However, use capped on the overall document. To display a specific number of values from an array, prefer $slice. Let us create a collection with documents βˆ’ > db.demo319.insertOne({"Scores":[100,345,980,890]}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ecf6f8647eb59e562064") } > db.demo319.insertOne({"Scores":[903,10004,84575,844]}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ed01f8647eb59e562065") } Display all documents from a collection with the help of find() method βˆ’ > db.demo319.find().pretty(); This will produce the following output βˆ’ { "_id" : ObjectId("5e50ecf6f8647eb59e562064"), "Scores" : [ 100, 345, 980, 890 ] } { "_id" : ObjectId("5e50ed01f8647eb59e562065"), "Scores" : [ 903, 10004, 84575, 844 ] } Following is the query for capped sub-collection in an array βˆ’ > db.demo319.aggregate([ ... { $project: {TwoScores: { $slice: [ "$Scores", 2 ] } } } ... ]) This will produce the following output βˆ’ { "_id" : ObjectId("5e50ecf6f8647eb59e562064"), "TwoScores" : [ 100, 345 ] } { "_id" : ObjectId("5e50ed01f8647eb59e562065"), "TwoScores" : [ 903, 10004 ] }
[ { "code": null, "e": 1230, "s": 1062, "text": "In MongoDB, you cannot use capped for sub-collection. However, use capped on the overall document. To display a specific number of values from an array, prefer $slice." }, { "code": null, "e": 1274, "s": 1230, "text": "Let us create a collection with documents βˆ’" }, { "code": null, "e": 1556, "s": 1274, "text": "> db.demo319.insertOne({\"Scores\":[100,345,980,890]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e50ecf6f8647eb59e562064\")\n}\n> db.demo319.insertOne({\"Scores\":[903,10004,84575,844]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e50ed01f8647eb59e562065\")\n}" }, { "code": null, "e": 1629, "s": 1556, "text": "Display all documents from a collection with the help of find() method βˆ’" }, { "code": null, "e": 1659, "s": 1629, "text": "> db.demo319.find().pretty();" }, { "code": null, "e": 1700, "s": 1659, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 1938, "s": 1700, "text": "{\n \"_id\" : ObjectId(\"5e50ecf6f8647eb59e562064\"),\n \"Scores\" : [\n 100,\n 345,\n 980,\n 890\n ]\n}\n{\n \"_id\" : ObjectId(\"5e50ed01f8647eb59e562065\"),\n \"Scores\" : [\n 903,\n 10004,\n 84575,\n 844\n ]\n}" }, { "code": null, "e": 2001, "s": 1938, "text": "Following is the query for capped sub-collection in an array βˆ’" }, { "code": null, "e": 2094, "s": 2001, "text": "> db.demo319.aggregate([\n... { $project: {TwoScores: { $slice: [ \"$Scores\", 2 ] } } }\n... ])" }, { "code": null, "e": 2135, "s": 2094, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2291, "s": 2135, "text": "{ \"_id\" : ObjectId(\"5e50ecf6f8647eb59e562064\"), \"TwoScores\" : [ 100, 345 ] }\n{ \"_id\" : ObjectId(\"5e50ed01f8647eb59e562065\"), \"TwoScores\" : [ 903, 10004 ] }" } ]
Functional Programming - Records
A record is a data structure for storing a fixed number of elements. It is similar to a structure in C language. At the time of compilation, its expressions are translated to tuple expressions. The keyword β€˜record’ is used to create records specified with record name and its fields. Its syntax is as follows βˆ’ record(recodname, {field1, field2, . . fieldn}) The syntax to insert values into the record is βˆ’ #recordname {fieldName1 = value1, fieldName2 = value2 .. fieldNamen = valuen} In the following example, we have created a record of name student having two fields, i.e., sname and sid. -module(helloworld). -export([start/0]). -record(student, {sname = "", sid}). start() -> S = #student{sname = "Sachin",sid = 5}. The following example shows how to create records using C++, which is an object-oriented programming language βˆ’ #include<iostream> #include<string> using namespace std; class student { public: string sname; int sid; 15 }; int main() { student S; S.sname = "Sachin"; S.sid = 5; return 0; } The following program shows how access record values using Erlang, which is a functional programming language βˆ’ -module(helloworld). -export([start/0]). -record(student, {sname = "", sid}). start() -> S = #student{sname = "Sachin",sid = 5}, io:fwrite("~p~n",[S#student.sid]), io:fwrite("~p~n",[S#student.sname]). It will produce the following output βˆ’ 5 "Sachin" The following program shows how to access record values using C++ βˆ’ #include<iostream> #include<string> using namespace std; class student { public: string sname; int sid; }; int main() { student S; S.sname = "Sachin"; S.sid = 5; cout<<S.sid<<"\n"<<S.sname; return 0; } It will produce the following output βˆ’ 5 Sachin The record values can be updated by changing the value to a particular field and then assigning that record to a new variable name. Take a look at the following two examples to understand how it is done using object-oriented and functional programming languages. The following program shows how to update record values using Erlang βˆ’ -module(helloworld). -export([start/0]). -record(student, {sname = "", sid}). start() -> S = #student{sname = "Sachin",sid = 5}, S1 = S#student{sname = "Jonny"}, io:fwrite("~p~n",[S1#student.sid]), io:fwrite("~p~n",[S1#student.sname]). It will produce the following output βˆ’ 5 "Jonny" The following program shows how to update record values using C++ βˆ’ #include<iostream> #include<string> using namespace std; class student { public: string sname; int sid; }; int main() { student S; S.sname = "Jonny"; S.sid = 5; cout<<S.sname<<"\n"<<S.sid; cout<<"\n"<< "value after updating"<<"\n"; S.sid = 10; cout<<S.sname<<"\n"<<S.sid; return 0; } It will produce the following output βˆ’ Jonny 5 value after updating Jonny 10 32 Lectures 3.5 hours Pavan Lalwani 11 Lectures 1 hours Prof. Paul Cline, Ed.D 72 Lectures 10.5 hours Arun Ammasai 51 Lectures 2 hours Skillbakerystudios 43 Lectures 4 hours Mohammad Nauman 8 Lectures 1 hours Santharam Sivalenka Print Add Notes Bookmark this page
[ { "code": null, "e": 2015, "s": 1821, "text": "A record is a data structure for storing a fixed number of elements. It is similar to a structure in C language. At the time of compilation, its expressions are translated to tuple expressions." }, { "code": null, "e": 2132, "s": 2015, "text": "The keyword β€˜record’ is used to create records specified with record name and its fields. Its syntax is as follows βˆ’" }, { "code": null, "e": 2181, "s": 2132, "text": "record(recodname, {field1, field2, . . fieldn})\n" }, { "code": null, "e": 2230, "s": 2181, "text": "The syntax to insert values into the record is βˆ’" }, { "code": null, "e": 2309, "s": 2230, "text": "#recordname {fieldName1 = value1, fieldName2 = value2 .. fieldNamen = valuen}\n" }, { "code": null, "e": 2416, "s": 2309, "text": "In the following example, we have created a record of name student having two fields, i.e., sname and sid." }, { "code": null, "e": 2559, "s": 2416, "text": "-module(helloworld). \n-export([start/0]). \n-record(student, {sname = \"\", sid}). \n\nstart() -> \n S = #student{sname = \"Sachin\",sid = 5}. " }, { "code": null, "e": 2671, "s": 2559, "text": "The following example shows how to create records using C++, which is an object-oriented programming language βˆ’" }, { "code": null, "e": 2892, "s": 2671, "text": "#include<iostream> \n#include<string>\nusing namespace std; \n\nclass student {\n public: \n string sname; \n int sid; \n 15 \n}; \n\nint main() { \n student S; \n S.sname = \"Sachin\"; \n S.sid = 5; \n return 0; \n} " }, { "code": null, "e": 3004, "s": 2892, "text": "The following program shows how access record values using Erlang, which is a functional programming language βˆ’" }, { "code": null, "e": 3229, "s": 3004, "text": "-module(helloworld). \n-export([start/0]). \n-record(student, {sname = \"\", sid}). \n\nstart() -> \n S = #student{sname = \"Sachin\",sid = 5}, \n io:fwrite(\"~p~n\",[S#student.sid]), \n io:fwrite(\"~p~n\",[S#student.sname]). " }, { "code": null, "e": 3268, "s": 3229, "text": "It will produce the following output βˆ’" }, { "code": null, "e": 3281, "s": 3268, "text": "5 \n\"Sachin\"\n" }, { "code": null, "e": 3349, "s": 3281, "text": "The following program shows how to access record values using C++ βˆ’" }, { "code": null, "e": 3602, "s": 3349, "text": "#include<iostream> \n#include<string> \nusing namespace std; \n\nclass student { \n public: \n string sname; \n int sid; \n}; \n\nint main() { \n student S; \n S.sname = \"Sachin\"; \n S.sid = 5; \n cout<<S.sid<<\"\\n\"<<S.sname; \n return 0; \n} " }, { "code": null, "e": 3641, "s": 3602, "text": "It will produce the following output βˆ’" }, { "code": null, "e": 3653, "s": 3641, "text": "5 \nSachin \n" }, { "code": null, "e": 3916, "s": 3653, "text": "The record values can be updated by changing the value to a particular field and then assigning that record to a new variable name. Take a look at the following two examples to understand how it is done using object-oriented and functional programming languages." }, { "code": null, "e": 3987, "s": 3916, "text": "The following program shows how to update record values using Erlang βˆ’" }, { "code": null, "e": 4252, "s": 3987, "text": "-module(helloworld). \n-export([start/0]). \n-record(student, {sname = \"\", sid}). \n\nstart() -> \n S = #student{sname = \"Sachin\",sid = 5}, \n S1 = S#student{sname = \"Jonny\"}, \n io:fwrite(\"~p~n\",[S1#student.sid]), \n io:fwrite(\"~p~n\",[S1#student.sname]). " }, { "code": null, "e": 4291, "s": 4252, "text": "It will produce the following output βˆ’" }, { "code": null, "e": 4303, "s": 4291, "text": "5\n\"Jonny\" \n" }, { "code": null, "e": 4371, "s": 4303, "text": "The following program shows how to update record values using C++ βˆ’" }, { "code": null, "e": 4717, "s": 4371, "text": "#include<iostream> \n#include<string> \nusing namespace std; \n\nclass student { \n public: \n string sname; \n int sid; \n}; \n\nint main() { \n student S; \n S.sname = \"Jonny\"; \n S.sid = 5; \n cout<<S.sname<<\"\\n\"<<S.sid; \n cout<<\"\\n\"<< \"value after updating\"<<\"\\n\"; \n S.sid = 10; \n cout<<S.sname<<\"\\n\"<<S.sid; \n return 0; \n}" }, { "code": null, "e": 4756, "s": 4717, "text": "It will produce the following output βˆ’" }, { "code": null, "e": 4800, "s": 4756, "text": "Jonny \n5 \nvalue after updating \nJonny \n10 \n" }, { "code": null, "e": 4835, "s": 4800, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4850, "s": 4835, "text": " Pavan Lalwani" }, { "code": null, "e": 4883, "s": 4850, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 4907, "s": 4883, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 4943, "s": 4907, "text": "\n 72 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4957, "s": 4943, "text": " Arun Ammasai" }, { "code": null, "e": 4990, "s": 4957, "text": "\n 51 Lectures \n 2 hours \n" }, { "code": null, "e": 5010, "s": 4990, "text": " Skillbakerystudios" }, { "code": null, "e": 5043, "s": 5010, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 5060, "s": 5043, "text": " Mohammad Nauman" }, { "code": null, "e": 5092, "s": 5060, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 5113, "s": 5092, "text": " Santharam Sivalenka" }, { "code": null, "e": 5120, "s": 5113, "text": " Print" }, { "code": null, "e": 5131, "s": 5120, "text": " Add Notes" } ]
Extract Tables from PDF file in a single line of Python Code | by Satyam Kumar | Towards Data Science
A standard principle in data science is that the presence of more data leads to training a better model. Data can be present in any format, data collection and data preparation is an important component of a model development pipeline. The required data for any case study can be present in any format, and it's the task of the data scientist to get the data into the desired format to proceed with the data preprocessing and other components of the pipeline. A lot of structured/semi-structured or unstructured data can be present in tabular format in text-based PDF documents and in image format. Developing a custom table extraction model requires a lot of time and effort. In this article, we will discuss how to use an open-source library Camelot, to extract all available tables from PDF documents in just one line of Python Code. Camelot is an open-source Python library, that enables developers to extract all tables from the PDF document and convert it to Pandas Dataframe format. The extracted table can also be exported in a structured form as CSV, JSON, Excel, or other formats, and can be used for modeling. Camelot has a limitation as it only works with text-based PDFs and not the scanned documents. Camelot uses two table parsing techniques, i.e Stream and Lattice to extract tables from PDF documents. One can choose between the two table parsing technique. Stream is a parsing technique that uses PDFMiner’s functionality to group characters into words or sentences based on white spaces or margins. Stream parsing techniques are like a guessing-based technique. Lattice is another parsing technique that does not rely on guessing but finds the horizontal and vertical lines in the table to parse over multiple tables in the PDF document. Lattice can only parse through the tables having demarcated lines between cells. Lattice Algorithm steps to find the tables in the PDF documents are: Convert the PDF document into Image using Ghostscript.OpenCV-based Morphological transformations are applied to get the horizontal and vertical line segments of the tables in the converted Image.Line Intersections are then detected by taking AND of line segments (from point 2) and tables pixel intensities.Tables borderline are detected by taking OR of line segments (from point 2) and their pixel intensities.Spanning cells or merged cells are detected by using the line intersection and line segments.The detected line segments and borderlines of the tables are then scaled and mapped to the PDF document, as the dimensions in the image and PDF may vary.After placing the line segments and borderlines of the tables in the appropriate (x, y) coordinates, words found on the cells of the table are detected and mapped to the data frame. Convert the PDF document into Image using Ghostscript. OpenCV-based Morphological transformations are applied to get the horizontal and vertical line segments of the tables in the converted Image. Line Intersections are then detected by taking AND of line segments (from point 2) and tables pixel intensities. Tables borderline are detected by taking OR of line segments (from point 2) and their pixel intensities. Spanning cells or merged cells are detected by using the line intersection and line segments. The detected line segments and borderlines of the tables are then scaled and mapped to the PDF document, as the dimensions in the image and PDF may vary. After placing the line segments and borderlines of the tables in the appropriate (x, y) coordinates, words found on the cells of the table are detected and mapped to the data frame. To visualize each of the above steps, follow the Advanced Usage documentation page of Camelot. Camelot and Ghostscript can be installed from PyPl using the command: !pip install "camelot-py[cv]"!apt install python3-tk ghostscript After installation, Camelot can be imported using: import camelot After importing the necessary modules, read the PDF file using camelot.read_pdf() function. tables = camelot.read_pdf('table.pdf') By default Camelot, only parses through the first page of the pdf document, to parse through the tables present in multiple pages of the document, use pages parameter in read_pdf function. # pass comma seperated page numbers or page rangestables = camelot.read_pdf('table.pdf', pages='1,2,3,5-7,8') Camelot can also extract tables from the password-protected PDF document, just bypassing the required password. tables = camelot.read_pdf('table.pdf', password='*******') camelot.read_pdf is the only single line of Python code, required to extract all tables from the PDF file. All the tables are now extracted in Tablelist format and can be accessed by its index. #Access the ith table as Pandas Data frametables[i].df To export the table to the desired format, you can use camelot.export() function, and use parameter f=’csv’, f=’excel’, f=’html’, or f=’sqlite’ . tables.export('name.csv', f='csv') To get the parsing report or metric report about how well the data is extracted tables[i].parsing_report# Output: {'accuracy': 99.27, 'order': 1, 'page': 1, 'whitespace': 13.89} The PDF document used in the below illustration is downloaded from Table, Table1. !apt install python3-tk ghostscript !pip install "camelot-py[cv]" import camelot tables = camelot.read_pdf('table.pdf') tables <TableList n=1> tables[0].parsing_report {'accuracy': 99.27, 'order': 1, 'page': 1, 'whitespace': 13.89} tables[0].df tables1 = camelot.read_pdf('table1.pdf') tables1 <TableList n=2> tables1[0].parsing_report {'accuracy': 100.0, 'order': 1, 'page': 1, 'whitespace': 0.0} tables1[0].df tables1[1].df In this article, we have discussed how to extract tables from PDF documents and convert them to Pandas Dataframe which can be further used for modeling. There are various open-source libraries including Tabula, pdftables, pdf-table-extract, pdfplumber that provide similar functionality as Camelot. Camelot works better than its alternatives, read this article to get a comparison of results between Camelot and its competitor's libraries. [1] Camelot Documentation: https://camelot-py.readthedocs.io/en/master/ Thank You for Reading
[ { "code": null, "e": 632, "s": 172, "text": "A standard principle in data science is that the presence of more data leads to training a better model. Data can be present in any format, data collection and data preparation is an important component of a model development pipeline. The required data for any case study can be present in any format, and it's the task of the data scientist to get the data into the desired format to proceed with the data preprocessing and other components of the pipeline." }, { "code": null, "e": 1009, "s": 632, "text": "A lot of structured/semi-structured or unstructured data can be present in tabular format in text-based PDF documents and in image format. Developing a custom table extraction model requires a lot of time and effort. In this article, we will discuss how to use an open-source library Camelot, to extract all available tables from PDF documents in just one line of Python Code." }, { "code": null, "e": 1293, "s": 1009, "text": "Camelot is an open-source Python library, that enables developers to extract all tables from the PDF document and convert it to Pandas Dataframe format. The extracted table can also be exported in a structured form as CSV, JSON, Excel, or other formats, and can be used for modeling." }, { "code": null, "e": 1387, "s": 1293, "text": "Camelot has a limitation as it only works with text-based PDFs and not the scanned documents." }, { "code": null, "e": 1547, "s": 1387, "text": "Camelot uses two table parsing techniques, i.e Stream and Lattice to extract tables from PDF documents. One can choose between the two table parsing technique." }, { "code": null, "e": 1753, "s": 1547, "text": "Stream is a parsing technique that uses PDFMiner’s functionality to group characters into words or sentences based on white spaces or margins. Stream parsing techniques are like a guessing-based technique." }, { "code": null, "e": 2079, "s": 1753, "text": "Lattice is another parsing technique that does not rely on guessing but finds the horizontal and vertical lines in the table to parse over multiple tables in the PDF document. Lattice can only parse through the tables having demarcated lines between cells. Lattice Algorithm steps to find the tables in the PDF documents are:" }, { "code": null, "e": 2918, "s": 2079, "text": "Convert the PDF document into Image using Ghostscript.OpenCV-based Morphological transformations are applied to get the horizontal and vertical line segments of the tables in the converted Image.Line Intersections are then detected by taking AND of line segments (from point 2) and tables pixel intensities.Tables borderline are detected by taking OR of line segments (from point 2) and their pixel intensities.Spanning cells or merged cells are detected by using the line intersection and line segments.The detected line segments and borderlines of the tables are then scaled and mapped to the PDF document, as the dimensions in the image and PDF may vary.After placing the line segments and borderlines of the tables in the appropriate (x, y) coordinates, words found on the cells of the table are detected and mapped to the data frame." }, { "code": null, "e": 2973, "s": 2918, "text": "Convert the PDF document into Image using Ghostscript." }, { "code": null, "e": 3115, "s": 2973, "text": "OpenCV-based Morphological transformations are applied to get the horizontal and vertical line segments of the tables in the converted Image." }, { "code": null, "e": 3228, "s": 3115, "text": "Line Intersections are then detected by taking AND of line segments (from point 2) and tables pixel intensities." }, { "code": null, "e": 3333, "s": 3228, "text": "Tables borderline are detected by taking OR of line segments (from point 2) and their pixel intensities." }, { "code": null, "e": 3427, "s": 3333, "text": "Spanning cells or merged cells are detected by using the line intersection and line segments." }, { "code": null, "e": 3581, "s": 3427, "text": "The detected line segments and borderlines of the tables are then scaled and mapped to the PDF document, as the dimensions in the image and PDF may vary." }, { "code": null, "e": 3763, "s": 3581, "text": "After placing the line segments and borderlines of the tables in the appropriate (x, y) coordinates, words found on the cells of the table are detected and mapped to the data frame." }, { "code": null, "e": 3858, "s": 3763, "text": "To visualize each of the above steps, follow the Advanced Usage documentation page of Camelot." }, { "code": null, "e": 3928, "s": 3858, "text": "Camelot and Ghostscript can be installed from PyPl using the command:" }, { "code": null, "e": 3993, "s": 3928, "text": "!pip install \"camelot-py[cv]\"!apt install python3-tk ghostscript" }, { "code": null, "e": 4044, "s": 3993, "text": "After installation, Camelot can be imported using:" }, { "code": null, "e": 4059, "s": 4044, "text": "import camelot" }, { "code": null, "e": 4151, "s": 4059, "text": "After importing the necessary modules, read the PDF file using camelot.read_pdf() function." }, { "code": null, "e": 4190, "s": 4151, "text": "tables = camelot.read_pdf('table.pdf')" }, { "code": null, "e": 4379, "s": 4190, "text": "By default Camelot, only parses through the first page of the pdf document, to parse through the tables present in multiple pages of the document, use pages parameter in read_pdf function." }, { "code": null, "e": 4489, "s": 4379, "text": "# pass comma seperated page numbers or page rangestables = camelot.read_pdf('table.pdf', pages='1,2,3,5-7,8')" }, { "code": null, "e": 4601, "s": 4489, "text": "Camelot can also extract tables from the password-protected PDF document, just bypassing the required password." }, { "code": null, "e": 4660, "s": 4601, "text": "tables = camelot.read_pdf('table.pdf', password='*******')" }, { "code": null, "e": 4854, "s": 4660, "text": "camelot.read_pdf is the only single line of Python code, required to extract all tables from the PDF file. All the tables are now extracted in Tablelist format and can be accessed by its index." }, { "code": null, "e": 4909, "s": 4854, "text": "#Access the ith table as Pandas Data frametables[i].df" }, { "code": null, "e": 5055, "s": 4909, "text": "To export the table to the desired format, you can use camelot.export() function, and use parameter f=’csv’, f=’excel’, f=’html’, or f=’sqlite’ ." }, { "code": null, "e": 5090, "s": 5055, "text": "tables.export('name.csv', f='csv')" }, { "code": null, "e": 5170, "s": 5090, "text": "To get the parsing report or metric report about how well the data is extracted" }, { "code": null, "e": 5268, "s": 5170, "text": "tables[i].parsing_report# Output: {'accuracy': 99.27, 'order': 1, 'page': 1, 'whitespace': 13.89}" }, { "code": null, "e": 5350, "s": 5268, "text": "The PDF document used in the below illustration is downloaded from Table, Table1." }, { "code": null, "e": 5432, "s": 5350, "text": "!apt install python3-tk ghostscript\n!pip install \"camelot-py[cv]\"\nimport camelot\n" }, { "code": null, "e": 5479, "s": 5432, "text": "tables = camelot.read_pdf('table.pdf')\ntables\n" }, { "code": null, "e": 5495, "s": 5479, "text": "<TableList n=1>" }, { "code": null, "e": 5521, "s": 5495, "text": "tables[0].parsing_report\n" }, { "code": null, "e": 5585, "s": 5521, "text": "{'accuracy': 99.27, 'order': 1, 'page': 1, 'whitespace': 13.89}" }, { "code": null, "e": 5599, "s": 5585, "text": "tables[0].df\n" }, { "code": null, "e": 5649, "s": 5599, "text": "tables1 = camelot.read_pdf('table1.pdf')\ntables1\n" }, { "code": null, "e": 5665, "s": 5649, "text": "<TableList n=2>" }, { "code": null, "e": 5692, "s": 5665, "text": "tables1[0].parsing_report\n" }, { "code": null, "e": 5754, "s": 5692, "text": "{'accuracy': 100.0, 'order': 1, 'page': 1, 'whitespace': 0.0}" }, { "code": null, "e": 5769, "s": 5754, "text": "tables1[0].df\n" }, { "code": null, "e": 5784, "s": 5769, "text": "tables1[1].df\n" }, { "code": null, "e": 6085, "s": 5786, "text": "In this article, we have discussed how to extract tables from PDF documents and convert them to Pandas Dataframe which can be further used for modeling. There are various open-source libraries including Tabula, pdftables, pdf-table-extract, pdfplumber that provide similar functionality as Camelot." }, { "code": null, "e": 6226, "s": 6085, "text": "Camelot works better than its alternatives, read this article to get a comparison of results between Camelot and its competitor's libraries." }, { "code": null, "e": 6298, "s": 6226, "text": "[1] Camelot Documentation: https://camelot-py.readthedocs.io/en/master/" } ]
Perl - Extracting Date from a String using Regex - GeeksforGeeks
14 Dec, 2020 In Perl generally, we have to read CSV (Comma Separated Values) files to extract the required data. Sometimes there are dates in the file name like sample 2014-02-12T11:10:10.csv or there could be a column in a file that has a date in it. These dates can be of any pattern like YYYY-MM-DDThh:mm:ss or dd/mm/yyyy hh.mm.ss. To handle those dates; the Perl scripts should be flexible enough to handle different types of date formats in a string. We need to use regular expression feature for extracting dates from a string. A regular expression is a string of characters that defines the specific pattern or patterns you are viewing. The basic method for applying a regular expression is to use the pattern binding operators =~ and !~. In Perl there are multiple libraries available for handling date and time such as Date::Parse and Time::Piece; both of these libraries come with lots of flexible functions to handle the more complex requirement. But these libraries are not part of standard Perl modules you need to install them separately. For general date formats its good to find specific regular expressions without installing any new library. Let’s go through some examples of parsing a date from a string in Perl. Before we look at examples for extracting date from a string we should look at these metasymbols that are used in parsing an expression in a string: Here are some brief examples. There is no separate module required for regular expression. Its in-built in Perl (any version). So you should have Perl (any version) installed on your system. We will see some examples to extract date, in a different format, from a string using Perl regex. Example 1: In this example we will see how to extract date with pattern, yyyy-mm-ddThh:mm:ss, from a string in Perl. The below example 1 shows a string sample2018-03-21T12:10:10.csv from which we need to extract the date in year, month and date variables to make it usable for further script. Here, the regex \d\d\d\d ensures that the date pattern in the string should start with the pattern of 4 digits. If not then it can throw an Uninitialized variable exception because of missing pattern in the string. What does /d?/d mean? This pattern ensures that month, day, hours, minutes and seconds could be in 1 digit or 2 digits. For example: 2013-9-21T11:3:30 2014-12-3T9:1:10 So /d?/d will ensure that the expression left to ? is optional and it will execute without any error. Perl #!/usr/bin/perl# your code heremy $str = "sample2018-03-21T12:10:10.csv";my (($year, $month, $day, $hour, $min, $sec) = $str =~ /(\d\d\d\d)-(\d?\d)-(\d?\d)T(\d?\d):(\d?\d):(\d?\d)/);print "year : $year month:$month day:$day - hour:$hour minute:$min seconds:$sec\n"; Output: year : 2018 month:03 day:21 - hour:12 minute:10 seconds:10 Example 2: In this example, we will see how to extract date with Pattern mm/dd/yyyy hh.mm.ss from a string. The date can be a part of filename or it could be a content. So the following example will help in parsing the date with format mm/dd/yyyy hh:mm:ss from a string. In this example we have taken a string test_28/04/2017 11.00.00 ; where date starts with 2 digits 28 followed by back-slash / Here, (\d?\d) regex ensures that the string will start with the pattern with 2 or 1 digit followed by /. The back-slash \ is put in-front of the . to make sure it only matches dots and not every character as it usually does. Perl #!/usr/bin/perl# your code heremy $str1 = "test_28/04/2017 11.00.00";my (($month1, $day1, $year1, $hour1, $min1, $sec1) = $str1 =~ m{(\d?\d)/(\d?\d)/(\d\d\d\d) (\d\d)\.(\d\d)\.(\d\d)}); print "year:$year1 month:$month1 day:$day1 - hour:$hour1 minute:$min1 seconds:$sec1\n"; Output: year:2017 month:28 day:04 - hour:11 minute:00 seconds:00 Example 3: Here we will see one more date pattern that’s {Day}, dd {mon} yyyy hh:mm:ss like Tue,11 Feb 2014 11:01:54 +0100 (CET); Sometimes CSV files have date column value in an above format that’s not readable for Perl operations, so we want to extract year, month and date from this format and use that as required. Here, .+?(\d+) regex means there would be some characters before the date digits 11, after that \s(.+?) regex means date is followed by a space and string of characters that’s Feb, s(\d+)/ regex ensures that 11 Feb is followed by a space and multiple digits that’s 2014. We save these values in the variables defined for day, month and year; that can be used in the further script. Perl #!/usr/bin/perl# your code heremy $string = 'Date: Tue, 11 Feb 2014 11:01:57 +0100 (CET)';my ($day3, $month3, $year3) = $string =~ /Date:.+?(\d+)\s(.+?)\s(\d+)/;print "Day:$day3 month:$month3 year:$year3\n"; Output: Day:11 month:Feb year:2014 Perl-regex Picked Technical Scripter 2020 Perl Technical Scripter Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl Tutorial - Learn Perl With Examples Perl | Basic Syntax of a Perl Program Perl | Inheritance in OOPs Perl | Opening and Reading a File Perl | Multidimensional Hashes Perl | ne operator Perl | Scope of Variables Perl | Hashes Perl | Data Types Perl | defined() Function
[ { "code": null, "e": 25315, "s": 25287, "text": "\n14 Dec, 2020" }, { "code": null, "e": 26049, "s": 25315, "text": "In Perl generally, we have to read CSV (Comma Separated Values) files to extract the required data. Sometimes there are dates in the file name like sample 2014-02-12T11:10:10.csv or there could be a column in a file that has a date in it. These dates can be of any pattern like YYYY-MM-DDThh:mm:ss or dd/mm/yyyy hh.mm.ss. To handle those dates; the Perl scripts should be flexible enough to handle different types of date formats in a string. We need to use regular expression feature for extracting dates from a string. A regular expression is a string of characters that defines the specific pattern or patterns you are viewing. The basic method for applying a regular expression is to use the pattern binding operators =~ and !~. " }, { "code": null, "e": 26356, "s": 26049, "text": "In Perl there are multiple libraries available for handling date and time such as Date::Parse and Time::Piece; both of these libraries come with lots of flexible functions to handle the more complex requirement. But these libraries are not part of standard Perl modules you need to install them separately." }, { "code": null, "e": 26535, "s": 26356, "text": "For general date formats its good to find specific regular expressions without installing any new library. Let’s go through some examples of parsing a date from a string in Perl." }, { "code": null, "e": 26684, "s": 26535, "text": "Before we look at examples for extracting date from a string we should look at these metasymbols that are used in parsing an expression in a string:" }, { "code": null, "e": 26714, "s": 26684, "text": "Here are some brief examples." }, { "code": null, "e": 26973, "s": 26714, "text": "There is no separate module required for regular expression. Its in-built in Perl (any version). So you should have Perl (any version) installed on your system. We will see some examples to extract date, in a different format, from a string using Perl regex." }, { "code": null, "e": 26984, "s": 26973, "text": "Example 1:" }, { "code": null, "e": 27267, "s": 26984, "text": "In this example we will see how to extract date with pattern, yyyy-mm-ddThh:mm:ss, from a string in Perl. The below example 1 shows a string sample2018-03-21T12:10:10.csv from which we need to extract the date in year, month and date variables to make it usable for further script. " }, { "code": null, "e": 27482, "s": 27267, "text": "Here, the regex \\d\\d\\d\\d ensures that the date pattern in the string should start with the pattern of 4 digits. If not then it can throw an Uninitialized variable exception because of missing pattern in the string." }, { "code": null, "e": 27603, "s": 27482, "text": "What does /d?/d mean? This pattern ensures that month, day, hours, minutes and seconds could be in 1 digit or 2 digits. " }, { "code": null, "e": 27619, "s": 27603, "text": "For example: " }, { "code": null, "e": 27637, "s": 27619, "text": "2013-9-21T11:3:30" }, { "code": null, "e": 27654, "s": 27637, "text": "2014-12-3T9:1:10" }, { "code": null, "e": 27756, "s": 27654, "text": "So /d?/d will ensure that the expression left to ? is optional and it will execute without any error." }, { "code": null, "e": 27761, "s": 27756, "text": "Perl" }, { "code": "#!/usr/bin/perl# your code heremy $str = \"sample2018-03-21T12:10:10.csv\";my (($year, $month, $day, $hour, $min, $sec) = $str =~ /(\\d\\d\\d\\d)-(\\d?\\d)-(\\d?\\d)T(\\d?\\d):(\\d?\\d):(\\d?\\d)/);print \"year : $year month:$month day:$day - hour:$hour minute:$min seconds:$sec\\n\";", "e": 28036, "s": 27761, "text": null }, { "code": null, "e": 28044, "s": 28036, "text": "Output:" }, { "code": null, "e": 28107, "s": 28044, "text": "year : 2018 month:03 day:21 - hour:12 minute:10 seconds:10" }, { "code": null, "e": 28118, "s": 28107, "text": "Example 2:" }, { "code": null, "e": 28505, "s": 28118, "text": "In this example, we will see how to extract date with Pattern mm/dd/yyyy hh.mm.ss from a string. The date can be a part of filename or it could be a content. So the following example will help in parsing the date with format mm/dd/yyyy hh:mm:ss from a string. In this example we have taken a string test_28/04/2017 11.00.00 ; where date starts with 2 digits 28 followed by back-slash / " }, { "code": null, "e": 28730, "s": 28505, "text": "Here, (\\d?\\d) regex ensures that the string will start with the pattern with 2 or 1 digit followed by /. The back-slash \\ is put in-front of the . to make sure it only matches dots and not every character as it usually does." }, { "code": null, "e": 28735, "s": 28730, "text": "Perl" }, { "code": "#!/usr/bin/perl# your code heremy $str1 = \"test_28/04/2017 11.00.00\";my (($month1, $day1, $year1, $hour1, $min1, $sec1) = $str1 =~ m{(\\d?\\d)/(\\d?\\d)/(\\d\\d\\d\\d) (\\d\\d)\\.(\\d\\d)\\.(\\d\\d)}); print \"year:$year1 month:$month1 day:$day1 - hour:$hour1 minute:$min1 seconds:$sec1\\n\";", "e": 29018, "s": 28735, "text": null }, { "code": null, "e": 29026, "s": 29018, "text": "Output:" }, { "code": null, "e": 29087, "s": 29026, "text": "year:2017 month:28 day:04 - hour:11 minute:00 seconds:00" }, { "code": null, "e": 29098, "s": 29087, "text": "Example 3:" }, { "code": null, "e": 29408, "s": 29098, "text": "Here we will see one more date pattern that’s {Day}, dd {mon} yyyy hh:mm:ss like Tue,11 Feb 2014 11:01:54 +0100 (CET); Sometimes CSV files have date column value in an above format that’s not readable for Perl operations, so we want to extract year, month and date from this format and use that as required. " }, { "code": null, "e": 29790, "s": 29408, "text": "Here, .+?(\\d+) regex means there would be some characters before the date digits 11, after that \\s(.+?) regex means date is followed by a space and string of characters that’s Feb, s(\\d+)/ regex ensures that 11 Feb is followed by a space and multiple digits that’s 2014. We save these values in the variables defined for day, month and year; that can be used in the further script." }, { "code": null, "e": 29795, "s": 29790, "text": "Perl" }, { "code": "#!/usr/bin/perl# your code heremy $string = 'Date: Tue, 11 Feb 2014 11:01:57 +0100 (CET)';my ($day3, $month3, $year3) = $string =~ /Date:.+?(\\d+)\\s(.+?)\\s(\\d+)/;print \"Day:$day3 month:$month3 year:$year3\\n\";", "e": 30003, "s": 29795, "text": null }, { "code": null, "e": 30011, "s": 30003, "text": "Output:" }, { "code": null, "e": 30038, "s": 30011, "text": "Day:11 month:Feb year:2014" }, { "code": null, "e": 30049, "s": 30038, "text": "Perl-regex" }, { "code": null, "e": 30056, "s": 30049, "text": "Picked" }, { "code": null, "e": 30080, "s": 30056, "text": "Technical Scripter 2020" }, { "code": null, "e": 30085, "s": 30080, "text": "Perl" }, { "code": null, "e": 30104, "s": 30085, "text": "Technical Scripter" }, { "code": null, "e": 30109, "s": 30104, "text": "Perl" }, { "code": null, "e": 30207, "s": 30109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30248, "s": 30207, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 30286, "s": 30248, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 30313, "s": 30286, "text": "Perl | Inheritance in OOPs" }, { "code": null, "e": 30347, "s": 30313, "text": "Perl | Opening and Reading a File" }, { "code": null, "e": 30378, "s": 30347, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 30397, "s": 30378, "text": "Perl | ne operator" }, { "code": null, "e": 30423, "s": 30397, "text": "Perl | Scope of Variables" }, { "code": null, "e": 30437, "s": 30423, "text": "Perl | Hashes" }, { "code": null, "e": 30455, "s": 30437, "text": "Perl | Data Types" } ]
How to add border to an element on mouse hover using CSS ? - GeeksforGeeks
14 Dec, 2020 We have given a web page containing elements and the task is to add border to an element on mouse move over (hover) using CSS. When we add a border to an element on hovering the mouse, it affects the position of the other nearest element. To remove this problem, we can use the CSS margin property. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title> Add CSS Border on Mouse Hover without Pushing Content </title> <style> ul { padding: 0; list-style: none; } ul li { float: left; margin: 10px; } ul ul li { display: block; } ul li:hover { border: 5px solid green; overflow: hidden; } ul ul li:hover img { margin: -5px; } </style></head> <body> <h2>GeeksForGeeks</h2> <h2> How to apply border to an element on mouse hover without affecting the layout in CSS? </h2> <ul> <li>Home</li> <li>news</li> <li>Images</li> <li>Music</li> </ul></body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction) Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 26167, "s": 26139, "text": "\n14 Dec, 2020" }, { "code": null, "e": 26466, "s": 26167, "text": "We have given a web page containing elements and the task is to add border to an element on mouse move over (hover) using CSS. When we add a border to an element on hovering the mouse, it affects the position of the other nearest element. To remove this problem, we can use the CSS margin property." }, { "code": null, "e": 26478, "s": 26466, "text": "Example: " }, { "code": null, "e": 26483, "s": 26478, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title> Add CSS Border on Mouse Hover without Pushing Content </title> <style> ul { padding: 0; list-style: none; } ul li { float: left; margin: 10px; } ul ul li { display: block; } ul li:hover { border: 5px solid green; overflow: hidden; } ul ul li:hover img { margin: -5px; } </style></head> <body> <h2>GeeksForGeeks</h2> <h2> How to apply border to an element on mouse hover without affecting the layout in CSS? </h2> <ul> <li>Home</li> <li>news</li> <li>Images</li> <li>Music</li> </ul></body> </html>", "e": 27336, "s": 26483, "text": null }, { "code": null, "e": 27344, "s": 27336, "text": "Output:" }, { "code": null, "e": 27364, "s": 27344, "text": "Supported Browsers:" }, { "code": null, "e": 27378, "s": 27364, "text": "Google Chrome" }, { "code": null, "e": 27396, "s": 27378, "text": "Internet Explorer" }, { "code": null, "e": 27404, "s": 27396, "text": "Firefox" }, { "code": null, "e": 27411, "s": 27404, "text": "Safari" }, { "code": null, "e": 27417, "s": 27411, "text": "Opera" }, { "code": null, "e": 27558, "s": 27421, "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": 27567, "s": 27558, "text": "CSS-Misc" }, { "code": null, "e": 27577, "s": 27567, "text": "HTML-Misc" }, { "code": null, "e": 27581, "s": 27577, "text": "CSS" }, { "code": null, "e": 27586, "s": 27581, "text": "HTML" }, { "code": null, "e": 27603, "s": 27586, "text": "Web Technologies" }, { "code": null, "e": 27630, "s": 27603, "text": "Web technologies Questions" }, { "code": null, "e": 27635, "s": 27630, "text": "HTML" }, { "code": null, "e": 27733, "s": 27635, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27788, "s": 27733, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 27825, "s": 27788, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27889, "s": 27825, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27926, "s": 27889, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27987, "s": 27926, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28047, "s": 27987, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28100, "s": 28047, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28150, "s": 28100, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28174, "s": 28150, "text": "REST API (Introduction)" } ]
Unformatted input/output operations In C++ - GeeksforGeeks
11 Nov, 2021 In this article, we will discuss the unformatted Input/Output operations In C++. Using objects cin and cout for the input and the output of data of various types is possible because of overloading of operator >> and << to recognize all the basic C++ types. The operator >> is overloaded in the istream class and operator << is overloaded in the ostream class. The general format for reading data from the keyboard: cin >> var1 >> var2 >> .... >> var_n; Here, var1, var2, ......, varn are the variable names that are declared already. The input data must be separated by white space characters and the data type of user input must be similar to the data types of the variables which are declared in the program. The operator >> reads the data character by character and assigns it to the indicated location. Reading of variables terminates when white space occurs or character type occurs that does not match the destination type. Program 1: C++ // C++ program to illustrate the// input and output of the data// entered by user#include <iostream>using namespace std; // Driver Codeint main(){ int data; char val; // Input the data cin >> data; cin >> val; // Print the data cout << data << " " << val; return 0;} Output: Explanation: In the above program, 123 is stored in the variable val of integer, and B is passed to the next cin object and stored in the data variable of character. The class istream and ostream have predefined functions get() and put(), to handle single character input and output operations. The function get() can be used in two ways, such as get(char*) and get(void) to fetch characters including blank spaces, newline characters, and tab. The function get(char*) assigns the value to a variable and get(void) to return the value of the character. Syntax: char data; // get() return the character value and assign to data variabledata = cin.get(); // Display the value stored in data variablecout.put(data); Example: char c; // directly assign value to c cin.get(c); // Display the value stored in c variablecout.put() Program 2: C++ // C++ program to illustrate the// input and output of data using// get() and puts()#include <iostream>using namespace std; // Driver Codeint main(){ char data; int count = 0; cout << "Enter Data: "; // Get the data cin.get(data); while (data != '\n') { // Print the data cout.put(data); count++; // Get the data again cin.get(data); } return 0;} Output: In C++, the function getline() and write() provide a more efficient way to handle line-oriented inputs and outputs. getline() function reads the complete line of text that ends with the new line character. This function can be invoked using the cin object. Syntax: cin.getline(variable_to_store_line, size); The reading is terminated by the β€˜\n’ (newline) character. The new character is read by the function, but it does not display it, instead, it is replaced with a NULL character. After reading a particular string the cin automatically adds the newline character at end of the string. The write() function displays the entire line in one go and its syntax is similar to the getline() function only that here cout object is used to invoke it. Syntax: cout.write(variable_to_store_line, size); The key point to remember is that the write() function does not stop displaying the string automatically when a NULL character occurs. If the size is greater than the length of the line then, the write() function displays beyond the bound of the line. Program 3: C++ // C++ program to illustrate the// input and output of file using// getline() and write() function#include <iostream>#include <string>using namespace std; // Driver Codeint main(){ char line[100]; // Get the input cin.getline(line, 10); // Print the data cout.write(line, 5); cout << endl; // Print the data cout.write(line, 20); cout << endl; return 0;} Output: kashishsoda ak14aman C++-Operator Overloading cpp-input-output cpp-operator cpp-operator-overloading Operators C++ C++ Programs cpp-operator Operators CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 25367, "s": 25339, "text": "\n11 Nov, 2021" }, { "code": null, "e": 25727, "s": 25367, "text": "In this article, we will discuss the unformatted Input/Output operations In C++. Using objects cin and cout for the input and the output of data of various types is possible because of overloading of operator >> and << to recognize all the basic C++ types. The operator >> is overloaded in the istream class and operator << is overloaded in the ostream class." }, { "code": null, "e": 25782, "s": 25727, "text": "The general format for reading data from the keyboard:" }, { "code": null, "e": 25820, "s": 25782, "text": "cin >> var1 >> var2 >> .... >> var_n;" }, { "code": null, "e": 25901, "s": 25820, "text": "Here, var1, var2, ......, varn are the variable names that are declared already." }, { "code": null, "e": 26078, "s": 25901, "text": "The input data must be separated by white space characters and the data type of user input must be similar to the data types of the variables which are declared in the program." }, { "code": null, "e": 26174, "s": 26078, "text": "The operator >> reads the data character by character and assigns it to the indicated location." }, { "code": null, "e": 26297, "s": 26174, "text": "Reading of variables terminates when white space occurs or character type occurs that does not match the destination type." }, { "code": null, "e": 26308, "s": 26297, "text": "Program 1:" }, { "code": null, "e": 26312, "s": 26308, "text": "C++" }, { "code": "// C++ program to illustrate the// input and output of the data// entered by user#include <iostream>using namespace std; // Driver Codeint main(){ int data; char val; // Input the data cin >> data; cin >> val; // Print the data cout << data << \" \" << val; return 0;}", "e": 26608, "s": 26312, "text": null }, { "code": null, "e": 26617, "s": 26608, "text": "Output: " }, { "code": null, "e": 26784, "s": 26617, "text": "Explanation: In the above program, 123 is stored in the variable val of integer, and B is passed to the next cin object and stored in the data variable of character. " }, { "code": null, "e": 27171, "s": 26784, "text": "The class istream and ostream have predefined functions get() and put(), to handle single character input and output operations. The function get() can be used in two ways, such as get(char*) and get(void) to fetch characters including blank spaces, newline characters, and tab. The function get(char*) assigns the value to a variable and get(void) to return the value of the character." }, { "code": null, "e": 27180, "s": 27171, "text": "Syntax: " }, { "code": null, "e": 27191, "s": 27180, "text": "char data;" }, { "code": null, "e": 27272, "s": 27191, "text": "// get() return the character value and assign to data variabledata = cin.get();" }, { "code": null, "e": 27333, "s": 27272, "text": "// Display the value stored in data variablecout.put(data); " }, { "code": null, "e": 27343, "s": 27333, "text": "Example: " }, { "code": null, "e": 27351, "s": 27343, "text": "char c;" }, { "code": null, "e": 27394, "s": 27351, "text": "// directly assign value to c cin.get(c); " }, { "code": null, "e": 27446, "s": 27394, "text": "// Display the value stored in c variablecout.put()" }, { "code": null, "e": 27458, "s": 27446, "text": "Program 2: " }, { "code": null, "e": 27462, "s": 27458, "text": "C++" }, { "code": "// C++ program to illustrate the// input and output of data using// get() and puts()#include <iostream>using namespace std; // Driver Codeint main(){ char data; int count = 0; cout << \"Enter Data: \"; // Get the data cin.get(data); while (data != '\\n') { // Print the data cout.put(data); count++; // Get the data again cin.get(data); } return 0;}", "e": 27873, "s": 27462, "text": null }, { "code": null, "e": 27881, "s": 27873, "text": "Output:" }, { "code": null, "e": 28138, "s": 27881, "text": "In C++, the function getline() and write() provide a more efficient way to handle line-oriented inputs and outputs. getline() function reads the complete line of text that ends with the new line character. This function can be invoked using the cin object." }, { "code": null, "e": 28146, "s": 28138, "text": "Syntax:" }, { "code": null, "e": 28189, "s": 28146, "text": "cin.getline(variable_to_store_line, size);" }, { "code": null, "e": 28471, "s": 28189, "text": "The reading is terminated by the β€˜\\n’ (newline) character. The new character is read by the function, but it does not display it, instead, it is replaced with a NULL character. After reading a particular string the cin automatically adds the newline character at end of the string." }, { "code": null, "e": 28628, "s": 28471, "text": "The write() function displays the entire line in one go and its syntax is similar to the getline() function only that here cout object is used to invoke it." }, { "code": null, "e": 28636, "s": 28628, "text": "Syntax:" }, { "code": null, "e": 28678, "s": 28636, "text": "cout.write(variable_to_store_line, size);" }, { "code": null, "e": 28930, "s": 28678, "text": "The key point to remember is that the write() function does not stop displaying the string automatically when a NULL character occurs. If the size is greater than the length of the line then, the write() function displays beyond the bound of the line." }, { "code": null, "e": 28941, "s": 28930, "text": "Program 3:" }, { "code": null, "e": 28945, "s": 28941, "text": "C++" }, { "code": "// C++ program to illustrate the// input and output of file using// getline() and write() function#include <iostream>#include <string>using namespace std; // Driver Codeint main(){ char line[100]; // Get the input cin.getline(line, 10); // Print the data cout.write(line, 5); cout << endl; // Print the data cout.write(line, 20); cout << endl; return 0;}", "e": 29335, "s": 28945, "text": null }, { "code": null, "e": 29344, "s": 29335, "text": "Output: " }, { "code": null, "e": 29358, "s": 29346, "text": "kashishsoda" }, { "code": null, "e": 29367, "s": 29358, "text": "ak14aman" }, { "code": null, "e": 29392, "s": 29367, "text": "C++-Operator Overloading" }, { "code": null, "e": 29409, "s": 29392, "text": "cpp-input-output" }, { "code": null, "e": 29422, "s": 29409, "text": "cpp-operator" }, { "code": null, "e": 29447, "s": 29422, "text": "cpp-operator-overloading" }, { "code": null, "e": 29457, "s": 29447, "text": "Operators" }, { "code": null, "e": 29461, "s": 29457, "text": "C++" }, { "code": null, "e": 29474, "s": 29461, "text": "C++ Programs" }, { "code": null, "e": 29487, "s": 29474, "text": "cpp-operator" }, { "code": null, "e": 29497, "s": 29487, "text": "Operators" }, { "code": null, "e": 29501, "s": 29497, "text": "CPP" }, { "code": null, "e": 29599, "s": 29501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29627, "s": 29599, "text": "Operator Overloading in C++" }, { "code": null, "e": 29647, "s": 29627, "text": "Polymorphism in C++" }, { "code": null, "e": 29671, "s": 29647, "text": "Sorting a vector in C++" }, { "code": null, "e": 29704, "s": 29671, "text": "Friend class and function in C++" }, { "code": null, "e": 29729, "s": 29704, "text": "std::string class in C++" }, { "code": null, "e": 29764, "s": 29729, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 29808, "s": 29764, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 29834, "s": 29808, "text": "C++ Program for QuickSort" }, { "code": null, "e": 29893, "s": 29834, "text": "How to return multiple values from a function in C or C++?" } ]
Errors and Exceptions in Python - GeeksforGeeks
22 Oct, 2021 Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program. Two types of Error occurs in python. Syntax errorsLogical errors (Exceptions) Syntax errors Logical errors (Exceptions) When the proper syntax of the language is not followed then a syntax error is thrown.Example Python3 # initialize the amount variableamount = 10000 # check that You are eligible to# purchase Dsa Self Paced or notif(amount>2999) print("You are eligible to purchase Dsa Self Paced") Output: It returns a syntax error message because after the if statement a colon: is missing. We can fix this by writing the correct syntax. When in the runtime an error that occurs after passing the syntax test is called exception or logical type. For example, when we divide any number by zero then the ZeroDivisionError exception is raised, or when we import a module that does not exist then ImportError is raised.Example 1: Python3 # initialize the amount variablemarks = 10000 # perform division with 0a = marks / 0print(a) Output: In the above example the ZeroDivisionError as we are trying to divide a number by 0.Example 2: When indentation is not correct. Python3 if(a<3):print("gfg") Output: Some of the common built-in exceptions are other than above mention exceptions are: Note: For more information, refer to Built-in Exceptions in Python When an error and an exception are raised then we handle that with the help of the Handling method. Handling Exceptions with Try/Except/Finally We can handle errors by the Try/Except/Finally method. we write unsafe code in the try, fall back code in except and final code in finally block.Example Python3 # put unsafe operation in try blocktry: print("code start") # unsafe operation perform print(1 / 0) # if error occur the it goes in except blockexcept: print("an error occurs") # final code in finally blockfinally: print("GeeksForGeeks") Output: code start an error occurs GeeksForGeeks Raising exceptions for a predefined condition When we want to code for the limitation of certain conditions then we can raise an exception. Example Python3 # try for unsafe codetry: amount = 1999 if amount < 2999: # raise the ValueError raise ValueError("please add money in your account") else: print("You are eligible to purchase DSA Self Paced course") # if false then raise the value errorexcept ValueError as e: print(e) Output: please add money in your account punamsingh628700 Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 42677, "s": 42649, "text": "\n22 Oct, 2021" }, { "code": null, "e": 42922, "s": 42677, "text": "Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program. Two types of Error occurs in python. " }, { "code": null, "e": 42965, "s": 42922, "text": "Syntax errorsLogical errors (Exceptions) " }, { "code": null, "e": 42979, "s": 42965, "text": "Syntax errors" }, { "code": null, "e": 43009, "s": 42979, "text": "Logical errors (Exceptions) " }, { "code": null, "e": 43106, "s": 43011, "text": "When the proper syntax of the language is not followed then a syntax error is thrown.Example " }, { "code": null, "e": 43114, "s": 43106, "text": "Python3" }, { "code": "# initialize the amount variableamount = 10000 # check that You are eligible to# purchase Dsa Self Paced or notif(amount>2999) print(\"You are eligible to purchase Dsa Self Paced\") ", "e": 43304, "s": 43114, "text": null }, { "code": null, "e": 43313, "s": 43304, "text": "Output: " }, { "code": null, "e": 43447, "s": 43313, "text": "It returns a syntax error message because after the if statement a colon: is missing. We can fix this by writing the correct syntax. " }, { "code": null, "e": 43737, "s": 43447, "text": "When in the runtime an error that occurs after passing the syntax test is called exception or logical type. For example, when we divide any number by zero then the ZeroDivisionError exception is raised, or when we import a module that does not exist then ImportError is raised.Example 1: " }, { "code": null, "e": 43745, "s": 43737, "text": "Python3" }, { "code": "# initialize the amount variablemarks = 10000 # perform division with 0a = marks / 0print(a)", "e": 43839, "s": 43745, "text": null }, { "code": null, "e": 43848, "s": 43839, "text": "Output: " }, { "code": null, "e": 43978, "s": 43848, "text": "In the above example the ZeroDivisionError as we are trying to divide a number by 0.Example 2: When indentation is not correct. " }, { "code": null, "e": 43986, "s": 43978, "text": "Python3" }, { "code": "if(a<3):print(\"gfg\")", "e": 44007, "s": 43986, "text": null }, { "code": null, "e": 44016, "s": 44007, "text": "Output: " }, { "code": null, "e": 44101, "s": 44016, "text": "Some of the common built-in exceptions are other than above mention exceptions are: " }, { "code": null, "e": 44171, "s": 44103, "text": "Note: For more information, refer to Built-in Exceptions in Python " }, { "code": null, "e": 44272, "s": 44171, "text": "When an error and an exception are raised then we handle that with the help of the Handling method. " }, { "code": null, "e": 44471, "s": 44272, "text": "Handling Exceptions with Try/Except/Finally We can handle errors by the Try/Except/Finally method. we write unsafe code in the try, fall back code in except and final code in finally block.Example " }, { "code": null, "e": 44479, "s": 44471, "text": "Python3" }, { "code": "# put unsafe operation in try blocktry: print(\"code start\") # unsafe operation perform print(1 / 0) # if error occur the it goes in except blockexcept: print(\"an error occurs\") # final code in finally blockfinally: print(\"GeeksForGeeks\")", "e": 44749, "s": 44479, "text": null }, { "code": null, "e": 44759, "s": 44749, "text": "Output: " }, { "code": null, "e": 44800, "s": 44759, "text": "code start\nan error occurs\nGeeksForGeeks" }, { "code": null, "e": 44952, "s": 44802, "text": "Raising exceptions for a predefined condition When we want to code for the limitation of certain conditions then we can raise an exception. Example " }, { "code": null, "e": 44960, "s": 44952, "text": "Python3" }, { "code": "# try for unsafe codetry: amount = 1999 if amount < 2999: # raise the ValueError raise ValueError(\"please add money in your account\") else: print(\"You are eligible to purchase DSA Self Paced course\") # if false then raise the value errorexcept ValueError as e: print(e)", "e": 45290, "s": 44960, "text": null }, { "code": null, "e": 45300, "s": 45290, "text": "Output: " }, { "code": null, "e": 45333, "s": 45300, "text": "please add money in your account" }, { "code": null, "e": 45350, "s": 45333, "text": "punamsingh628700" }, { "code": null, "e": 45368, "s": 45350, "text": "Python-exceptions" }, { "code": null, "e": 45375, "s": 45368, "text": "Python" }, { "code": null, "e": 45473, "s": 45375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45501, "s": 45473, "text": "Read JSON file using Python" }, { "code": null, "e": 45551, "s": 45501, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 45573, "s": 45551, "text": "Python map() function" }, { "code": null, "e": 45617, "s": 45573, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 45652, "s": 45617, "text": "Read a file line by line in Python" }, { "code": null, "e": 45684, "s": 45652, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 45706, "s": 45684, "text": "Enumerate() in Python" }, { "code": null, "e": 45748, "s": 45706, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 45778, "s": 45748, "text": "Iterate over a list in Python" } ]
Interfaces and Inheritance in Java - GeeksforGeeks
28 Jun, 2021 Prerequisites: Interfaces in Java, Java and Multiple Inheritance A class can extends another class and/ can implement one and more than one interface. // Java program to demonstrate that a class can// implement multiple interfacesimport java.io.*;interface intfA{ void m1();} interface intfB{ void m2();} // class implements both interfaces// and provides implementation to the method.class sample implements intfA, intfB{ @Override public void m1() { System.out.println("Welcome: inside the method m1"); } @Override public void m2() { System.out.println("Welcome: inside the method m2"); }} class GFG{ public static void main (String[] args) { sample ob1 = new sample(); // calling the method implemented // within the class. ob1.m1(); ob1.m2(); }} Output; Welcome: inside the method m1 Welcome: inside the method m2 Interface inheritance : An Interface can extend other interface. // Java program to demonstrate inheritance in // interfaces.import java.io.*;interface intfA{ void geekName();} interface intfB extends intfA{ void geekInstitute();} // class implements both interfaces and provides// implementation to the method.class sample implements intfB{ @Override public void geekName() { System.out.println("Rohit"); } @Override public void geekInstitute() { System.out.println("JIIT"); } public static void main (String[] args) { sample ob1 = new sample(); // calling the method implemented // within the class. ob1.geekName(); ob1.geekInstitute(); }} Output: Rohit JIIT An interface can also extend multiple interfaces. // Java program to demonstrate multiple inheritance // in interfacesimport java.io.*;interface intfA{ void geekName();} interface intfB { void geekInstitute();} interface intfC extends intfA, intfB { void geekBranch();} // class implements both interfaces and provides// implementation to the method.class sample implements intfC{ public void geekName() { System.out.println("Rohit"); } public void geekInstitute() { System.out.println("JIIT"); } public void geekBranch() { System.out.println("CSE"); } public static void main (String[] args) { sample ob1 = new sample(); // calling the method implemented // within the class. ob1.geekName(); ob1.geekInstitute(); ob1.geekBranch(); }} Output: Rohit JIIT CSE Why Multiple Inheritance is not supported through a class in Java, but it can be possible through the interface?Multiple Inheritance is not supported by class because of ambiguity. In case of interface, there is no ambiguity because implementation to the method(s) is provided by the implementing class up to Java 7. From Java 8, interfaces also have implementations of methods. So if a class implementing two or more interfaces having the same method signature with implementation, it is mandated to implement the method in class also. Refer Java and Multiple Inheritance for details. This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. DeepsD java-inheritance Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25797, "s": 25769, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25862, "s": 25797, "text": "Prerequisites: Interfaces in Java, Java and Multiple Inheritance" }, { "code": null, "e": 25948, "s": 25862, "text": "A class can extends another class and/ can implement one and more than one interface." }, { "code": "// Java program to demonstrate that a class can// implement multiple interfacesimport java.io.*;interface intfA{ void m1();} interface intfB{ void m2();} // class implements both interfaces// and provides implementation to the method.class sample implements intfA, intfB{ @Override public void m1() { System.out.println(\"Welcome: inside the method m1\"); } @Override public void m2() { System.out.println(\"Welcome: inside the method m2\"); }} class GFG{ public static void main (String[] args) { sample ob1 = new sample(); // calling the method implemented // within the class. ob1.m1(); ob1.m2(); }}", "e": 26642, "s": 25948, "text": null }, { "code": null, "e": 26650, "s": 26642, "text": "Output;" }, { "code": null, "e": 26711, "s": 26650, "text": "Welcome: inside the method m1\nWelcome: inside the method m2\n" }, { "code": null, "e": 26776, "s": 26711, "text": "Interface inheritance : An Interface can extend other interface." }, { "code": "// Java program to demonstrate inheritance in // interfaces.import java.io.*;interface intfA{ void geekName();} interface intfB extends intfA{ void geekInstitute();} // class implements both interfaces and provides// implementation to the method.class sample implements intfB{ @Override public void geekName() { System.out.println(\"Rohit\"); } @Override public void geekInstitute() { System.out.println(\"JIIT\"); } public static void main (String[] args) { sample ob1 = new sample(); // calling the method implemented // within the class. ob1.geekName(); ob1.geekInstitute(); }}", "e": 27449, "s": 26776, "text": null }, { "code": null, "e": 27457, "s": 27449, "text": "Output:" }, { "code": null, "e": 27469, "s": 27457, "text": "Rohit\nJIIT\n" }, { "code": null, "e": 27519, "s": 27469, "text": "An interface can also extend multiple interfaces." }, { "code": "// Java program to demonstrate multiple inheritance // in interfacesimport java.io.*;interface intfA{ void geekName();} interface intfB { void geekInstitute();} interface intfC extends intfA, intfB { void geekBranch();} // class implements both interfaces and provides// implementation to the method.class sample implements intfC{ public void geekName() { System.out.println(\"Rohit\"); } public void geekInstitute() { System.out.println(\"JIIT\"); } public void geekBranch() { System.out.println(\"CSE\"); } public static void main (String[] args) { sample ob1 = new sample(); // calling the method implemented // within the class. ob1.geekName(); ob1.geekInstitute(); ob1.geekBranch(); }}", "e": 28327, "s": 27519, "text": null }, { "code": null, "e": 28335, "s": 28327, "text": "Output:" }, { "code": null, "e": 28351, "s": 28335, "text": "Rohit\nJIIT\nCSE\n" }, { "code": null, "e": 28937, "s": 28351, "text": "Why Multiple Inheritance is not supported through a class in Java, but it can be possible through the interface?Multiple Inheritance is not supported by class because of ambiguity. In case of interface, there is no ambiguity because implementation to the method(s) is provided by the implementing class up to Java 7. From Java 8, interfaces also have implementations of methods. So if a class implementing two or more interfaces having the same method signature with implementation, it is mandated to implement the method in class also. Refer Java and Multiple Inheritance for details." }, { "code": null, "e": 29235, "s": 28937, "text": "This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29360, "s": 29235, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29367, "s": 29360, "text": "DeepsD" }, { "code": null, "e": 29384, "s": 29367, "text": "java-inheritance" }, { "code": null, "e": 29389, "s": 29384, "text": "Java" }, { "code": null, "e": 29394, "s": 29389, "text": "Java" }, { "code": null, "e": 29492, "s": 29394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29522, "s": 29492, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29541, "s": 29522, "text": "Interfaces in Java" }, { "code": null, "e": 29556, "s": 29541, "text": "Stream In Java" }, { "code": null, "e": 29587, "s": 29556, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29605, "s": 29587, "text": "ArrayList in Java" }, { "code": null, "e": 29637, "s": 29605, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29657, "s": 29637, "text": "Stack Class in Java" }, { "code": null, "e": 29689, "s": 29657, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29713, "s": 29689, "text": "Singleton Class in Java" } ]
numpy.concatenate() function | Python - GeeksforGeeks
22 Apr, 2020 numpy.concatenate() function concatenate a sequence of arrays along an existing axis. Syntax : numpy.concatenate((arr1, arr2, ...), axis=0, out=None)Parameters :arr1, arr2, ... : [sequence of array_like] The arrays must have the same shape, except in the dimension corresponding to axis.axis : [int, optional] The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.out : [ndarray, optional] If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.Return : [ndarray] The concatenated array. Code #1 : # Python program explaining# numpy.concatenate() function # importing numpy as geek import numpy as geek arr1 = geek.array([[2, 4], [6, 8]])arr2 = geek.array([[3, 5], [7, 9]]) gfg = geek.concatenate((arr1, arr2), axis = 0) print (gfg) Output : [[2 4] [6 8] [3 5] [7 9]] Code #2 : # Python program explaining# numpy.concatenate() function # importing numpy as geek import numpy as geek arr1 = geek.array([[2, 4], [6, 8]])arr2 = geek.array([[3, 5], [7, 9]]) gfg = geek.concatenate((arr1, arr2), axis = 1) print (gfg) Output : [[2 4 3 5] [6 8 7 9]] Code #3 : # Python program explaining# numpy.concatenate() function # importing numpy as geek import numpy as geek arr1 = geek.array([[2, 4], [6, 8]])arr2 = geek.array([[3, 5], [7, 9]]) gfg = geek.concatenate((arr1, arr2), axis = None) print (gfg) Output : [2 4 6 8 3 5 7 9] Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25648, "s": 25562, "text": "numpy.concatenate() function concatenate a sequence of arrays along an existing axis." }, { "code": null, "e": 26217, "s": 25648, "text": "Syntax : numpy.concatenate((arr1, arr2, ...), axis=0, out=None)Parameters :arr1, arr2, ... : [sequence of array_like] The arrays must have the same shape, except in the dimension corresponding to axis.axis : [int, optional] The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.out : [ndarray, optional] If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.Return : [ndarray] The concatenated array." }, { "code": null, "e": 26227, "s": 26217, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.concatenate() function # importing numpy as geek import numpy as geek arr1 = geek.array([[2, 4], [6, 8]])arr2 = geek.array([[3, 5], [7, 9]]) gfg = geek.concatenate((arr1, arr2), axis = 0) print (gfg)", "e": 26466, "s": 26227, "text": null }, { "code": null, "e": 26475, "s": 26466, "text": "Output :" }, { "code": null, "e": 26505, "s": 26475, "text": "[[2 4]\n [6 8]\n [3 5]\n [7 9]]\n" }, { "code": null, "e": 26516, "s": 26505, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.concatenate() function # importing numpy as geek import numpy as geek arr1 = geek.array([[2, 4], [6, 8]])arr2 = geek.array([[3, 5], [7, 9]]) gfg = geek.concatenate((arr1, arr2), axis = 1) print (gfg)", "e": 26755, "s": 26516, "text": null }, { "code": null, "e": 26764, "s": 26755, "text": "Output :" }, { "code": null, "e": 26788, "s": 26764, "text": "[[2 4 3 5]\n [6 8 7 9]]\n" }, { "code": null, "e": 26799, "s": 26788, "text": " Code #3 :" }, { "code": "# Python program explaining# numpy.concatenate() function # importing numpy as geek import numpy as geek arr1 = geek.array([[2, 4], [6, 8]])arr2 = geek.array([[3, 5], [7, 9]]) gfg = geek.concatenate((arr1, arr2), axis = None) print (gfg)", "e": 27041, "s": 26799, "text": null }, { "code": null, "e": 27050, "s": 27041, "text": "Output :" }, { "code": null, "e": 27069, "s": 27050, "text": "[2 4 6 8 3 5 7 9]\n" }, { "code": null, "e": 27100, "s": 27069, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 27113, "s": 27100, "text": "Python-numpy" }, { "code": null, "e": 27120, "s": 27113, "text": "Python" }, { "code": null, "e": 27218, "s": 27120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27250, "s": 27218, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27292, "s": 27250, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27334, "s": 27292, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27390, "s": 27334, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27417, "s": 27390, "text": "Python Classes and Objects" }, { "code": null, "e": 27448, "s": 27417, "text": "Python | os.path.join() method" }, { "code": null, "e": 27487, "s": 27448, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27516, "s": 27487, "text": "Create a directory in Python" }, { "code": null, "e": 27538, "s": 27516, "text": "Defaultdict in Python" } ]
C# | First occurrence in the List that matches the specified conditions - GeeksforGeeks
30 Sep, 2019 List<T>.Find(Predicate<T>) Method is used to search for an element which matches the conditions defined by the specified predicate and it returns the first occurrence of that element within the entire List<T>. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element. Syntax: public T Find (Predicate<T> match); Parameter: match: It is the Predicate delegate which defines the conditions of the element which is to be searched. Return Value: If the element found then this method will return the first element that matches the conditions defined by the specified predicate otherwise it returns the default value for type T. Exception: This method will give ArgumentNullException if the match is null. Below programs illustrate the use of List<T>.Find(Predicate<T>) Method: Example 1: // C# Program to get the first occurrence// of the element that match the specified// conditions defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(2); firstlist.Add(4); firstlist.Add(7); firstlist.Add(2); firstlist.Add(6); firstlist.Add(2); firstlist.Add(2); Console.WriteLine("Elements Present in List:\n"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.Write("Result: "); // Will give the first occurrence of the // element of firstlist that match the // conditions defined by predicate Console.WriteLine(firstlist.Find(isEven)); }} Output: Elements Present in List: 2 4 7 2 6 2 2 Result: 2 Example 2: // C# Program to get the first occurrence// of the element that match the specified// conditions defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(5); firstlist.Add(7); firstlist.Add(9); firstlist.Add(11); firstlist.Add(3); firstlist.Add(17); firstlist.Add(19); Console.WriteLine("Elements Present in List:\n"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.Write("Result: "); // Will give the first occurrence of the // element of firstlist that match the // conditions defined by predicate // No match found so it will return 0 Console.WriteLine(firstlist.Find(isEven)); }} Output: Elements Present in List: 5 7 9 11 3 17 19 Result: 0 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.find?view=netframework-4.7.2 nidhi_biet CSharp-Collections-Namespace CSharp-Generic-List CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | Replace() Method Introduction to .NET Framework C# | Data Types HashSet in C# with Examples
[ { "code": null, "e": 25791, "s": 25763, "text": "\n30 Sep, 2019" }, { "code": null, "e": 26001, "s": 25791, "text": "List<T>.Find(Predicate<T>) Method is used to search for an element which matches the conditions defined by the specified predicate and it returns the first occurrence of that element within the entire List<T>." }, { "code": null, "e": 26021, "s": 26001, "text": "Properties of List:" }, { "code": null, "e": 26107, "s": 26021, "text": "It is different from the arrays. A list can be resized dynamically but arrays cannot." }, { "code": null, "e": 26210, "s": 26107, "text": "List class can accept null as a valid value for reference types and it also allows duplicate elements." }, { "code": null, "e": 26434, "s": 26210, "text": "If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element." }, { "code": null, "e": 26442, "s": 26434, "text": "Syntax:" }, { "code": null, "e": 26479, "s": 26442, "text": "public T Find (Predicate<T> match);\n" }, { "code": null, "e": 26490, "s": 26479, "text": "Parameter:" }, { "code": null, "e": 26595, "s": 26490, "text": "match: It is the Predicate delegate which defines the conditions of the element which is to be searched." }, { "code": null, "e": 26791, "s": 26595, "text": "Return Value: If the element found then this method will return the first element that matches the conditions defined by the specified predicate otherwise it returns the default value for type T." }, { "code": null, "e": 26868, "s": 26791, "text": "Exception: This method will give ArgumentNullException if the match is null." }, { "code": null, "e": 26940, "s": 26868, "text": "Below programs illustrate the use of List<T>.Find(Predicate<T>) Method:" }, { "code": null, "e": 26951, "s": 26940, "text": "Example 1:" }, { "code": "// C# Program to get the first occurrence// of the element that match the specified// conditions defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(2); firstlist.Add(4); firstlist.Add(7); firstlist.Add(2); firstlist.Add(6); firstlist.Add(2); firstlist.Add(2); Console.WriteLine(\"Elements Present in List:\\n\"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.Write(\"Result: \"); // Will give the first occurrence of the // element of firstlist that match the // conditions defined by predicate Console.WriteLine(firstlist.Find(isEven)); }}", "e": 28178, "s": 26951, "text": null }, { "code": null, "e": 28186, "s": 28178, "text": "Output:" }, { "code": null, "e": 28240, "s": 28186, "text": "Elements Present in List:\n\n2\n4\n7\n2\n6\n2\n2\n \nResult: 2\n" }, { "code": null, "e": 28251, "s": 28240, "text": "Example 2:" }, { "code": "// C# Program to get the first occurrence// of the element that match the specified// conditions defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(5); firstlist.Add(7); firstlist.Add(9); firstlist.Add(11); firstlist.Add(3); firstlist.Add(17); firstlist.Add(19); Console.WriteLine(\"Elements Present in List:\\n\"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.Write(\"Result: \"); // Will give the first occurrence of the // element of firstlist that match the // conditions defined by predicate // No match found so it will return 0 Console.WriteLine(firstlist.Find(isEven)); }}", "e": 29526, "s": 28251, "text": null }, { "code": null, "e": 29534, "s": 29526, "text": "Output:" }, { "code": null, "e": 29591, "s": 29534, "text": "Elements Present in List:\n\n5\n7\n9\n11\n3\n17\n19\n \nResult: 0\n" }, { "code": null, "e": 29602, "s": 29591, "text": "Reference:" }, { "code": null, "e": 29709, "s": 29602, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.find?view=netframework-4.7.2" }, { "code": null, "e": 29720, "s": 29709, "text": "nidhi_biet" }, { "code": null, "e": 29749, "s": 29720, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 29769, "s": 29749, "text": "CSharp-Generic-List" }, { "code": null, "e": 29794, "s": 29769, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 29808, "s": 29794, "text": "CSharp-method" }, { "code": null, "e": 29811, "s": 29808, "text": "C#" }, { "code": null, "e": 29909, "s": 29811, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29924, "s": 29909, "text": "C# | Delegates" }, { "code": null, "e": 29946, "s": 29924, "text": "C# | Abstract Classes" }, { "code": null, "e": 29992, "s": 29946, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30015, "s": 29992, "text": "Extension Method in C#" }, { "code": null, "e": 30037, "s": 30015, "text": "C# | Class and Object" }, { "code": null, "e": 30055, "s": 30037, "text": "C# | Constructors" }, { "code": null, "e": 30077, "s": 30055, "text": "C# | Replace() Method" }, { "code": null, "e": 30108, "s": 30077, "text": "Introduction to .NET Framework" }, { "code": null, "e": 30124, "s": 30108, "text": "C# | Data Types" } ]
Top 10 High Paying Jobs That Demand SQL - GeeksforGeeks
16 Dec, 2019 SQL can execute queries, retrieve data, insert or delete records, create tables or stored procedures in a database, and so on. SQL is the most adaptable niche in the market. Switching the job once you enter in IT industry is not a big deal. The hardest part is in the beginning. But most of the students who are going to begin their career in the database using SQL must be looking for top high paying jobs in database or SQL related profiles. Read on to know about the various profiles associated with SQL or database. As per the data found on various job websites, here are the top 10 high paying jobs that demand SQL: 1. Data Analyst 2. Database Developer 3. Database Administrator 4. Data Scientist 5. SQL Server Developer 6. Software Developer 7. Software Consultant 8. .Net Developer 9. ETL Developer 10. Big Data engineer These are discussed as following below. 1. Data Analyst:SQL is a must if you want to become a Data Analyst. SQL in data analysis is used for accessing, cleaning, and analyzing data that is stored in databases. Data analysts must be systematically talented so as to recognize designs inside enormous amounts of information. By expository aptitude we mean comprehension of mathematics, calculations, and statistics. With this, programming and MS Excel skills are mandatory. The average salary of a Data Analyst is $60,187 per year. 2. Database Developer:Database developers guarantee that DBMS’s can deal with monstrous amounts of data. Database developers generally deal with software development teams. It requires a high level of knowledge of SQL to pursue this career. The job of database developer regularly falls into three unmistakable territories: Modifying and editing databases Designing and developing new databases Investigating database issues The average salary of a Database Developer is $98,415 per year. 3. Database Administrator:A database administrator or database manager takes care of critical obligation as the overseer of an organization’s data. He/she is liable for transforming the crude information into actionable insight. So what does a database administrator do precisely ? Database installation and configuration Data security User creation and maintenance Database backups and recovery Database performance tuning and optimization Data transformation and loading Reporting and querying The average salary of a Database Administrator is $94,406 per year. 4. Data Scientist:A data scientist must have the ability to recover data. They may likewise use SQL to make their very own table or table environment. A data scientist comprehends both business and data. He will apply aptitudes in business, statistics, and data programming to the assortment of data or potentially its refinement, examination, and application to acquire the most primary concern advantage. The average salary of a Data Scientist is high as $135,000 per year. 5. SQL Server Developer:The MSSD plays a basic job in the extension of the Microsoft SQL Server and its related operational applications. He is responsible for different fundamental assignments, for example, doing the exercises identified with database and ETL (Extract/Transform/Load) to support and propel the Microsoft SQL Server’s operational stage. He takes a shot at the database programming to adequately resolve issues identified with the application. The average salary of a SQL Server Developer is $102,400 per year. 6. Software Developer:A software developer works in both design and development phases of the creation of software. He will regularly plot out the different parts of the automated errands that will be essential. He plans documentation and flowcharts to help represent the process of the software. The average salary of a Software Developer is $102,528 per year. 7. Software Consultant:Software Consultants create a range of database solutions given below: Database Development Services Database Administration and Maintenance Services MS SQL Database Trouble-shooting Database-optimization and performance scalability Database design while using Data modeling tool such as xCase Custom Reports using MS SQL report services SSIS SQL Server Integration Services The average salary of a Software Consultant is $118,000 per year. 8. Dot(.) Net Developer:Data is quickly getting one of the most significant parts of advancement, and .NET is no special case. .NET developers ought to be knowledgeable in Microsoft’s very own SQL databases as well as rising innovation, for example, NoSQL. The average salary of a .Net Developer is $107,250 per year. 9. ETL Developer:SQL is the lifeblood of ETL developers and is the mandatory language for them. All aspects of ETL are performed with SQL. There are other Query Languages that can be utilized, yet SQL is the most well-known for organizations. As a rule, ETL tools are extremely just SQL generators off camera, so it’s imperative to have the option to utilize both interchangeably. The average salary of an ETL Developer is $107,250 per year. 10. Big Data Engineer:Big data engineers work with big data tools like Hadoop, Spark, Hive, and so on. To work with these tools, proficiency with SQL is mandatory. SQL Server underpins PolyBase to inquiry Big Data utilizing T-SQL. You should be a master in SQL Server to implement your database knowledge. After all, you will be dealing with database and database initiates with SQL. The average salary of a Big Data Engineer is $136,500 per year. You are on your way!With the above details, you might have understood now why SQL is a must-have skill for a technical as well as a non-technical individual. SQL enables you to work legitimately with essential information, instead of requiring another person to furnish you with composed datasets. This enables you to move speedier on strategy, lead projects independently, and become a technical asset to your organization. Learning SQL is not at all challenging! You can produce incredible queries from unlimited permutations of the SQL statements. Keep in mind, the most ideal approach to bond the ideas and show signs of improvement in SQL are by rehearsing and tackling SQL issues. You can discover increasingly intuitive activities by going through SQL Server training and tune your SQL career. β€œThe more you practice the better you’ll be, the harder you train the extraordinary in you they’ll see.” – Alcurtis Turner. satyabook Career-Advices Marketing DBMS GBlog SQL TechTips DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL Difference between Clustered and Non-clustered index Data Preprocessing in Data Mining Difference between SQL and NoSQL Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... DSA Sheet by Love Babbar Socket Programming in C/C++ GET and POST requests using Python Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 25615, "s": 25587, "text": "\n16 Dec, 2019" }, { "code": null, "e": 26135, "s": 25615, "text": "SQL can execute queries, retrieve data, insert or delete records, create tables or stored procedures in a database, and so on. SQL is the most adaptable niche in the market. Switching the job once you enter in IT industry is not a big deal. The hardest part is in the beginning. But most of the students who are going to begin their career in the database using SQL must be looking for top high paying jobs in database or SQL related profiles. Read on to know about the various profiles associated with SQL or database." }, { "code": null, "e": 26236, "s": 26135, "text": "As per the data found on various job websites, here are the top 10 high paying jobs that demand SQL:" }, { "code": null, "e": 26445, "s": 26236, "text": "1. Data Analyst\n2. Database Developer\n3. Database Administrator\n4. Data Scientist\n5. SQL Server Developer\n6. Software Developer\n7. Software Consultant\n8. .Net Developer\n9. ETL Developer\n10. Big Data engineer " }, { "code": null, "e": 26485, "s": 26445, "text": "These are discussed as following below." }, { "code": null, "e": 26917, "s": 26485, "text": "1. Data Analyst:SQL is a must if you want to become a Data Analyst. SQL in data analysis is used for accessing, cleaning, and analyzing data that is stored in databases. Data analysts must be systematically talented so as to recognize designs inside enormous amounts of information. By expository aptitude we mean comprehension of mathematics, calculations, and statistics. With this, programming and MS Excel skills are mandatory." }, { "code": null, "e": 26975, "s": 26917, "text": "The average salary of a Data Analyst is $60,187 per year." }, { "code": null, "e": 27299, "s": 26975, "text": "2. Database Developer:Database developers guarantee that DBMS’s can deal with monstrous amounts of data. Database developers generally deal with software development teams. It requires a high level of knowledge of SQL to pursue this career. The job of database developer regularly falls into three unmistakable territories:" }, { "code": null, "e": 27331, "s": 27299, "text": "Modifying and editing databases" }, { "code": null, "e": 27370, "s": 27331, "text": "Designing and developing new databases" }, { "code": null, "e": 27400, "s": 27370, "text": "Investigating database issues" }, { "code": null, "e": 27464, "s": 27400, "text": "The average salary of a Database Developer is $98,415 per year." }, { "code": null, "e": 27746, "s": 27464, "text": "3. Database Administrator:A database administrator or database manager takes care of critical obligation as the overseer of an organization’s data. He/she is liable for transforming the crude information into actionable insight. So what does a database administrator do precisely ?" }, { "code": null, "e": 27786, "s": 27746, "text": "Database installation and configuration" }, { "code": null, "e": 27800, "s": 27786, "text": "Data security" }, { "code": null, "e": 27830, "s": 27800, "text": "User creation and maintenance" }, { "code": null, "e": 27860, "s": 27830, "text": "Database backups and recovery" }, { "code": null, "e": 27905, "s": 27860, "text": "Database performance tuning and optimization" }, { "code": null, "e": 27937, "s": 27905, "text": "Data transformation and loading" }, { "code": null, "e": 27960, "s": 27937, "text": "Reporting and querying" }, { "code": null, "e": 28028, "s": 27960, "text": "The average salary of a Database Administrator is $94,406 per year." }, { "code": null, "e": 28435, "s": 28028, "text": "4. Data Scientist:A data scientist must have the ability to recover data. They may likewise use SQL to make their very own table or table environment. A data scientist comprehends both business and data. He will apply aptitudes in business, statistics, and data programming to the assortment of data or potentially its refinement, examination, and application to acquire the most primary concern advantage." }, { "code": null, "e": 28504, "s": 28435, "text": "The average salary of a Data Scientist is high as $135,000 per year." }, { "code": null, "e": 28964, "s": 28504, "text": "5. SQL Server Developer:The MSSD plays a basic job in the extension of the Microsoft SQL Server and its related operational applications. He is responsible for different fundamental assignments, for example, doing the exercises identified with database and ETL (Extract/Transform/Load) to support and propel the Microsoft SQL Server’s operational stage. He takes a shot at the database programming to adequately resolve issues identified with the application." }, { "code": null, "e": 29031, "s": 28964, "text": "The average salary of a SQL Server Developer is $102,400 per year." }, { "code": null, "e": 29328, "s": 29031, "text": "6. Software Developer:A software developer works in both design and development phases of the creation of software. He will regularly plot out the different parts of the automated errands that will be essential. He plans documentation and flowcharts to help represent the process of the software." }, { "code": null, "e": 29393, "s": 29328, "text": "The average salary of a Software Developer is $102,528 per year." }, { "code": null, "e": 29487, "s": 29393, "text": "7. Software Consultant:Software Consultants create a range of database solutions given below:" }, { "code": null, "e": 29517, "s": 29487, "text": "Database Development Services" }, { "code": null, "e": 29566, "s": 29517, "text": "Database Administration and Maintenance Services" }, { "code": null, "e": 29599, "s": 29566, "text": "MS SQL Database Trouble-shooting" }, { "code": null, "e": 29649, "s": 29599, "text": "Database-optimization and performance scalability" }, { "code": null, "e": 29710, "s": 29649, "text": "Database design while using Data modeling tool such as xCase" }, { "code": null, "e": 29754, "s": 29710, "text": "Custom Reports using MS SQL report services" }, { "code": null, "e": 29791, "s": 29754, "text": "SSIS SQL Server Integration Services" }, { "code": null, "e": 29857, "s": 29791, "text": "The average salary of a Software Consultant is $118,000 per year." }, { "code": null, "e": 30114, "s": 29857, "text": "8. Dot(.) Net Developer:Data is quickly getting one of the most significant parts of advancement, and .NET is no special case. .NET developers ought to be knowledgeable in Microsoft’s very own SQL databases as well as rising innovation, for example, NoSQL." }, { "code": null, "e": 30175, "s": 30114, "text": "The average salary of a .Net Developer is $107,250 per year." }, { "code": null, "e": 30556, "s": 30175, "text": "9. ETL Developer:SQL is the lifeblood of ETL developers and is the mandatory language for them. All aspects of ETL are performed with SQL. There are other Query Languages that can be utilized, yet SQL is the most well-known for organizations. As a rule, ETL tools are extremely just SQL generators off camera, so it’s imperative to have the option to utilize both interchangeably." }, { "code": null, "e": 30617, "s": 30556, "text": "The average salary of an ETL Developer is $107,250 per year." }, { "code": null, "e": 31001, "s": 30617, "text": "10. Big Data Engineer:Big data engineers work with big data tools like Hadoop, Spark, Hive, and so on. To work with these tools, proficiency with SQL is mandatory. SQL Server underpins PolyBase to inquiry Big Data utilizing T-SQL. You should be a master in SQL Server to implement your database knowledge. After all, you will be dealing with database and database initiates with SQL." }, { "code": null, "e": 31065, "s": 31001, "text": "The average salary of a Big Data Engineer is $136,500 per year." }, { "code": null, "e": 31490, "s": 31065, "text": "You are on your way!With the above details, you might have understood now why SQL is a must-have skill for a technical as well as a non-technical individual. SQL enables you to work legitimately with essential information, instead of requiring another person to furnish you with composed datasets. This enables you to move speedier on strategy, lead projects independently, and become a technical asset to your organization." }, { "code": null, "e": 31866, "s": 31490, "text": "Learning SQL is not at all challenging! You can produce incredible queries from unlimited permutations of the SQL statements. Keep in mind, the most ideal approach to bond the ideas and show signs of improvement in SQL are by rehearsing and tackling SQL issues. You can discover increasingly intuitive activities by going through SQL Server training and tune your SQL career." }, { "code": null, "e": 31990, "s": 31866, "text": "β€œThe more you practice the better you’ll be, the harder you train the extraordinary in you they’ll see.” – Alcurtis Turner." }, { "code": null, "e": 32000, "s": 31990, "text": "satyabook" }, { "code": null, "e": 32015, "s": 32000, "text": "Career-Advices" }, { "code": null, "e": 32025, "s": 32015, "text": "Marketing" }, { "code": null, "e": 32030, "s": 32025, "text": "DBMS" }, { "code": null, "e": 32036, "s": 32030, "text": "GBlog" }, { "code": null, "e": 32040, "s": 32036, "text": "SQL" }, { "code": null, "e": 32049, "s": 32040, "text": "TechTips" }, { "code": null, "e": 32054, "s": 32049, "text": "DBMS" }, { "code": null, "e": 32058, "s": 32054, "text": "SQL" }, { "code": null, "e": 32156, "s": 32058, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32180, "s": 32156, "text": "SQL Interview Questions" }, { "code": null, "e": 32191, "s": 32180, "text": "CTE in SQL" }, { "code": null, "e": 32244, "s": 32191, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 32278, "s": 32244, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 32311, "s": 32278, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 32385, "s": 32311, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 32410, "s": 32385, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32438, "s": 32410, "text": "Socket Programming in C/C++" }, { "code": null, "e": 32473, "s": 32438, "text": "GET and POST requests using Python" } ]
Node.js fs.lstat() Method - GeeksforGeeks
11 Oct, 2021 The fs.lstat() method is similar to the fs.stat() method except that it is used to return information about the symbolic link that is being used to refer to a file or directory. The fs.Stat object returned has several fields and methods to get more details about the file. Syntax: fs.lstat( path, options, callback ) Parameters: This method accept three parameters as mentioned above and described below: path: It is a String, Buffer or URL that holds the path of the symbolic link. options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false. bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false. callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the method.Stats: It is the Stats object that contains the details of the file path. err: It is an error that would be thrown if the method. Stats: It is the Stats object that contains the details of the file path. Below examples illustrate the fs.lstat() method in Node.js: Example 1: This example uses fs.lstat() method to get the details of a symbolic link to a file. // Node.js program to demonstrate the// fs.lstat() method // Import the filesystem moduleconst fs = require('fs'); fs.symlinkSync(__dirname + "\\example_file.txt", "symlinkToFile", 'file');console.log("Symlink to file created") fs.lstat("symlinkToFile", (err, stats) => { if (err) console.log(err); else { console.log("Stat of symlinkToFile") console.log(stats); }}); Output: Symlink to file created Stat of symlinkToFile Stats { dev: 3229478529, mode: 41398, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 281474976780939, size: 45, blocks: 0, atimeMs: 1585207132017.4473, mtimeMs: 1585207132017.4473, ctimeMs: 1585207132017.4473, birthtimeMs: 1585207132017.4473, atime: 2020-03-26T07:18:52.017Z, mtime: 2020-03-26T07:18:52.017Z, ctime: 2020-03-26T07:18:52.017Z, birthtime: 2020-03-26T07:18:52.017Z } Example 2: This example uses fs.lstat() method to get the details of a symbolic link to a folder. // Node.js program to demonstrate the// fs.lstat() method // Import the filesystem moduleconst fs = require('fs'); fs.symlinkSync(__dirname + "\\example_directory", "symlinkToDir", 'dir'); console.log("Symlink to directory created") fs.lstat("symlinkToDir", (err, stats) => { if (err) console.log(err); else { console.log("Stat of symlinkToDir") console.log(stats); }}); Output: Symlink to directory created Stat of symlinkToDir Stats { dev: 3229478529, mode: 41398, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 281474976780940, size: 46, blocks: 0, atimeMs: 1585207184224.7136, mtimeMs: 1585207184224.7136, ctimeMs: 1585207184224.7136, birthtimeMs: 1585207184224.7136, atime: 2020-03-26T07:19:44.225Z, mtime: 2020-03-26T07:19:44.225Z, ctime: 2020-03-26T07:19:44.225Z, birthtime: 2020-03-26T07:19:44.225Z } Reference: https://nodejs.org/api/fs.html#fs_fs_lstat_path_options_callback Node.js-fs-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.render() Function Mongoose | findByIdAndUpdate() Function Remove elements from a JavaScript Array 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25759, "s": 25731, "text": "\n11 Oct, 2021" }, { "code": null, "e": 26032, "s": 25759, "text": "The fs.lstat() method is similar to the fs.stat() method except that it is used to return information about the symbolic link that is being used to refer to a file or directory. The fs.Stat object returned has several fields and methods to get more details about the file." }, { "code": null, "e": 26040, "s": 26032, "text": "Syntax:" }, { "code": null, "e": 26076, "s": 26040, "text": "fs.lstat( path, options, callback )" }, { "code": null, "e": 26164, "s": 26076, "text": "Parameters: This method accept three parameters as mentioned above and described below:" }, { "code": null, "e": 26242, "s": 26164, "text": "path: It is a String, Buffer or URL that holds the path of the symbolic link." }, { "code": null, "e": 26514, "s": 26242, "text": "options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false." }, { "code": null, "e": 26654, "s": 26514, "text": "bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false." }, { "code": null, "e": 26861, "s": 26654, "text": "callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the method.Stats: It is the Stats object that contains the details of the file path." }, { "code": null, "e": 26917, "s": 26861, "text": "err: It is an error that would be thrown if the method." }, { "code": null, "e": 26991, "s": 26917, "text": "Stats: It is the Stats object that contains the details of the file path." }, { "code": null, "e": 27051, "s": 26991, "text": "Below examples illustrate the fs.lstat() method in Node.js:" }, { "code": null, "e": 27147, "s": 27051, "text": "Example 1: This example uses fs.lstat() method to get the details of a symbolic link to a file." }, { "code": "// Node.js program to demonstrate the// fs.lstat() method // Import the filesystem moduleconst fs = require('fs'); fs.symlinkSync(__dirname + \"\\\\example_file.txt\", \"symlinkToFile\", 'file');console.log(\"Symlink to file created\") fs.lstat(\"symlinkToFile\", (err, stats) => { if (err) console.log(err); else { console.log(\"Stat of symlinkToFile\") console.log(stats); }});", "e": 27553, "s": 27147, "text": null }, { "code": null, "e": 27561, "s": 27553, "text": "Output:" }, { "code": null, "e": 28031, "s": 27561, "text": "Symlink to file created\nStat of symlinkToFile\nStats {\n dev: 3229478529,\n mode: 41398,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 281474976780939,\n size: 45,\n blocks: 0,\n atimeMs: 1585207132017.4473,\n mtimeMs: 1585207132017.4473,\n ctimeMs: 1585207132017.4473,\n birthtimeMs: 1585207132017.4473,\n atime: 2020-03-26T07:18:52.017Z,\n mtime: 2020-03-26T07:18:52.017Z,\n ctime: 2020-03-26T07:18:52.017Z,\n birthtime: 2020-03-26T07:18:52.017Z\n}" }, { "code": null, "e": 28129, "s": 28031, "text": "Example 2: This example uses fs.lstat() method to get the details of a symbolic link to a folder." }, { "code": "// Node.js program to demonstrate the// fs.lstat() method // Import the filesystem moduleconst fs = require('fs'); fs.symlinkSync(__dirname + \"\\\\example_directory\", \"symlinkToDir\", 'dir'); console.log(\"Symlink to directory created\") fs.lstat(\"symlinkToDir\", (err, stats) => { if (err) console.log(err); else { console.log(\"Stat of symlinkToDir\") console.log(stats); }});", "e": 28541, "s": 28129, "text": null }, { "code": null, "e": 28549, "s": 28541, "text": "Output:" }, { "code": null, "e": 29023, "s": 28549, "text": "Symlink to directory created\nStat of symlinkToDir\nStats {\n dev: 3229478529,\n mode: 41398,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 281474976780940,\n size: 46,\n blocks: 0,\n atimeMs: 1585207184224.7136,\n mtimeMs: 1585207184224.7136,\n ctimeMs: 1585207184224.7136,\n birthtimeMs: 1585207184224.7136,\n atime: 2020-03-26T07:19:44.225Z,\n mtime: 2020-03-26T07:19:44.225Z,\n ctime: 2020-03-26T07:19:44.225Z,\n birthtime: 2020-03-26T07:19:44.225Z\n}" }, { "code": null, "e": 29099, "s": 29023, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_lstat_path_options_callback" }, { "code": null, "e": 29117, "s": 29099, "text": "Node.js-fs-module" }, { "code": null, "e": 29125, "s": 29117, "text": "Node.js" }, { "code": null, "e": 29142, "s": 29125, "text": "Web Technologies" }, { "code": null, "e": 29240, "s": 29142, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29297, "s": 29240, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 29351, "s": 29297, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 29388, "s": 29351, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 29421, "s": 29388, "text": "Express.js res.render() Function" }, { "code": null, "e": 29461, "s": 29421, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 29501, "s": 29461, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29546, "s": 29501, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29589, "s": 29546, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29639, "s": 29589, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
User Defined Data Structures in Python - GeeksforGeeks
19 Jan, 2022 In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures: Non-primitive data types: Python has list, set, and dictionary as its non-primitive data types which can also be considered its in-built data structures. User-defined data structures: Data structures that aren’t supported by python but can be programmed to reflect the same functionality using concepts supported by python are user-defined data structures. There are many data structure that can be implemented this way:Linked listStackQueueTreeGraphHashmap Linked list Stack Queue Tree Graph Hashmap A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: Program: Python3 llist = ['first', 'second', 'third']print(llist) print() # adding elementsllist.append('fourth')llist.append('fifth')llist.insert(3, 'sixth')print(llist)print() llist.remove('second')print(llist)print() Output: [β€˜first’, β€˜second’, β€˜third’] [β€˜first’, β€˜second’, β€˜third’, β€˜sixth’, β€˜fourth’, β€˜fifth’] [β€˜first’, β€˜third’, β€˜sixth’, β€˜fourth’, β€˜fifth’] A stack is a linear structure that allows data to be inserted and removed from the same end thus follows a last in first out(LIFO) system. Insertion and deletion is known as push() and pop() respectively. Program: Python3 stack = ['first', 'second', 'third']print(stack) print() # pushing elementsstack.append('fourth')stack.append('fifth')print(stack)print() # printing topn = len(stack)print(stack[n-1])print() # poping elementstack.pop()print(stack) Output: [β€˜first’, β€˜second’, β€˜third’] [β€˜first’, β€˜second’, β€˜third’, β€˜fourth’, β€˜fifth’] fifth [β€˜first’, β€˜second’, β€˜third’, β€˜fourth’] A queue is a linear structure that allows insertion of elements from one end and deletion from the other. Thus it follows, First In First Out(FIFO) methodology. The end which allows deletion is known as the front of the queue and the other end is known as the rear end of the queue. Program: Python3 queue = ['first', 'second', 'third']print(queue) print() # pushing elementsqueue.append('fourth')queue.append('fifth')print(queue)print() # printing headprint(queue[0]) # printing tailn = len(queue)print(queue[n-1])print() # poping elementqueue.remove(queue[0])print(queue) Output: [β€˜first’, β€˜second’, β€˜third’] [β€˜first’, β€˜second’, β€˜third’, β€˜fourth’, β€˜fifth’] first fifth [β€˜second’, β€˜third’, β€˜fourth’, β€˜fifth’] A tree is a non-linear but hierarchical data structure. The topmost element is known as the root of the tree since the tree is believed to start from the root. The elements at the end of the tree are known as its leaves. Trees are appropriate for storing data that aren’t linearly connected to each other but form a hierarchy. Program: Python3 class node: def __init__(self, ele): self.ele = ele self.left = None self.right = None def preorder(self): if self: print(self.ele) preorder(self.left) preorder(self.right) n = node('first')n.left = node('second')n.right = node('third')preorder(n) Output: first second third A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes. Program: Python3 class adjnode: def __init__(self, val): self.val = val self.next = None class graph: def __init__(self, vertices): self.v = vertices self.ele = [None]*self.v def edge(self, src, dest): node = adjnode(dest) node.next = self.ele[src] self.ele[src] = node node = adjnode(src) node.next = self.ele[dest] self.ele[dest] = node def __repr__(self): for i in range(self.v): print("Adjacency list of vertex {}\n head".format(i), end="") temp = self.ele[i] while temp: print(" -> {}".format(temp.val), end="") temp = temp.next g = graph(4)g.edge(0, 2)g.edge(1, 3)g.edge(3, 2)g.edge(0, 3)g.__repr__() Output: Adjacency list of vertex 0 head -> 3 -> 2 Adjacency list of vertex 1 head -> 3 Adjacency list of vertex 2 head -> 3 -> 0 Adjacency list of vertex 3 head -> 0 -> 2 -> 1 Hash maps are indexed data structures. A hash map makes use of a hash function to compute an index with a key into an array of buckets or slots. Its value is mapped to the bucket with the corresponding index. The key is unique and immutable. In Python, dictionaries are examples of hash maps. Program: Python3 def printdict(d): for key in d: print(key, "->", d[key]) hm = {0: 'first', 1: 'second', 2: 'third'}printdict(hm)print() hm[3] = 'fourth'printdict(hm)print() hm.popitem()printdict(hm) Output: 0 -> first 1 -> second 2 -> third 0 -> first 1 -> second 2 -> third 3 -> fourth 0 -> first 1 -> second 2 -> third sagartomar9927 Python-Data Type Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n19 Jan, 2022" }, { "code": null, "e": 25833, "s": 25561, "text": "In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures:" }, { "code": null, "e": 25987, "s": 25833, "text": "Non-primitive data types: Python has list, set, and dictionary as its non-primitive data types which can also be considered its in-built data structures." }, { "code": null, "e": 26291, "s": 25987, "text": "User-defined data structures: Data structures that aren’t supported by python but can be programmed to reflect the same functionality using concepts supported by python are user-defined data structures. There are many data structure that can be implemented this way:Linked listStackQueueTreeGraphHashmap" }, { "code": null, "e": 26303, "s": 26291, "text": "Linked list" }, { "code": null, "e": 26309, "s": 26303, "text": "Stack" }, { "code": null, "e": 26315, "s": 26309, "text": "Queue" }, { "code": null, "e": 26320, "s": 26315, "text": "Tree" }, { "code": null, "e": 26326, "s": 26320, "text": "Graph" }, { "code": null, "e": 26334, "s": 26326, "text": "Hashmap" }, { "code": null, "e": 26531, "s": 26334, "text": "A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: " }, { "code": null, "e": 26540, "s": 26531, "text": "Program:" }, { "code": null, "e": 26548, "s": 26540, "text": "Python3" }, { "code": "llist = ['first', 'second', 'third']print(llist) print() # adding elementsllist.append('fourth')llist.append('fifth')llist.insert(3, 'sixth')print(llist)print() llist.remove('second')print(llist)print()", "e": 26751, "s": 26548, "text": null }, { "code": null, "e": 26759, "s": 26751, "text": "Output:" }, { "code": null, "e": 26788, "s": 26759, "text": "[β€˜first’, β€˜second’, β€˜third’]" }, { "code": null, "e": 26845, "s": 26788, "text": "[β€˜first’, β€˜second’, β€˜third’, β€˜sixth’, β€˜fourth’, β€˜fifth’]" }, { "code": null, "e": 26892, "s": 26845, "text": "[β€˜first’, β€˜third’, β€˜sixth’, β€˜fourth’, β€˜fifth’]" }, { "code": null, "e": 27097, "s": 26892, "text": "A stack is a linear structure that allows data to be inserted and removed from the same end thus follows a last in first out(LIFO) system. Insertion and deletion is known as push() and pop() respectively." }, { "code": null, "e": 27106, "s": 27097, "text": "Program:" }, { "code": null, "e": 27114, "s": 27106, "text": "Python3" }, { "code": "stack = ['first', 'second', 'third']print(stack) print() # pushing elementsstack.append('fourth')stack.append('fifth')print(stack)print() # printing topn = len(stack)print(stack[n-1])print() # poping elementstack.pop()print(stack)", "e": 27345, "s": 27114, "text": null }, { "code": null, "e": 27353, "s": 27345, "text": "Output:" }, { "code": null, "e": 27382, "s": 27353, "text": "[β€˜first’, β€˜second’, β€˜third’]" }, { "code": null, "e": 27430, "s": 27382, "text": "[β€˜first’, β€˜second’, β€˜third’, β€˜fourth’, β€˜fifth’]" }, { "code": null, "e": 27436, "s": 27430, "text": "fifth" }, { "code": null, "e": 27475, "s": 27436, "text": "[β€˜first’, β€˜second’, β€˜third’, β€˜fourth’]" }, { "code": null, "e": 27759, "s": 27475, "text": "A queue is a linear structure that allows insertion of elements from one end and deletion from the other. Thus it follows, First In First Out(FIFO) methodology. The end which allows deletion is known as the front of the queue and the other end is known as the rear end of the queue. " }, { "code": null, "e": 27768, "s": 27759, "text": "Program:" }, { "code": null, "e": 27776, "s": 27768, "text": "Python3" }, { "code": "queue = ['first', 'second', 'third']print(queue) print() # pushing elementsqueue.append('fourth')queue.append('fifth')print(queue)print() # printing headprint(queue[0]) # printing tailn = len(queue)print(queue[n-1])print() # poping elementqueue.remove(queue[0])print(queue)", "e": 28050, "s": 27776, "text": null }, { "code": null, "e": 28058, "s": 28050, "text": "Output:" }, { "code": null, "e": 28087, "s": 28058, "text": "[β€˜first’, β€˜second’, β€˜third’]" }, { "code": null, "e": 28135, "s": 28087, "text": "[β€˜first’, β€˜second’, β€˜third’, β€˜fourth’, β€˜fifth’]" }, { "code": null, "e": 28141, "s": 28135, "text": "first" }, { "code": null, "e": 28147, "s": 28141, "text": "fifth" }, { "code": null, "e": 28186, "s": 28147, "text": "[β€˜second’, β€˜third’, β€˜fourth’, β€˜fifth’]" }, { "code": null, "e": 28514, "s": 28186, "text": "A tree is a non-linear but hierarchical data structure. The topmost element is known as the root of the tree since the tree is believed to start from the root. The elements at the end of the tree are known as its leaves. Trees are appropriate for storing data that aren’t linearly connected to each other but form a hierarchy. " }, { "code": null, "e": 28523, "s": 28514, "text": "Program:" }, { "code": null, "e": 28531, "s": 28523, "text": "Python3" }, { "code": "class node: def __init__(self, ele): self.ele = ele self.left = None self.right = None def preorder(self): if self: print(self.ele) preorder(self.left) preorder(self.right) n = node('first')n.left = node('second')n.right = node('third')preorder(n)", "e": 28829, "s": 28531, "text": null }, { "code": null, "e": 28837, "s": 28829, "text": "Output:" }, { "code": null, "e": 28843, "s": 28837, "text": "first" }, { "code": null, "e": 28850, "s": 28843, "text": "second" }, { "code": null, "e": 28856, "s": 28850, "text": "third" }, { "code": null, "e": 29156, "s": 28856, "text": "A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes." }, { "code": null, "e": 29165, "s": 29156, "text": "Program:" }, { "code": null, "e": 29173, "s": 29165, "text": "Python3" }, { "code": "class adjnode: def __init__(self, val): self.val = val self.next = None class graph: def __init__(self, vertices): self.v = vertices self.ele = [None]*self.v def edge(self, src, dest): node = adjnode(dest) node.next = self.ele[src] self.ele[src] = node node = adjnode(src) node.next = self.ele[dest] self.ele[dest] = node def __repr__(self): for i in range(self.v): print(\"Adjacency list of vertex {}\\n head\".format(i), end=\"\") temp = self.ele[i] while temp: print(\" -> {}\".format(temp.val), end=\"\") temp = temp.next g = graph(4)g.edge(0, 2)g.edge(1, 3)g.edge(3, 2)g.edge(0, 3)g.__repr__()", "e": 29920, "s": 29173, "text": null }, { "code": null, "e": 29928, "s": 29920, "text": "Output:" }, { "code": null, "e": 29955, "s": 29928, "text": "Adjacency list of vertex 0" }, { "code": null, "e": 29970, "s": 29955, "text": "head -> 3 -> 2" }, { "code": null, "e": 29997, "s": 29970, "text": "Adjacency list of vertex 1" }, { "code": null, "e": 30007, "s": 29997, "text": "head -> 3" }, { "code": null, "e": 30034, "s": 30007, "text": "Adjacency list of vertex 2" }, { "code": null, "e": 30049, "s": 30034, "text": "head -> 3 -> 0" }, { "code": null, "e": 30076, "s": 30049, "text": "Adjacency list of vertex 3" }, { "code": null, "e": 30096, "s": 30076, "text": "head -> 0 -> 2 -> 1" }, { "code": null, "e": 30389, "s": 30096, "text": "Hash maps are indexed data structures. A hash map makes use of a hash function to compute an index with a key into an array of buckets or slots. Its value is mapped to the bucket with the corresponding index. The key is unique and immutable. In Python, dictionaries are examples of hash maps." }, { "code": null, "e": 30398, "s": 30389, "text": "Program:" }, { "code": null, "e": 30406, "s": 30398, "text": "Python3" }, { "code": "def printdict(d): for key in d: print(key, \"->\", d[key]) hm = {0: 'first', 1: 'second', 2: 'third'}printdict(hm)print() hm[3] = 'fourth'printdict(hm)print() hm.popitem()printdict(hm)", "e": 30600, "s": 30406, "text": null }, { "code": null, "e": 30608, "s": 30600, "text": "Output:" }, { "code": null, "e": 30619, "s": 30608, "text": "0 -> first" }, { "code": null, "e": 30631, "s": 30619, "text": "1 -> second" }, { "code": null, "e": 30642, "s": 30631, "text": "2 -> third" }, { "code": null, "e": 30653, "s": 30642, "text": "0 -> first" }, { "code": null, "e": 30665, "s": 30653, "text": "1 -> second" }, { "code": null, "e": 30676, "s": 30665, "text": "2 -> third" }, { "code": null, "e": 30688, "s": 30676, "text": "3 -> fourth" }, { "code": null, "e": 30699, "s": 30688, "text": "0 -> first" }, { "code": null, "e": 30711, "s": 30699, "text": "1 -> second" }, { "code": null, "e": 30722, "s": 30711, "text": "2 -> third" }, { "code": null, "e": 30737, "s": 30722, "text": "sagartomar9927" }, { "code": null, "e": 30754, "s": 30737, "text": "Python-Data Type" }, { "code": null, "e": 30778, "s": 30754, "text": "Technical Scripter 2020" }, { "code": null, "e": 30785, "s": 30778, "text": "Python" }, { "code": null, "e": 30804, "s": 30785, "text": "Technical Scripter" }, { "code": null, "e": 30902, "s": 30804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30934, "s": 30902, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30976, "s": 30934, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31018, "s": 30976, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31045, "s": 31018, "text": "Python Classes and Objects" }, { "code": null, "e": 31101, "s": 31045, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31140, "s": 31101, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31162, "s": 31140, "text": "Defaultdict in Python" }, { "code": null, "e": 31193, "s": 31162, "text": "Python | os.path.join() method" }, { "code": null, "e": 31222, "s": 31193, "text": "Create a directory in Python" } ]
wxPython - Set window in center of screen - GeeksforGeeks
10 Mar, 2022 In this article we are going to learn that, how can we show window in the center of the screen. We can do this by using a Centre() function in wx.Frame module. Syntax: wx.Frame.Centre(self, direction = wx.BOTH) Parameters: Example #1: Python3 # import wxPythonimport wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title = title, size =(300, 200)) # Centre frame using Centre() function self.Centre() def main(): app = wx.App() ex = Example(None, title ='Centering') ex.Show() app.MainLoop() if __name__ == '__main__': main() Output: Example #2: Python3 # import wxPythonimport wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title = title, size =(300, 200)) # Centre frame using Centre() function self.Centre(direction = wx.VERTICAL) def main(): app = wx.App() ex = Example(None, title ='Centering') ex.Show() app.MainLoop() if __name__ == '__main__': main() Output: ysachin2314 ManasChhabra2 Python-gui Python-wxPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Enumerate() in Python Python Dictionary Defaultdict in Python sum() function in Python Python String | replace() Read a file line by line in Python How to Install PIP on Windows ? Deque in Python Different ways to create Pandas Dataframe Iterate over a list in Python
[ { "code": null, "e": 26083, "s": 26055, "text": "\n10 Mar, 2022" }, { "code": null, "e": 26245, "s": 26083, "text": "In this article we are going to learn that, how can we show window in the center of the screen. We can do this by using a Centre() function in wx.Frame module. " }, { "code": null, "e": 26255, "s": 26245, "text": "Syntax: " }, { "code": null, "e": 26298, "s": 26255, "text": "wx.Frame.Centre(self, direction = wx.BOTH)" }, { "code": null, "e": 26312, "s": 26298, "text": "Parameters: " }, { "code": null, "e": 26328, "s": 26314, "text": "Example #1: " }, { "code": null, "e": 26336, "s": 26328, "text": "Python3" }, { "code": "# import wxPythonimport wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title = title, size =(300, 200)) # Centre frame using Centre() function self.Centre() def main(): app = wx.App() ex = Example(None, title ='Centering') ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 26758, "s": 26336, "text": null }, { "code": null, "e": 26768, "s": 26758, "text": "Output: " }, { "code": null, "e": 26782, "s": 26768, "text": "Example #2: " }, { "code": null, "e": 26790, "s": 26782, "text": "Python3" }, { "code": "# import wxPythonimport wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title = title, size =(300, 200)) # Centre frame using Centre() function self.Centre(direction = wx.VERTICAL) def main(): app = wx.App() ex = Example(None, title ='Centering') ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 27234, "s": 26790, "text": null }, { "code": null, "e": 27244, "s": 27234, "text": "Output: " }, { "code": null, "e": 27258, "s": 27246, "text": "ysachin2314" }, { "code": null, "e": 27272, "s": 27258, "text": "ManasChhabra2" }, { "code": null, "e": 27283, "s": 27272, "text": "Python-gui" }, { "code": null, "e": 27299, "s": 27283, "text": "Python-wxPython" }, { "code": null, "e": 27306, "s": 27299, "text": "Python" }, { "code": null, "e": 27404, "s": 27306, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27426, "s": 27404, "text": "Enumerate() in Python" }, { "code": null, "e": 27444, "s": 27426, "text": "Python Dictionary" }, { "code": null, "e": 27466, "s": 27444, "text": "Defaultdict in Python" }, { "code": null, "e": 27491, "s": 27466, "text": "sum() function in Python" }, { "code": null, "e": 27517, "s": 27491, "text": "Python String | replace()" }, { "code": null, "e": 27552, "s": 27517, "text": "Read a file line by line in Python" }, { "code": null, "e": 27584, "s": 27552, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27600, "s": 27584, "text": "Deque in Python" }, { "code": null, "e": 27642, "s": 27600, "text": "Different ways to create Pandas Dataframe" } ]
Program to implement Linear Extrapolation - GeeksforGeeks
25 Nov, 2021 What is Extrapolation? Extrapolation is the process in mathematics where the required value is estimated beyond the range the of the given variable range. Extrapolation is often used to estimate the data of some observation below or above the given range. Extrapolation is also referred to as a mathematical prediction to predict values by observing the relationship between the given variables. There are many processes of Extrapolation.Here only Linear Extrapolation will be discussed. This process was first described by Thomas D. Clareson in 1959 in his book of science. He referred to it as a meaningful prediction by understanding the given data. How to calculate Linear Exptrapolation?The method is useful when the linear function is given. It is done by drawing a tangent and extending it beyond the limit. Linear Extrapolation gives a very good result when the point to be predicted is not very far from the rest of the points. Extrapolation formula: Here and are two given points and x is the point for which we want to predict the value of y.Examples: Input: , , x = 1.2 Output: y = 3.15 Implementation: C++ Java Python3 C# PHP Javascript // C++ code for the implementation// of Linear extrapolation #include <bits/stdc++.h>using namespace std; // Consider a structure// to keep each pair of x and y togetherstruct Data { double x, y;}; // Function to calculate// the linear extrapolationdouble extrapolate(Data d[], double x){ double y; y = d[0].y + (x - d[0].x) / (d[1].x - d[0].x) * (d[1].y - d[0].y); return y;} // Driver Codeint main(){ // Sample dataset Data d[] = { { 1.2, 2.7 }, { 1.4, 3.1 } }; // Sample x value double x = 2.1; // Finding the extrapolation cout << "Value of y at x = 2.1 : " << extrapolate(d, x); return 0;} // Java code for the implementation of// Linear extrapolationclass GFG{ // Function to calculate the linear// extrapolationstatic double extrapolate(double[][] d, double x){ double y = d[0][1] + (x - d[0][0]) / (d[1][0] - d[0][0]) * (d[1][1] - d[0][1]); return y;} // Driver Codepublic static void main (String[] args){ // Sample datasetdouble[][] d = {{ 1.2, 2.7 },{ 1.4, 3.1 }}; // Sample x valuedouble x = 2.1; // Finding the extrapolationSystem.out.println("Value of y at x = 2.1 : " + extrapolate(d, x));}} // This code is contributed by chandan_jnu # Python3 code for the implementation of# Linear extrapolation # Function to calculate the linear# extrapolationdef extrapolate(d, x): y = (d[0][1] + (x - d[0][0]) / (d[1][0] - d[0][0]) * (d[1][1] - d[0][1])); return y; # Driver Code # Sample datasetd = [[ 1.2, 2.7 ], [1.4, 3.1 ]]; # Sample x valuex = 2.1; # Finding the extrapolationprint("Value of y at x = 2.1 :", extrapolate(d, x)); # This code is contributed by mits // C# code for the implementation of// Linear extrapolationclass GFG{ // Function to calculate the linear// extrapolationstatic double extrapolate(double[,] d, double x){ double y = d[0,1] + (x - d[0,0]) / (d[1,0] - d[0,0]) * (d[1,1] - d[0,1]); return y;} // Driver Codestatic void Main(){ // Sample datasetdouble[,] d = {{ 1.2, 2.7 },{ 1.4, 3.1 }}; // Sample x valuedouble x = 2.1; // Finding the extrapolationSystem.Console.WriteLine("Value of y at x = 2.1 : " + extrapolate(d, x));}} // This code is contributed by chandan_jnu <?php// PHP code for the implementation of// Linear extrapolation // Function to calculate the linear// extrapolationfunction extrapolate($d, $x){ $y = $d[0][1] + ($x - $d[0][0]) / ($d[1][0] - $d[0][0]) * ($d[1][1] - $d[0][1]); return $y;} // Driver Code // Sample dataset$d = array(array( 1.2, 2.7 ), array( 1.4, 3.1 )); // Sample x value$x = 2.1; // Finding the extrapolationecho "Value of y at x = 2.1 : ", extrapolate($d, $x); // This code is contributed by Ryuga?> <script> // Javascript code for the implementation of // Linear extrapolation // Function to calculate the linear // extrapolation function extrapolate(d, x) { let y = d[0][1] + (x - d[0][0]) / (d[1][0] - d[0][0]) * (d[1][1] - d[0][1]); return y; } // Sample dataset let d = [[ 1.2, 2.7 ],[ 1.4, 3.1 ]]; // Sample x value let x = 2.1; // Finding the extrapolation document.write("Value of y at x = 2.1 : " + extrapolate(d, x)); // This code is contributed by mukesh07.</script> Value of y at x = 2.1 : 4.5 ankthon Mithun Kumar Chandan_Kumar mukesh07 rajeev0719singh Algebra C++ Programs Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25876, "s": 25848, "text": "\n25 Nov, 2021" }, { "code": null, "e": 26814, "s": 25876, "text": "What is Extrapolation? Extrapolation is the process in mathematics where the required value is estimated beyond the range the of the given variable range. Extrapolation is often used to estimate the data of some observation below or above the given range. Extrapolation is also referred to as a mathematical prediction to predict values by observing the relationship between the given variables. There are many processes of Extrapolation.Here only Linear Extrapolation will be discussed. This process was first described by Thomas D. Clareson in 1959 in his book of science. He referred to it as a meaningful prediction by understanding the given data. How to calculate Linear Exptrapolation?The method is useful when the linear function is given. It is done by drawing a tangent and extending it beyond the limit. Linear Extrapolation gives a very good result when the point to be predicted is not very far from the rest of the points. " }, { "code": null, "e": 26838, "s": 26814, "text": "Extrapolation formula: " }, { "code": null, "e": 26943, "s": 26838, "text": "Here and are two given points and x is the point for which we want to predict the value of y.Examples: " }, { "code": null, "e": 26981, "s": 26943, "text": "Input: , , x = 1.2 Output: y = 3.15 " }, { "code": null, "e": 27003, "s": 26985, "text": "Implementation: " }, { "code": null, "e": 27007, "s": 27003, "text": "C++" }, { "code": null, "e": 27012, "s": 27007, "text": "Java" }, { "code": null, "e": 27020, "s": 27012, "text": "Python3" }, { "code": null, "e": 27023, "s": 27020, "text": "C#" }, { "code": null, "e": 27027, "s": 27023, "text": "PHP" }, { "code": null, "e": 27038, "s": 27027, "text": "Javascript" }, { "code": "// C++ code for the implementation// of Linear extrapolation #include <bits/stdc++.h>using namespace std; // Consider a structure// to keep each pair of x and y togetherstruct Data { double x, y;}; // Function to calculate// the linear extrapolationdouble extrapolate(Data d[], double x){ double y; y = d[0].y + (x - d[0].x) / (d[1].x - d[0].x) * (d[1].y - d[0].y); return y;} // Driver Codeint main(){ // Sample dataset Data d[] = { { 1.2, 2.7 }, { 1.4, 3.1 } }; // Sample x value double x = 2.1; // Finding the extrapolation cout << \"Value of y at x = 2.1 : \" << extrapolate(d, x); return 0;}", "e": 27711, "s": 27038, "text": null }, { "code": "// Java code for the implementation of// Linear extrapolationclass GFG{ // Function to calculate the linear// extrapolationstatic double extrapolate(double[][] d, double x){ double y = d[0][1] + (x - d[0][0]) / (d[1][0] - d[0][0]) * (d[1][1] - d[0][1]); return y;} // Driver Codepublic static void main (String[] args){ // Sample datasetdouble[][] d = {{ 1.2, 2.7 },{ 1.4, 3.1 }}; // Sample x valuedouble x = 2.1; // Finding the extrapolationSystem.out.println(\"Value of y at x = 2.1 : \" + extrapolate(d, x));}} // This code is contributed by chandan_jnu", "e": 28330, "s": 27711, "text": null }, { "code": "# Python3 code for the implementation of# Linear extrapolation # Function to calculate the linear# extrapolationdef extrapolate(d, x): y = (d[0][1] + (x - d[0][0]) / (d[1][0] - d[0][0]) * (d[1][1] - d[0][1])); return y; # Driver Code # Sample datasetd = [[ 1.2, 2.7 ], [1.4, 3.1 ]]; # Sample x valuex = 2.1; # Finding the extrapolationprint(\"Value of y at x = 2.1 :\", extrapolate(d, x)); # This code is contributed by mits", "e": 28786, "s": 28330, "text": null }, { "code": "// C# code for the implementation of// Linear extrapolationclass GFG{ // Function to calculate the linear// extrapolationstatic double extrapolate(double[,] d, double x){ double y = d[0,1] + (x - d[0,0]) / (d[1,0] - d[0,0]) * (d[1,1] - d[0,1]); return y;} // Driver Codestatic void Main(){ // Sample datasetdouble[,] d = {{ 1.2, 2.7 },{ 1.4, 3.1 }}; // Sample x valuedouble x = 2.1; // Finding the extrapolationSystem.Console.WriteLine(\"Value of y at x = 2.1 : \" + extrapolate(d, x));}} // This code is contributed by chandan_jnu", "e": 29380, "s": 28786, "text": null }, { "code": "<?php// PHP code for the implementation of// Linear extrapolation // Function to calculate the linear// extrapolationfunction extrapolate($d, $x){ $y = $d[0][1] + ($x - $d[0][0]) / ($d[1][0] - $d[0][0]) * ($d[1][1] - $d[0][1]); return $y;} // Driver Code // Sample dataset$d = array(array( 1.2, 2.7 ), array( 1.4, 3.1 )); // Sample x value$x = 2.1; // Finding the extrapolationecho \"Value of y at x = 2.1 : \", extrapolate($d, $x); // This code is contributed by Ryuga?>", "e": 29892, "s": 29380, "text": null }, { "code": "<script> // Javascript code for the implementation of // Linear extrapolation // Function to calculate the linear // extrapolation function extrapolate(d, x) { let y = d[0][1] + (x - d[0][0]) / (d[1][0] - d[0][0]) * (d[1][1] - d[0][1]); return y; } // Sample dataset let d = [[ 1.2, 2.7 ],[ 1.4, 3.1 ]]; // Sample x value let x = 2.1; // Finding the extrapolation document.write(\"Value of y at x = 2.1 : \" + extrapolate(d, x)); // This code is contributed by mukesh07.</script>", "e": 30478, "s": 29892, "text": null }, { "code": null, "e": 30506, "s": 30478, "text": "Value of y at x = 2.1 : 4.5" }, { "code": null, "e": 30516, "s": 30508, "text": "ankthon" }, { "code": null, "e": 30529, "s": 30516, "text": "Mithun Kumar" }, { "code": null, "e": 30543, "s": 30529, "text": "Chandan_Kumar" }, { "code": null, "e": 30552, "s": 30543, "text": "mukesh07" }, { "code": null, "e": 30568, "s": 30552, "text": "rajeev0719singh" }, { "code": null, "e": 30576, "s": 30568, "text": "Algebra" }, { "code": null, "e": 30589, "s": 30576, "text": "C++ Programs" }, { "code": null, "e": 30602, "s": 30589, "text": "Mathematical" }, { "code": null, "e": 30615, "s": 30602, "text": "Mathematical" }, { "code": null, "e": 30713, "s": 30615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30754, "s": 30713, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 30813, "s": 30754, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 30834, "s": 30813, "text": "Const keyword in C++" }, { "code": null, "e": 30846, "s": 30834, "text": "cout in C++" }, { "code": null, "e": 30867, "s": 30846, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 30897, "s": 30867, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30957, "s": 30897, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30972, "s": 30957, "text": "C++ Data Types" }, { "code": null, "e": 31015, "s": 30972, "text": "Set in C++ Standard Template Library (STL)" } ]
Josephus Problem | (Iterative Solution) - GeeksforGeeks
22 Jan, 2020 There are N Children are seated on N chairs arranged around a circle. The chairs are numbered from 1 to N. The game starts going in circles counting the children starting with the first chair. Once the count reaches K, that child leaves the game, removing his/her chair. The game starts again, beginning with the next chair in the circle. The last child remaining in the circle is the winner. Find the child that wins the game. Examples: Input : N = 5, K = 2 Output : 3 Firstly, the child at position 2 is out, then position 4 goes out, then position 1 Finally, the child at position 5 is out. So the position 3 survives. Input : 7 4 Output : 2 We have discussed a recursive solution for Josephus Problem . The given solution is better than the recursive solution of Josephus Solution which is not suitable for large inputs as it gives stack overflow. The time complexity is O(N). Approach – In the algorithm, we use sum variable to find out the chair to be removed. The current chair position is calculated by adding the chair count K to the previous position i.e. sum and modulus of the sum. At last we return sum+1 as numbering starts from 1 to N. C++ Java // Iterative solution for Josephus Problem #include <bits/stdc++.h>using namespace std; // Function for finding the winning child.long long int find(long long int n, long long int k){ long long int sum = 0, i; // For finding out the removed // chairs in each iteration for (i = 2; i <= n; i++) sum = (sum + k) % i; return sum + 1;} // Driver function to find the winning childint main(){ int n = 14, k = 2; cout << find(n, k); return 0;} // Iterative solution for Josephus Problemclass Test { // Method for finding the winning child. private int josephus(int n, int k) { int sum = 0; // For finding out the removed // chairs in each iteration for(int i = 2; i <= n; i++) { sum = (sum + k) % i; } return sum+1; } // Driver Program to test above method public static void main(String[] args) { int n = 14; int k = 2; Test obj = new Test(); System.out.println(obj.josephus(n, k)); }} // This code is contributed by Kumar Saras 13 KumarSaras programming-puzzle Game Theory Searching Searching Game Theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Classification of Algorithms with Examples A Binary String Game Random Number Memory Game in C Two player game in which a player can remove all occurrences of a number Find the winner of the Game to Win by erasing any two consecutive similar alphabets Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26451, "s": 26423, "text": "\n22 Jan, 2020" }, { "code": null, "e": 26879, "s": 26451, "text": "There are N Children are seated on N chairs arranged around a circle. The chairs are numbered from 1 to N. The game starts going in circles counting the children starting with the first chair. Once the count reaches K, that child leaves the game, removing his/her chair. The game starts again, beginning with the next chair in the circle. The last child remaining in the circle is the winner. Find the child that wins the game." }, { "code": null, "e": 26889, "s": 26879, "text": "Examples:" }, { "code": null, "e": 27100, "s": 26889, "text": "Input : N = 5, K = 2\nOutput : 3\nFirstly, the child at position 2 is out, \nthen position 4 goes out, then position 1\nFinally, the child at position 5 is out. \nSo the position 3 survives.\n\nInput : 7 4\nOutput : 2\n" }, { "code": null, "e": 27336, "s": 27100, "text": "We have discussed a recursive solution for Josephus Problem . The given solution is better than the recursive solution of Josephus Solution which is not suitable for large inputs as it gives stack overflow. The time complexity is O(N)." }, { "code": null, "e": 27606, "s": 27336, "text": "Approach – In the algorithm, we use sum variable to find out the chair to be removed. The current chair position is calculated by adding the chair count K to the previous position i.e. sum and modulus of the sum. At last we return sum+1 as numbering starts from 1 to N." }, { "code": null, "e": 27610, "s": 27606, "text": "C++" }, { "code": null, "e": 27615, "s": 27610, "text": "Java" }, { "code": "// Iterative solution for Josephus Problem #include <bits/stdc++.h>using namespace std; // Function for finding the winning child.long long int find(long long int n, long long int k){ long long int sum = 0, i; // For finding out the removed // chairs in each iteration for (i = 2; i <= n; i++) sum = (sum + k) % i; return sum + 1;} // Driver function to find the winning childint main(){ int n = 14, k = 2; cout << find(n, k); return 0;}", "e": 28091, "s": 27615, "text": null }, { "code": "// Iterative solution for Josephus Problemclass Test { // Method for finding the winning child. private int josephus(int n, int k) { int sum = 0; // For finding out the removed // chairs in each iteration for(int i = 2; i <= n; i++) { sum = (sum + k) % i; } return sum+1; } // Driver Program to test above method public static void main(String[] args) { int n = 14; int k = 2; Test obj = new Test(); System.out.println(obj.josephus(n, k)); }} // This code is contributed by Kumar Saras", "e": 28707, "s": 28091, "text": null }, { "code": null, "e": 28711, "s": 28707, "text": "13\n" }, { "code": null, "e": 28722, "s": 28711, "text": "KumarSaras" }, { "code": null, "e": 28741, "s": 28722, "text": "programming-puzzle" }, { "code": null, "e": 28753, "s": 28741, "text": "Game Theory" }, { "code": null, "e": 28763, "s": 28753, "text": "Searching" }, { "code": null, "e": 28773, "s": 28763, "text": "Searching" }, { "code": null, "e": 28785, "s": 28773, "text": "Game Theory" }, { "code": null, "e": 28883, "s": 28785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28926, "s": 28883, "text": "Classification of Algorithms with Examples" }, { "code": null, "e": 28947, "s": 28926, "text": "A Binary String Game" }, { "code": null, "e": 28978, "s": 28947, "text": "Random Number Memory Game in C" }, { "code": null, "e": 29051, "s": 28978, "text": "Two player game in which a player can remove all occurrences of a number" }, { "code": null, "e": 29135, "s": 29051, "text": "Find the winner of the Game to Win by erasing any two consecutive similar alphabets" }, { "code": null, "e": 29149, "s": 29135, "text": "Binary Search" }, { "code": null, "e": 29217, "s": 29149, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 29231, "s": 29217, "text": "Linear Search" }, { "code": null, "e": 29279, "s": 29231, "text": "Search an element in a sorted and rotated array" } ]
Program to calculate the number of odd days in given number of years - GeeksforGeeks
01 Apr, 2021 Given an integer N, the task is to find the number of odd days in the years from 1 to N. Odd Days: Number of odd days refer to those days that are left in a certain year(s) when it’s days gets converted into weeks. Say, an ordinary year has 365 days, that is 52 weeks and one odd day. This means, out of the 365 days in an ordinary year, 364 days will get converted into 52 weeks and one day will remain. This one day is referred to as 1 odd day. Simply the modulus total number of days by 7(days in a week) gives us the number of odd days. It’s value lies between 0 to 6 only. [0, 6] Leap Year: Every year divisible either by 400 or by 4 but not 100 Ordinary Year: Years Except Leap Years Every Ordinary Year has 1 odd day. Every Leap Year has 2 odd days. Examples: Input: N = 8 Output: 3 Out of the 8 years, 4 and 8 are the only leap years. (6 x 1) + (2 x 2) = 10 i.e. 1 week and 3 daysInput: N = 400 Output: 0 Approach: Count number of ordinary years and number of leap years out of given N years.Calculate the overall number of days.Print the modulo(7) of the total number of days. Count number of ordinary years and number of leap years out of given N years. Calculate the overall number of days. Print the modulo(7) of the total number of days. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to return the count of odd daysint oddDays(int N){ // Count of years divisible // by 100 and 400 int hund1 = N / 100; int hund4 = N / 400; // Every 4th year is a leap year int leap = N >> 2; int ord = N - leap; // Every 100th year is divisible by 4 // but is not a leap year if (hund1) { ord += hund1; leap -= hund1; } // Every 400th year is divisible by 100 // but is a leap year if (hund4) { ord -= hund4; leap += hund4; } // Total number of extra days int days = ord + leap * 2; // modulo(7) for final answer int odd = days % 7; return odd;} // Driver codeint main(){ // Number of days int N = 100; cout << oddDays(N); return 0;} // Java implementation of the approachclass GFG { // Function to return the count of odd days static int oddDays(int N) { // Count of years divisible // by 100 and 400 int hund1 = N / 100; int hund4 = N / 400; // Every 4th year is a leap year int leap = N >> 2; int ord = N - leap; // Every 100th year is divisible by 4 // but is not a leap year if (hund1 > 0) { ord += hund1; leap -= hund1; } // Every 400th year is divisible by 100 // but is a leap year if (hund4 > 0) { ord -= hund4; leap += hund4; } // Total number of extra days int days = ord + leap * 2; // modulo(7) for final answer int odd = days % 7; return odd; } // Driver code public static void main(String args[]) { // Number of days int N = 100; System.out.print(oddDays(N)); }} # Python3 implementation of the approach # Function to return the count of odd daysdef oddDays(N): # Count of years divisible # by 100 and 400 hund1 = N // 100 hund4 = N // 400 # Every 4th year is a leap year leap = N >> 2 ordd = N - leap # Every 100th year is divisible by 4 # but is not a leap year if (hund1): ordd += hund1 leap -= hund1 # Every 400th year is divisible by 100 # but is a leap year if (hund4): ordd -= hund4 leap += hund4 # Total number of extra days days = ordd + leap * 2 # modulo(7) for final answer odd = days % 7 return odd # Driver code # Number of daysN = 100print(oddDays(N)) # This code is contributed# by mohit kumar // C# implementation of the approachusing System; class GFG{ // Function to return the count of odd days static int oddDays(int N) { // Count of years divisible // by 100 and 400 int hund1 = N / 100; int hund4 = N / 400; // Every 4th year is a leap year int leap = N >> 2; int ord = N - leap; // Every 100th year is divisible by 4 // but is not a leap year if (hund1 > 0) { ord += hund1; leap -= hund1; } // Every 400th year is divisible by 100 // but is a leap year if (hund4 > 0) { ord -= hund4; leap += hund4; } // Total number of extra days int days = ord + leap * 2; // modulo(7) for final answer int odd = days % 7; return odd; } // Driver code static void Main() { // Number of days int N = 100; Console.WriteLine(oddDays(N)); }} // This code is contributed by mits <?php// PHP implementation of the approach // Function to return the count of odd daysfunction oddDays($N){ // Count of years divisible // by 100 and 400 $hund1 = floor($N / 100); $hund4 = floor($N / 400); // Every 4th year is a leap year $leap = $N >> 2; $ord = $N - $leap; // Every 100th year is divisible by 4 // but is not a leap year if ($hund1) { $ord += $hund1; $leap -= $hund1; } // Every 400th year is divisible by 100 // but is a leap year if ($hund4) { $ord -= $hund4; $leap += $hund4; } // Total number of extra days $days = $ord + $leap * 2; // modulo(7) for final answer $odd = $days % 7; return $odd;} // Driver code // Number of days$N = 100; echo oddDays($N); // This code is contributed by Ryuga?> <script> // JavaScript implementation of the approach // Function to return the count of odd days function oddDays(N) { // Count of years divisible // by 100 and 400 var hund1 = N / 100; var hund4 = N / 400; // Every 4th year is a leap year var leap = N >> 2; var ord = N - leap; // Every 100th year is divisible by 4 // but is not a leap year if (hund1 > 0) { ord += hund1; leap -= hund1; } // Every 400th year is divisible by 100 // but is a leap year if (hund4 > 0) { ord -= hund4; leap += hund4; } // Total number of extra days var days = ord + leap * 2; // modulo(7) for final answer var odd = days % 7; return odd; } // Driver code // Number of days var N = 100; document.write(oddDays(N).toFixed()); // This code is contributed by todaysgaurav </script> 5 mohit kumar 29 Mithun Kumar ankthon todaysgaurav school-programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25937, "s": 25909, "text": "\n01 Apr, 2021" }, { "code": null, "e": 26386, "s": 25937, "text": "Given an integer N, the task is to find the number of odd days in the years from 1 to N. Odd Days: Number of odd days refer to those days that are left in a certain year(s) when it’s days gets converted into weeks. Say, an ordinary year has 365 days, that is 52 weeks and one odd day. This means, out of the 365 days in an ordinary year, 364 days will get converted into 52 weeks and one day will remain. This one day is referred to as 1 odd day. " }, { "code": null, "e": 26480, "s": 26386, "text": "Simply the modulus total number of days by 7(days in a week) gives us the number of odd days." }, { "code": null, "e": 26524, "s": 26480, "text": "It’s value lies between 0 to 6 only. [0, 6]" }, { "code": null, "e": 26590, "s": 26524, "text": "Leap Year: Every year divisible either by 400 or by 4 but not 100" }, { "code": null, "e": 26629, "s": 26590, "text": "Ordinary Year: Years Except Leap Years" }, { "code": null, "e": 26664, "s": 26629, "text": "Every Ordinary Year has 1 odd day." }, { "code": null, "e": 26696, "s": 26664, "text": "Every Leap Year has 2 odd days." }, { "code": null, "e": 26708, "s": 26696, "text": "Examples: " }, { "code": null, "e": 26856, "s": 26708, "text": "Input: N = 8 Output: 3 Out of the 8 years, 4 and 8 are the only leap years. (6 x 1) + (2 x 2) = 10 i.e. 1 week and 3 daysInput: N = 400 Output: 0 " }, { "code": null, "e": 26870, "s": 26858, "text": "Approach: " }, { "code": null, "e": 27033, "s": 26870, "text": "Count number of ordinary years and number of leap years out of given N years.Calculate the overall number of days.Print the modulo(7) of the total number of days." }, { "code": null, "e": 27111, "s": 27033, "text": "Count number of ordinary years and number of leap years out of given N years." }, { "code": null, "e": 27149, "s": 27111, "text": "Calculate the overall number of days." }, { "code": null, "e": 27198, "s": 27149, "text": "Print the modulo(7) of the total number of days." }, { "code": null, "e": 27250, "s": 27198, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27254, "s": 27250, "text": "C++" }, { "code": null, "e": 27259, "s": 27254, "text": "Java" }, { "code": null, "e": 27267, "s": 27259, "text": "Python3" }, { "code": null, "e": 27270, "s": 27267, "text": "C#" }, { "code": null, "e": 27274, "s": 27270, "text": "PHP" }, { "code": null, "e": 27285, "s": 27274, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the count of odd daysint oddDays(int N){ // Count of years divisible // by 100 and 400 int hund1 = N / 100; int hund4 = N / 400; // Every 4th year is a leap year int leap = N >> 2; int ord = N - leap; // Every 100th year is divisible by 4 // but is not a leap year if (hund1) { ord += hund1; leap -= hund1; } // Every 400th year is divisible by 100 // but is a leap year if (hund4) { ord -= hund4; leap += hund4; } // Total number of extra days int days = ord + leap * 2; // modulo(7) for final answer int odd = days % 7; return odd;} // Driver codeint main(){ // Number of days int N = 100; cout << oddDays(N); return 0;}", "e": 28116, "s": 27285, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the count of odd days static int oddDays(int N) { // Count of years divisible // by 100 and 400 int hund1 = N / 100; int hund4 = N / 400; // Every 4th year is a leap year int leap = N >> 2; int ord = N - leap; // Every 100th year is divisible by 4 // but is not a leap year if (hund1 > 0) { ord += hund1; leap -= hund1; } // Every 400th year is divisible by 100 // but is a leap year if (hund4 > 0) { ord -= hund4; leap += hund4; } // Total number of extra days int days = ord + leap * 2; // modulo(7) for final answer int odd = days % 7; return odd; } // Driver code public static void main(String args[]) { // Number of days int N = 100; System.out.print(oddDays(N)); }}", "e": 29099, "s": 28116, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count of odd daysdef oddDays(N): # Count of years divisible # by 100 and 400 hund1 = N // 100 hund4 = N // 400 # Every 4th year is a leap year leap = N >> 2 ordd = N - leap # Every 100th year is divisible by 4 # but is not a leap year if (hund1): ordd += hund1 leap -= hund1 # Every 400th year is divisible by 100 # but is a leap year if (hund4): ordd -= hund4 leap += hund4 # Total number of extra days days = ordd + leap * 2 # modulo(7) for final answer odd = days % 7 return odd # Driver code # Number of daysN = 100print(oddDays(N)) # This code is contributed# by mohit kumar", "e": 29834, "s": 29099, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of odd days static int oddDays(int N) { // Count of years divisible // by 100 and 400 int hund1 = N / 100; int hund4 = N / 400; // Every 4th year is a leap year int leap = N >> 2; int ord = N - leap; // Every 100th year is divisible by 4 // but is not a leap year if (hund1 > 0) { ord += hund1; leap -= hund1; } // Every 400th year is divisible by 100 // but is a leap year if (hund4 > 0) { ord -= hund4; leap += hund4; } // Total number of extra days int days = ord + leap * 2; // modulo(7) for final answer int odd = days % 7; return odd; } // Driver code static void Main() { // Number of days int N = 100; Console.WriteLine(oddDays(N)); }} // This code is contributed by mits", "e": 30859, "s": 29834, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the count of odd daysfunction oddDays($N){ // Count of years divisible // by 100 and 400 $hund1 = floor($N / 100); $hund4 = floor($N / 400); // Every 4th year is a leap year $leap = $N >> 2; $ord = $N - $leap; // Every 100th year is divisible by 4 // but is not a leap year if ($hund1) { $ord += $hund1; $leap -= $hund1; } // Every 400th year is divisible by 100 // but is a leap year if ($hund4) { $ord -= $hund4; $leap += $hund4; } // Total number of extra days $days = $ord + $leap * 2; // modulo(7) for final answer $odd = $days % 7; return $odd;} // Driver code // Number of days$N = 100; echo oddDays($N); // This code is contributed by Ryuga?>", "e": 31676, "s": 30859, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the count of odd days function oddDays(N) { // Count of years divisible // by 100 and 400 var hund1 = N / 100; var hund4 = N / 400; // Every 4th year is a leap year var leap = N >> 2; var ord = N - leap; // Every 100th year is divisible by 4 // but is not a leap year if (hund1 > 0) { ord += hund1; leap -= hund1; } // Every 400th year is divisible by 100 // but is a leap year if (hund4 > 0) { ord -= hund4; leap += hund4; } // Total number of extra days var days = ord + leap * 2; // modulo(7) for final answer var odd = days % 7; return odd; } // Driver code // Number of days var N = 100; document.write(oddDays(N).toFixed()); // This code is contributed by todaysgaurav </script>", "e": 32667, "s": 31676, "text": null }, { "code": null, "e": 32669, "s": 32667, "text": "5" }, { "code": null, "e": 32686, "s": 32671, "text": "mohit kumar 29" }, { "code": null, "e": 32699, "s": 32686, "text": "Mithun Kumar" }, { "code": null, "e": 32707, "s": 32699, "text": "ankthon" }, { "code": null, "e": 32720, "s": 32707, "text": "todaysgaurav" }, { "code": null, "e": 32739, "s": 32720, "text": "school-programming" }, { "code": null, "e": 32752, "s": 32739, "text": "Mathematical" }, { "code": null, "e": 32765, "s": 32752, "text": "Mathematical" }, { "code": null, "e": 32863, "s": 32765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32907, "s": 32863, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 32949, "s": 32907, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 32980, "s": 32949, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33051, "s": 32980, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 33076, "s": 33051, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 33108, "s": 33076, "text": "Check if a number is Palindrome" }, { "code": null, "e": 33141, "s": 33108, "text": "Program to multiply two matrices" }, { "code": null, "e": 33187, "s": 33141, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 33231, "s": 33187, "text": "Generate all permutation of a set in Python" } ]
Check if a string represents a hexadecimal number or not - GeeksforGeeks
13 Apr, 2021 Given an alphanumeric string S of length N, the task is to check if the given string represents a hexadecimal number or not. Print Yes if it represents a hexadecimal number. Otherwise, print No. Examples: Input: S = β€œBF57C” Output: Yes Explanation: Decimal Representation of the given string = 783740 Input: S = β€œ58GK” Output: No Approach: The approach is based on the idea that all the elements of a hexadecimal number lie between characters A to F or between integers 0 to 9. Below are the steps to solve the problem: Iterate over the given string.Check if each character of the string is between characters A to F or between 0 and 9.If found to be true, then print Yes.Otherwise, print No. Iterate over the given string. Check if each character of the string is between characters A to F or between 0 and 9. If found to be true, then print Yes. Otherwise, print No. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the string// represents a hexadecimal numbervoid checkHex(string s){ // Size of string int n = s.length(); // Iterate over string for(int i = 0; i < n; i++) { char ch = s[i]; // Check if the character // is invalid if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F')) { cout << "No" << endl; return; } } // Print true if all // characters are valid cout << "Yes" << endl;} // Driver code int main(){ // Given string string s = "BF57C"; // Function call checkHex(s); return 0;} // This code is contributed by divyeshrabadiya07 // Java implementation of the above approach import java.util.*;import java.io.*; class GFG { // Function to check if the string // represents a hexadecimal number public static void checkHex(String s) { // Size of string int n = s.length(); // Iterate over string for (int i = 0; i < n; i++) { char ch = s.charAt(i); // Check if the character // is invalid if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F')) { System.out.println("No"); return; } } // Print true if all // characters are valid System.out.println("Yes"); } // Driver Code public static void main(String[] args) { // Given string String s = "BF57C"; // Function Call checkHex(s); }} # Python3 implementation of the# above approach # Function to check if the string# represents a hexadecimal numberdef checkHex(s): # Iterate over string for ch in s: # Check if the character # is invalid if ((ch < '0' or ch > '9') and (ch < 'A' or ch > 'F')): print("No") return # Print true if all # characters are valid print("Yes") # Driver Code # Given strings = "BF57C" # Function callcheckHex(s) # This code is contributed by extragornax // C# implementation of// the above approachusing System;class GFG{ // Function to check if the string// represents a hexadecimal numberpublic static void checkHex(String s){ // Size of string int n = s.Length; // Iterate over string for (int i = 0; i < n; i++) { char ch = s[i]; // Check if the character // is invalid if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F')) { Console.WriteLine("No"); return; } } // Print true if all // characters are valid Console.WriteLine("Yes");} // Driver Codepublic static void Main(String[] args){ // Given string String s = "BF57C"; // Function Call checkHex(s);}} // This code is contributed by gauravrajput1 <script> // JavaScript implementation of the// above approach // Function to check if the string// represents a hexadecimal numberfunction checkHex(s){ // Size of string let n = s.length; // Iterate over string for(let i = 0; i < n; i++) { let ch = s[i]; // Check if the character // is invalid if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F')) { document.write("No"); return; } } // Print true if all // characters are valid document.write("Yes");} // Driver code // Given stringlet s = "BF57C"; // Function CallcheckHex(s); // This code is contributed by souravghosh0416 </script> Yes Time Complexity: O(N) Auxiliary Space: O(1) GauravRajput1 divyeshrabadiya07 amit143katiyar sanjoy_62 gaspard souravghosh0416 number-digits Numbers Searching Strings Searching Strings Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best First Search (Informed Search) 3 Different ways to print Fibonacci series in Java Find whether an array is subset of another array | Added Method 5 Given a sorted and rotated array, find if there is a pair with a given sum Program to remove vowels from a String Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26189, "s": 26161, "text": "\n13 Apr, 2021" }, { "code": null, "e": 26384, "s": 26189, "text": "Given an alphanumeric string S of length N, the task is to check if the given string represents a hexadecimal number or not. Print Yes if it represents a hexadecimal number. Otherwise, print No." }, { "code": null, "e": 26394, "s": 26384, "text": "Examples:" }, { "code": null, "e": 26490, "s": 26394, "text": "Input: S = β€œBF57C” Output: Yes Explanation: Decimal Representation of the given string = 783740" }, { "code": null, "e": 26519, "s": 26490, "text": "Input: S = β€œ58GK” Output: No" }, { "code": null, "e": 26709, "s": 26519, "text": "Approach: The approach is based on the idea that all the elements of a hexadecimal number lie between characters A to F or between integers 0 to 9. Below are the steps to solve the problem:" }, { "code": null, "e": 26882, "s": 26709, "text": "Iterate over the given string.Check if each character of the string is between characters A to F or between 0 and 9.If found to be true, then print Yes.Otherwise, print No." }, { "code": null, "e": 26913, "s": 26882, "text": "Iterate over the given string." }, { "code": null, "e": 27000, "s": 26913, "text": "Check if each character of the string is between characters A to F or between 0 and 9." }, { "code": null, "e": 27037, "s": 27000, "text": "If found to be true, then print Yes." }, { "code": null, "e": 27058, "s": 27037, "text": "Otherwise, print No." }, { "code": null, "e": 27109, "s": 27058, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27113, "s": 27109, "text": "C++" }, { "code": null, "e": 27118, "s": 27113, "text": "Java" }, { "code": null, "e": 27126, "s": 27118, "text": "Python3" }, { "code": null, "e": 27129, "s": 27126, "text": "C#" }, { "code": null, "e": 27140, "s": 27129, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the string// represents a hexadecimal numbervoid checkHex(string s){ // Size of string int n = s.length(); // Iterate over string for(int i = 0; i < n; i++) { char ch = s[i]; // Check if the character // is invalid if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F')) { cout << \"No\" << endl; return; } } // Print true if all // characters are valid cout << \"Yes\" << endl;} // Driver code int main(){ // Given string string s = \"BF57C\"; // Function call checkHex(s); return 0;} // This code is contributed by divyeshrabadiya07", "e": 27914, "s": 27140, "text": null }, { "code": "// Java implementation of the above approach import java.util.*;import java.io.*; class GFG { // Function to check if the string // represents a hexadecimal number public static void checkHex(String s) { // Size of string int n = s.length(); // Iterate over string for (int i = 0; i < n; i++) { char ch = s.charAt(i); // Check if the character // is invalid if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F')) { System.out.println(\"No\"); return; } } // Print true if all // characters are valid System.out.println(\"Yes\"); } // Driver Code public static void main(String[] args) { // Given string String s = \"BF57C\"; // Function Call checkHex(s); }}", "e": 28784, "s": 27914, "text": null }, { "code": "# Python3 implementation of the# above approach # Function to check if the string# represents a hexadecimal numberdef checkHex(s): # Iterate over string for ch in s: # Check if the character # is invalid if ((ch < '0' or ch > '9') and (ch < 'A' or ch > 'F')): print(\"No\") return # Print true if all # characters are valid print(\"Yes\") # Driver Code # Given strings = \"BF57C\" # Function callcheckHex(s) # This code is contributed by extragornax", "e": 29332, "s": 28784, "text": null }, { "code": "// C# implementation of// the above approachusing System;class GFG{ // Function to check if the string// represents a hexadecimal numberpublic static void checkHex(String s){ // Size of string int n = s.Length; // Iterate over string for (int i = 0; i < n; i++) { char ch = s[i]; // Check if the character // is invalid if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F')) { Console.WriteLine(\"No\"); return; } } // Print true if all // characters are valid Console.WriteLine(\"Yes\");} // Driver Codepublic static void Main(String[] args){ // Given string String s = \"BF57C\"; // Function Call checkHex(s);}} // This code is contributed by gauravrajput1", "e": 30036, "s": 29332, "text": null }, { "code": "<script> // JavaScript implementation of the// above approach // Function to check if the string// represents a hexadecimal numberfunction checkHex(s){ // Size of string let n = s.length; // Iterate over string for(let i = 0; i < n; i++) { let ch = s[i]; // Check if the character // is invalid if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F')) { document.write(\"No\"); return; } } // Print true if all // characters are valid document.write(\"Yes\");} // Driver code // Given stringlet s = \"BF57C\"; // Function CallcheckHex(s); // This code is contributed by souravghosh0416 </script>", "e": 30733, "s": 30036, "text": null }, { "code": null, "e": 30737, "s": 30733, "text": "Yes" }, { "code": null, "e": 30781, "s": 30737, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 30795, "s": 30781, "text": "GauravRajput1" }, { "code": null, "e": 30813, "s": 30795, "text": "divyeshrabadiya07" }, { "code": null, "e": 30828, "s": 30813, "text": "amit143katiyar" }, { "code": null, "e": 30838, "s": 30828, "text": "sanjoy_62" }, { "code": null, "e": 30846, "s": 30838, "text": "gaspard" }, { "code": null, "e": 30862, "s": 30846, "text": "souravghosh0416" }, { "code": null, "e": 30876, "s": 30862, "text": "number-digits" }, { "code": null, "e": 30884, "s": 30876, "text": "Numbers" }, { "code": null, "e": 30894, "s": 30884, "text": "Searching" }, { "code": null, "e": 30902, "s": 30894, "text": "Strings" }, { "code": null, "e": 30912, "s": 30902, "text": "Searching" }, { "code": null, "e": 30920, "s": 30912, "text": "Strings" }, { "code": null, "e": 30928, "s": 30920, "text": "Numbers" }, { "code": null, "e": 31026, "s": 30928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31062, "s": 31026, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 31113, "s": 31062, "text": "3 Different ways to print Fibonacci series in Java" }, { "code": null, "e": 31179, "s": 31113, "text": "Find whether an array is subset of another array | Added Method 5" }, { "code": null, "e": 31254, "s": 31179, "text": "Given a sorted and rotated array, find if there is a pair with a given sum" }, { "code": null, "e": 31293, "s": 31254, "text": "Program to remove vowels from a String" }, { "code": null, "e": 31339, "s": 31293, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31364, "s": 31339, "text": "Reverse a string in Java" }, { "code": null, "e": 31424, "s": 31364, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31439, "s": 31424, "text": "C++ Data Types" } ]
Storage Definition Languages (SDL) - GeeksforGeeks
11 Sep, 2020 DBMS supports many languages out of which (SDL) is one of them. SDL stands for Storage Definition Language. SDL matter is almost anything that’s not specified by SQL standard. It is different in every DBMS which specifies anything to do with how or where data in relevant table is stored. It’s applications are as follows : Used to define internal schema. It defines physical structure of database. The order of fields. Bytes per field will be used. How records will be accesses etc. The mapping between two schema may also be defined. Example : Let us take some examples to understand how Storage Definition Language (SDL) works. Example-1 : CREATE TABLE geeksforgeeks (no_of_articles INT) ENGINE = INNODB; In the above example, we specify storage engine to be used by adding ENGINE option. InnoDB is default storage engine for MySQL 8.0. Example-2 : CREATE TABLE geeksforgeeks (article_titile varchar(65000) ENGINE = MEMORY; This time, engine used is MEMORY. MEMORY storage engine (also known as HEAP) creates tables for particular purpose with contents that are stored in memory. Because the data is vulnerable to power outages, crashes or hardware issues, only use these tables as temporary work areas or read-only caches for data pulled from other tables. Example-3 : CREATE TABLE f (x int, y varchar(25)); In the above statement, Storage Definition Language (SDL) defines storage of row int, varchar(25). Indeed, In most relational database management systems (RDBMS) there is no specific language that performs the role of SDL. Instead, combination of functions, parameters, and specifications related to storage of files define internal schema. Picked DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Deadlock in DBMS Types of Functional dependencies in DBMS KDD Process in Data Mining Conflict Serializability in DBMS What is Temporary Table in SQL? Two Phase Locking Protocol Introduction of Relational Algebra in DBMS MySQL | Regular expressions (Regexp) Difference between Where and Having Clause in SQL Difference between File System and DBMS
[ { "code": null, "e": 25549, "s": 25521, "text": "\n11 Sep, 2020" }, { "code": null, "e": 25873, "s": 25549, "text": "DBMS supports many languages out of which (SDL) is one of them. SDL stands for Storage Definition Language. SDL matter is almost anything that’s not specified by SQL standard. It is different in every DBMS which specifies anything to do with how or where data in relevant table is stored. It’s applications are as follows :" }, { "code": null, "e": 25905, "s": 25873, "text": "Used to define internal schema." }, { "code": null, "e": 25948, "s": 25905, "text": "It defines physical structure of database." }, { "code": null, "e": 25969, "s": 25948, "text": "The order of fields." }, { "code": null, "e": 25999, "s": 25969, "text": "Bytes per field will be used." }, { "code": null, "e": 26033, "s": 25999, "text": "How records will be accesses etc." }, { "code": null, "e": 26085, "s": 26033, "text": "The mapping between two schema may also be defined." }, { "code": null, "e": 26180, "s": 26085, "text": "Example : Let us take some examples to understand how Storage Definition Language (SDL) works." }, { "code": null, "e": 26192, "s": 26180, "text": "Example-1 :" }, { "code": null, "e": 26258, "s": 26192, "text": "CREATE TABLE geeksforgeeks (no_of_articles INT) ENGINE = INNODB;\n" }, { "code": null, "e": 26390, "s": 26258, "text": "In the above example, we specify storage engine to be used by adding ENGINE option. InnoDB is default storage engine for MySQL 8.0." }, { "code": null, "e": 26402, "s": 26390, "text": "Example-2 :" }, { "code": null, "e": 26478, "s": 26402, "text": "CREATE TABLE geeksforgeeks (article_titile varchar(65000) ENGINE = MEMORY;\n" }, { "code": null, "e": 26812, "s": 26478, "text": "This time, engine used is MEMORY. MEMORY storage engine (also known as HEAP) creates tables for particular purpose with contents that are stored in memory. Because the data is vulnerable to power outages, crashes or hardware issues, only use these tables as temporary work areas or read-only caches for data pulled from other tables." }, { "code": null, "e": 26824, "s": 26812, "text": "Example-3 :" }, { "code": null, "e": 26864, "s": 26824, "text": "CREATE TABLE f (x int, y varchar(25));\n" }, { "code": null, "e": 26963, "s": 26864, "text": "In the above statement, Storage Definition Language (SDL) defines storage of row int, varchar(25)." }, { "code": null, "e": 27205, "s": 26963, "text": "Indeed, In most relational database management systems (RDBMS) there is no specific language that performs the role of SDL. Instead, combination of functions, parameters, and specifications related to storage of files define internal schema." }, { "code": null, "e": 27212, "s": 27205, "text": "Picked" }, { "code": null, "e": 27217, "s": 27212, "text": "DBMS" }, { "code": null, "e": 27222, "s": 27217, "text": "DBMS" }, { "code": null, "e": 27320, "s": 27222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27337, "s": 27320, "text": "Deadlock in DBMS" }, { "code": null, "e": 27378, "s": 27337, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 27405, "s": 27378, "text": "KDD Process in Data Mining" }, { "code": null, "e": 27438, "s": 27405, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 27470, "s": 27438, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27497, "s": 27470, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 27540, "s": 27497, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 27577, "s": 27540, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 27627, "s": 27577, "text": "Difference between Where and Having Clause in SQL" } ]
Construct sum-array with sum of elements in given range - GeeksforGeeks
05 Apr, 2021 You are given an array of n-elements and an odd-integer m. You have to construct a new sum_array from given array such that sum_array[i] = Ξ£arr[j] for (i-(m/2)) < j (i+(m/2)). note : for 0 > j or j >= n take arr[j] = 0.Examples: Input : arr[] = {1, 2, 3, 4, 5}, m = 3 Output : sum_array = {3, 6, 9, 12, 9} Explanation : sum_array[0] = arr[0] + arr[1] sum_array[1] = arr[0] + arr[1] + arr[2] sum_array[2] = arr[1] + arr[2] + arr[3] sum_array[3] = arr[2] + arr[3] + arr[4] sum_array[4] = arr[3] + arr[4] Input : arr[] = {2, 4, 3, 4, 2}, m = 1 Output : sum_array = {2, 4, 3, 4, 2} Explanation : sum_array[0] = arr[0] sum_array[1] = arr[1] sum_array[2] = arr[2] sum_array[3] = arr[3] sum_array[4] = arr[4] Basic Approach : As per problem statement, we calculate sum_array[i] by iterating over i-(m/2) to i+(m/2). According to this approach, we have a nested loop which will result into time complexity of O(n*m).Efficient Approach : For calculating sum_array is to use sliding window concept and thus can easily save our time. For Sliding window, the time complexity is O(n). Algorithm calculate sum of first (m/2)+1 elementssum_array[0] = sumfor i=1 to i<nif( (i-(m/2)-1) >= 0 ) sum -= arr[(i-(m/2)-1)]if( (i+m/2) < n) sum += arr[(i+m/2)]sum_array[i] = sumprint sum_array C++ Java Python3 C# PHP Javascript // CPP Program to find sum array for a given// array.#include <bits/stdc++.h>using namespace std; // function to calc sum_array and printvoid calcSum_array(int arr[], int n, int m){ int sum = 0; int sum_array[n]; // calc 1st m/2 + 1 element for 1st window for (int i = 0; i < m / 2 + 1; i++) sum += arr[i]; sum_array[0] = sum; // use sliding window to // calculate rest of sum_array for (int i = 1; i < n; i++) { if (i - (m / 2) - 1 >= 0) sum -= arr[i - (m / 2) - 1]; if (i + (m / 2) < n) sum += arr[i + (m / 2)]; sum_array[i] = sum; } // print sum_array for (int i = 0; i < n; i++) cout << sum_array[i] << " ";} // driver programint main(){ int arr[] = { 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 }; int m = 5; int n = sizeof(arr) / sizeof(int); calcSum_array(arr, n, m); return 0;} // Java Program to find sum array// for a given array.class GFG{ // function to calc sum_array and print static void calcSum_array(int arr[], int n, int m) { int sum = 0; int sum_array[] = new int[n]; // calc 1st m/2 + 1 element // for 1st window for (int i = 0; i < m / 2 + 1; i++) sum += arr[i]; sum_array[0] = sum; // use sliding window to // calculate rest of sum_array for (int i = 1; i < n; i++) { if (i - (m / 2) - 1 >= 0) sum -= arr[i - (m / 2) - 1]; if (i + (m / 2) < n) sum += arr[i + (m / 2)]; sum_array[i] = sum; } // print sum_array for (int i = 0; i < n; i++) System.out.print(sum_array[i] + " "); } // Driver program public static void main(String[] args) { int arr[] = { 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 }; int m = 5; int n = arr.length; calcSum_array(arr, n, m); }} // This code is contributed by prerna saini. # Python3 Program to find Sum array# for a given array.import math as mt # function to calc Sum_array and printdef calcSum_array(arr, n, m): Sum = 0 Sum_array = [0 for i in range(n)] # calc 1st m/2 + 1 element for 1st window for i in range(m // 2 + 1): Sum += arr[i] Sum_array[0] = Sum # use sliding window to # calculate rest of Sum_array for i in range(1, n): if (i - (m // 2) - 1 >= 0): Sum -= arr[i - (m // 2) - 1] if (i + (m / 2) < n): Sum += arr[i + (m //2)] Sum_array[i] = Sum # prSum_array for i in range(n): print(Sum_array[i], end = " ") # Driver Codearr = [ 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 ]m = 5n = len(arr)calcSum_array(arr, n, m) # This code is contributed by mohit kumar 29 // C# Program to find sum array// for a given array.using System; class GFG{ // function to calc sum_array and print static void calcSum_array(int []arr, int n, int m) { int sum = 0; int []sum_array = new int[n]; // calc 1st m/2 + 1 element // for 1st window for (int i = 0; i < m / 2 + 1; i++) sum += arr[i]; sum_array[0] = sum; // use sliding window to // calculate rest of sum_array for (int i = 1; i < n; i++) { if (i - (m / 2) - 1 >= 0) sum -= arr[i - (m / 2) - 1]; if (i + (m / 2) < n) sum += arr[i + (m / 2)]; sum_array[i] = sum; } // print sum_array for (int i = 0; i < n; i++) Console.Write(sum_array[i] + " "); } // Driver program public static void Main() { int []arr = { 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 }; int m = 5; int n = arr.Length; calcSum_array(arr, n, m); }} // This code is contributed by vt_m. <?php// PHP Program to find sum array// for a given array. // function to calc sum_array and printfunction calcSum_array(&$arr, $n, $m){ $sum = 0; $sum_array = array(); // calc 1st m/2 + 1 element // for 1st window for ($i = 0; $i < (int)($m / 2) + 1; $i++) $sum = $sum + $arr[$i]; $sum_array[0] = $sum; // use sliding window to // calculate rest of sum_array for ($i = 1; $i < $n; $i++) { if ($i - (int)($m / 2) - 1 >= 0) $sum = $sum - $arr[$i - (int)($m / 2) - 1]; if ($i + (int)($m / 2) < $n) $sum = $sum + $arr[$i + (int)($m / 2)]; $sum_array[$i] = $sum; } // print sum_array for ($i = 0; $i < $n; $i++) echo $sum_array[$i] . " ";} // Driver Code$arr = array(3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 );$m = 5;$n = sizeof($arr);calcSum_array($arr, $n, $m); // This code is contributed by Mukul Singh?> <script>// JavaScript Program to find sum array for a given// array. // function to calc sum_array and printfunction calcSum_array(arr, n, m){ let sum = 0; let sum_array = new Array(n); // calc 1st m/2 + 1 element for 1st window for (let i = 0; i < Math.floor(m / 2) + 1; i++) sum += arr[i]; sum_array[0] = sum; // use sliding window to // calculate rest of sum_array for (let i = 1; i < n; i++) { if (i - Math.floor(m / 2) - 1 >= 0) sum -= arr[i - Math.floor(m / 2) - 1]; if (i + Math.floor(m / 2) < n) sum += arr[i + Math.floor(m / 2)]; sum_array[i] = sum; } // print sum_array for (let i = 0; i < n; i++) document.write(sum_array[i] + " ");} // Driver program let arr = [ 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 ]; let m = 5; let n = arr.length; calcSum_array(arr, n, m); // This code is contributed by Surbhi Tyagi.</script> Output: 11 18 21 26 24 31 25 27 19 19 10 9 mohit kumar 29 Code_Mech surbhityagi15 sliding-window Arrays sliding-window Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Find subarray with given sum | Set 1 (Nonnegative Numbers) Remove duplicates from sorted array Move all negative numbers to beginning and positive to end with constant extra space Building Heap from Array
[ { "code": null, "e": 26041, "s": 26013, "text": "\n05 Apr, 2021" }, { "code": null, "e": 26272, "s": 26041, "text": "You are given an array of n-elements and an odd-integer m. You have to construct a new sum_array from given array such that sum_array[i] = Ξ£arr[j] for (i-(m/2)) < j (i+(m/2)). note : for 0 > j or j >= n take arr[j] = 0.Examples: " }, { "code": null, "e": 26848, "s": 26272, "text": "Input : arr[] = {1, 2, 3, 4, 5}, \n m = 3\nOutput : sum_array = {3, 6, 9, 12, 9}\nExplanation : sum_array[0] = arr[0] + arr[1]\n sum_array[1] = arr[0] + arr[1] + arr[2]\n sum_array[2] = arr[1] + arr[2] + arr[3]\n sum_array[3] = arr[2] + arr[3] + arr[4]\n sum_array[4] = arr[3] + arr[4]\n\nInput : arr[] = {2, 4, 3, 4, 2}, \n m = 1\nOutput : sum_array = {2, 4, 3, 4, 2}\nExplanation : sum_array[0] = arr[0] \n sum_array[1] = arr[1]\n sum_array[2] = arr[2]\n sum_array[3] = arr[3]\n sum_array[4] = arr[4]" }, { "code": null, "e": 27232, "s": 26850, "text": "Basic Approach : As per problem statement, we calculate sum_array[i] by iterating over i-(m/2) to i+(m/2). According to this approach, we have a nested loop which will result into time complexity of O(n*m).Efficient Approach : For calculating sum_array is to use sliding window concept and thus can easily save our time. For Sliding window, the time complexity is O(n). Algorithm " }, { "code": null, "e": 27441, "s": 27232, "text": "calculate sum of first (m/2)+1 elementssum_array[0] = sumfor i=1 to i<nif( (i-(m/2)-1) >= 0 )\n sum -= arr[(i-(m/2)-1)]if( (i+m/2) < n)\n sum += arr[(i+m/2)]sum_array[i] = sumprint sum_array" }, { "code": null, "e": 27447, "s": 27443, "text": "C++" }, { "code": null, "e": 27452, "s": 27447, "text": "Java" }, { "code": null, "e": 27460, "s": 27452, "text": "Python3" }, { "code": null, "e": 27463, "s": 27460, "text": "C#" }, { "code": null, "e": 27467, "s": 27463, "text": "PHP" }, { "code": null, "e": 27478, "s": 27467, "text": "Javascript" }, { "code": "// CPP Program to find sum array for a given// array.#include <bits/stdc++.h>using namespace std; // function to calc sum_array and printvoid calcSum_array(int arr[], int n, int m){ int sum = 0; int sum_array[n]; // calc 1st m/2 + 1 element for 1st window for (int i = 0; i < m / 2 + 1; i++) sum += arr[i]; sum_array[0] = sum; // use sliding window to // calculate rest of sum_array for (int i = 1; i < n; i++) { if (i - (m / 2) - 1 >= 0) sum -= arr[i - (m / 2) - 1]; if (i + (m / 2) < n) sum += arr[i + (m / 2)]; sum_array[i] = sum; } // print sum_array for (int i = 0; i < n; i++) cout << sum_array[i] << \" \";} // driver programint main(){ int arr[] = { 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 }; int m = 5; int n = sizeof(arr) / sizeof(int); calcSum_array(arr, n, m); return 0;}", "e": 28384, "s": 27478, "text": null }, { "code": "// Java Program to find sum array// for a given array.class GFG{ // function to calc sum_array and print static void calcSum_array(int arr[], int n, int m) { int sum = 0; int sum_array[] = new int[n]; // calc 1st m/2 + 1 element // for 1st window for (int i = 0; i < m / 2 + 1; i++) sum += arr[i]; sum_array[0] = sum; // use sliding window to // calculate rest of sum_array for (int i = 1; i < n; i++) { if (i - (m / 2) - 1 >= 0) sum -= arr[i - (m / 2) - 1]; if (i + (m / 2) < n) sum += arr[i + (m / 2)]; sum_array[i] = sum; } // print sum_array for (int i = 0; i < n; i++) System.out.print(sum_array[i] + \" \"); } // Driver program public static void main(String[] args) { int arr[] = { 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 }; int m = 5; int n = arr.length; calcSum_array(arr, n, m); }} // This code is contributed by prerna saini.", "e": 29462, "s": 28384, "text": null }, { "code": "# Python3 Program to find Sum array# for a given array.import math as mt # function to calc Sum_array and printdef calcSum_array(arr, n, m): Sum = 0 Sum_array = [0 for i in range(n)] # calc 1st m/2 + 1 element for 1st window for i in range(m // 2 + 1): Sum += arr[i] Sum_array[0] = Sum # use sliding window to # calculate rest of Sum_array for i in range(1, n): if (i - (m // 2) - 1 >= 0): Sum -= arr[i - (m // 2) - 1] if (i + (m / 2) < n): Sum += arr[i + (m //2)] Sum_array[i] = Sum # prSum_array for i in range(n): print(Sum_array[i], end = \" \") # Driver Codearr = [ 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 ]m = 5n = len(arr)calcSum_array(arr, n, m) # This code is contributed by mohit kumar 29", "e": 30249, "s": 29462, "text": null }, { "code": "// C# Program to find sum array// for a given array.using System; class GFG{ // function to calc sum_array and print static void calcSum_array(int []arr, int n, int m) { int sum = 0; int []sum_array = new int[n]; // calc 1st m/2 + 1 element // for 1st window for (int i = 0; i < m / 2 + 1; i++) sum += arr[i]; sum_array[0] = sum; // use sliding window to // calculate rest of sum_array for (int i = 1; i < n; i++) { if (i - (m / 2) - 1 >= 0) sum -= arr[i - (m / 2) - 1]; if (i + (m / 2) < n) sum += arr[i + (m / 2)]; sum_array[i] = sum; } // print sum_array for (int i = 0; i < n; i++) Console.Write(sum_array[i] + \" \"); } // Driver program public static void Main() { int []arr = { 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 }; int m = 5; int n = arr.Length; calcSum_array(arr, n, m); }} // This code is contributed by vt_m.", "e": 31311, "s": 30249, "text": null }, { "code": "<?php// PHP Program to find sum array// for a given array. // function to calc sum_array and printfunction calcSum_array(&$arr, $n, $m){ $sum = 0; $sum_array = array(); // calc 1st m/2 + 1 element // for 1st window for ($i = 0; $i < (int)($m / 2) + 1; $i++) $sum = $sum + $arr[$i]; $sum_array[0] = $sum; // use sliding window to // calculate rest of sum_array for ($i = 1; $i < $n; $i++) { if ($i - (int)($m / 2) - 1 >= 0) $sum = $sum - $arr[$i - (int)($m / 2) - 1]; if ($i + (int)($m / 2) < $n) $sum = $sum + $arr[$i + (int)($m / 2)]; $sum_array[$i] = $sum; } // print sum_array for ($i = 0; $i < $n; $i++) echo $sum_array[$i] . \" \";} // Driver Code$arr = array(3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 );$m = 5;$n = sizeof($arr);calcSum_array($arr, $n, $m); // This code is contributed by Mukul Singh?>", "e": 32267, "s": 31311, "text": null }, { "code": "<script>// JavaScript Program to find sum array for a given// array. // function to calc sum_array and printfunction calcSum_array(arr, n, m){ let sum = 0; let sum_array = new Array(n); // calc 1st m/2 + 1 element for 1st window for (let i = 0; i < Math.floor(m / 2) + 1; i++) sum += arr[i]; sum_array[0] = sum; // use sliding window to // calculate rest of sum_array for (let i = 1; i < n; i++) { if (i - Math.floor(m / 2) - 1 >= 0) sum -= arr[i - Math.floor(m / 2) - 1]; if (i + Math.floor(m / 2) < n) sum += arr[i + Math.floor(m / 2)]; sum_array[i] = sum; } // print sum_array for (let i = 0; i < n; i++) document.write(sum_array[i] + \" \");} // Driver program let arr = [ 3, 6, 2, 7, 3, 8, 4, 9, 1, 5, 0, 4 ]; let m = 5; let n = arr.length; calcSum_array(arr, n, m); // This code is contributed by Surbhi Tyagi.</script>", "e": 33219, "s": 32267, "text": null }, { "code": null, "e": 33229, "s": 33219, "text": "Output: " }, { "code": null, "e": 33265, "s": 33229, "text": "11 18 21 26 24 31 25 27 19 19 10 9 " }, { "code": null, "e": 33282, "s": 33267, "text": "mohit kumar 29" }, { "code": null, "e": 33292, "s": 33282, "text": "Code_Mech" }, { "code": null, "e": 33306, "s": 33292, "text": "surbhityagi15" }, { "code": null, "e": 33321, "s": 33306, "text": "sliding-window" }, { "code": null, "e": 33328, "s": 33321, "text": "Arrays" }, { "code": null, "e": 33343, "s": 33328, "text": "sliding-window" }, { "code": null, "e": 33350, "s": 33343, "text": "Arrays" }, { "code": null, "e": 33448, "s": 33350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33475, "s": 33448, "text": "Count pairs with given sum" }, { "code": null, "e": 33506, "s": 33475, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 33531, "s": 33506, "text": "Window Sliding Technique" }, { "code": null, "e": 33569, "s": 33531, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33590, "s": 33569, "text": "Next Greater Element" }, { "code": null, "e": 33648, "s": 33590, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 33707, "s": 33648, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 33743, "s": 33707, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 33828, "s": 33743, "text": "Move all negative numbers to beginning and positive to end with constant extra space" } ]
Applied Multivariate Regression. A look into the practical applications... | by Ashwin Raj | Towards Data Science
In this article we will be getting introduced to the concepts of Multivariate regression. We will also be discussing about a common problem associated with the algorithm i.e. The Dummy Variable Trap. First we will be getting familiar with the concepts of Multivariate regression and then we will build our very own multivariate regression model. However before getting started I would recommend you to take a look at my article on Simple Linear Regression for understanding the concepts even better . Multivariate regression is an extension of simple linear regression. It is used when we want to predict the value of a variable based on the value of two or more different variables. The variable we want to predict is called the Dependent Variable, while those used to calculate the dependent variable are termed as Independent Variables. The mathematical function/hypothesis of a Multivariate regression is of the form: where, n represents the number of independent variables, Ξ²0~ Ξ²n represent the coefficients and x1~xn, are the independent variable Using a multivariate model helps us compare coefficients across outcomes. What makes a multivariate or multiple linear regression a better model is a small cost function. In simple words it is a function that assigns a cost to instances where the model deviates from the observed data. In this case, our cost is the sum of squared errors. The cost function for multiple linear regression is given by: We can understand this equation as the summation of square of difference between our predicted value and the actual value divided by twice of length of data set. A smaller mean squared error implies a better performance. Generally a cost function is used along with the Gradient Descent algorithm to find the best parameters. Now we will be practically applying what we have learned by building a multivariate linear regression. You can access the complete code and other resources for this regression model on my GitHub handle. In this example we will be predicting the value of a house, given the features like median income, average house age, number of rooms, households, average area, number of bedrooms and area population. Our first step is to import the libraries required to build our model. It is not necessary to import all the libraries at just one place. Python allows us to import any library at any place. To get started we will be importing Pandas, Numpy, Matplotlib and Seaborn libraries. #Importing the libraries and and reading the data into a Pandas DataFrameimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snstest=pd.read_csv("california_housing_test.csv")train=pd.read_csv("california_housing_train.csv") Once these libraries have been imported our next step will be fetching the dataset and loading the data into our notebook. For this example I have taken the California Housing dataset. After successfully loading the data, our next step is to visualize this data. Matplotlib and Seashore are excellent libraries that can be used to visualize our data on various different plots. #Visuaising our data using Seaborn Libraryplt.figure()sns.heatmap(data.corr(), cmap='coolwarm')plt.show()sns.lmplot(x='median_income', y='median_house_value', data=train)sns.lmplot(x='housing_median_age', y='median_house_value', data=train) Feature engineering is the process of using domain knowledge to extract features from raw data via data mining techniques. I have selected only few columns to work with continuous numerical values only for this model. data = data[[β€˜total_rooms’, β€˜total_bedrooms’, β€˜housing_median_age’, β€˜median_income’, β€˜population’, β€˜households’]]data.info()data['total_rooms'] = data['total_rooms'].fillna(data['total_rooms'].mean())data['total_bedrooms'] = data['total_bedrooms'].fillna(data['total_bedrooms'].mean()) Feature Engineering becomes even more important when the number of features are very large. One of the most important use of feature engineering is that it reduces overfitting and improves the accuracy of a model. After selecting the desired parameters the next step is to import train_test_split from sklearn library which is used to split the dataset into training and testing data. #Splitting training and testing datafrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(train, y, test_size = 0.2, random_state = 0)y_train = y_train.reshape(-1,1)y_test = y_test.reshape(-1,1) After this LinearRegression is imported from sklearn.model_selection and the model is fit over the training dataset. The intercept and coefficient of our model can be calculated as shown below: #Fitting the model on training datafrom sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(X_train, y_train)#Calculating the Intercept and Coefficientprint(regressor.intercept_)print(regressor.coef_) The performance of the model can be evaluated by finding the root mean squared error of the model. predictions = regressor.predict(X_test)predictions = predictions.reshape(-1,1)#Calculate RMSE of the modelfrom sklearn.metrics import mean_squared_errorprint(β€˜MSE:’, mean_squared_error(y_test,predictions))print(β€˜RMSE:’, np.sqrt(mean_squared_error(y_test,predictions))) The RMSE for our model is 0.6628934048044981. The plot for the calculated values against predicted values is as shown below: When working with multivariate models, it is easy to handle quantitative or numerical data. However, this is not the same for categorical data. They can’t be used directly and needs to be transformed. Dummy variables are β€œproxy” variables used in place for categorical data that are sometimes present in the datasets that we use for building regression models. Using all dummy variables for regression models lead to dummy variable trap. The Dummy Variable trap is a scenario in which the independent variables are multicollinear i.e. two or more variables are highly correlated. In order to avoid such a scenario it is recommended to design the regression model such that it excludes one of the dummy variables. Let’s consider the case of gender which can have either of the two values male (0) or female (1). After using label encoding procedures to transform these categorical features to numerical attributes, if we include both the dummy variables then it causes redundancy, leading to Dummy Variable trap. Such a problem can be avoided, if we don’t use both the variables in regression models, as if a person is not male then it is expected that the person is a female. This way the dummy variable trap can be avoided Here are some resources that you can use to get an even deeper understanding of the concepts of multivariate regression. GeeksforgeeksMultiple Linear Regression-Beginner’s GuideWriting Multivariate Linear Regression from Scratch Geeksforgeeks Multiple Linear Regression-Beginner’s Guide Writing Multivariate Linear Regression from Scratch Now that we have reached the end of this article, I hope you would have found this article really informative. I hope you found it informative! If you have any question or if i have made any mistake, please contact me! You can get in touch with me via: Email or LinkedIn
[ { "code": null, "e": 372, "s": 172, "text": "In this article we will be getting introduced to the concepts of Multivariate regression. We will also be discussing about a common problem associated with the algorithm i.e. The Dummy Variable Trap." }, { "code": null, "e": 673, "s": 372, "text": "First we will be getting familiar with the concepts of Multivariate regression and then we will build our very own multivariate regression model. However before getting started I would recommend you to take a look at my article on Simple Linear Regression for understanding the concepts even better ." }, { "code": null, "e": 1012, "s": 673, "text": "Multivariate regression is an extension of simple linear regression. It is used when we want to predict the value of a variable based on the value of two or more different variables. The variable we want to predict is called the Dependent Variable, while those used to calculate the dependent variable are termed as Independent Variables." }, { "code": null, "e": 1094, "s": 1012, "text": "The mathematical function/hypothesis of a Multivariate regression is of the form:" }, { "code": null, "e": 1225, "s": 1094, "text": "where, n represents the number of independent variables, Ξ²0~ Ξ²n represent the coefficients and x1~xn, are the independent variable" }, { "code": null, "e": 1396, "s": 1225, "text": "Using a multivariate model helps us compare coefficients across outcomes. What makes a multivariate or multiple linear regression a better model is a small cost function." }, { "code": null, "e": 1626, "s": 1396, "text": "In simple words it is a function that assigns a cost to instances where the model deviates from the observed data. In this case, our cost is the sum of squared errors. The cost function for multiple linear regression is given by:" }, { "code": null, "e": 1952, "s": 1626, "text": "We can understand this equation as the summation of square of difference between our predicted value and the actual value divided by twice of length of data set. A smaller mean squared error implies a better performance. Generally a cost function is used along with the Gradient Descent algorithm to find the best parameters." }, { "code": null, "e": 2055, "s": 1952, "text": "Now we will be practically applying what we have learned by building a multivariate linear regression." }, { "code": null, "e": 2155, "s": 2055, "text": "You can access the complete code and other resources for this regression model on my GitHub handle." }, { "code": null, "e": 2356, "s": 2155, "text": "In this example we will be predicting the value of a house, given the features like median income, average house age, number of rooms, households, average area, number of bedrooms and area population." }, { "code": null, "e": 2632, "s": 2356, "text": "Our first step is to import the libraries required to build our model. It is not necessary to import all the libraries at just one place. Python allows us to import any library at any place. To get started we will be importing Pandas, Numpy, Matplotlib and Seaborn libraries." }, { "code": null, "e": 2891, "s": 2632, "text": "#Importing the libraries and and reading the data into a Pandas DataFrameimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snstest=pd.read_csv(\"california_housing_test.csv\")train=pd.read_csv(\"california_housing_train.csv\")" }, { "code": null, "e": 3076, "s": 2891, "text": "Once these libraries have been imported our next step will be fetching the dataset and loading the data into our notebook. For this example I have taken the California Housing dataset." }, { "code": null, "e": 3269, "s": 3076, "text": "After successfully loading the data, our next step is to visualize this data. Matplotlib and Seashore are excellent libraries that can be used to visualize our data on various different plots." }, { "code": null, "e": 3510, "s": 3269, "text": "#Visuaising our data using Seaborn Libraryplt.figure()sns.heatmap(data.corr(), cmap='coolwarm')plt.show()sns.lmplot(x='median_income', y='median_house_value', data=train)sns.lmplot(x='housing_median_age', y='median_house_value', data=train)" }, { "code": null, "e": 3728, "s": 3510, "text": "Feature engineering is the process of using domain knowledge to extract features from raw data via data mining techniques. I have selected only few columns to work with continuous numerical values only for this model." }, { "code": null, "e": 4014, "s": 3728, "text": "data = data[[β€˜total_rooms’, β€˜total_bedrooms’, β€˜housing_median_age’, β€˜median_income’, β€˜population’, β€˜households’]]data.info()data['total_rooms'] = data['total_rooms'].fillna(data['total_rooms'].mean())data['total_bedrooms'] = data['total_bedrooms'].fillna(data['total_bedrooms'].mean())" }, { "code": null, "e": 4228, "s": 4014, "text": "Feature Engineering becomes even more important when the number of features are very large. One of the most important use of feature engineering is that it reduces overfitting and improves the accuracy of a model." }, { "code": null, "e": 4399, "s": 4228, "text": "After selecting the desired parameters the next step is to import train_test_split from sklearn library which is used to split the dataset into training and testing data." }, { "code": null, "e": 4644, "s": 4399, "text": "#Splitting training and testing datafrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(train, y, test_size = 0.2, random_state = 0)y_train = y_train.reshape(-1,1)y_test = y_test.reshape(-1,1)" }, { "code": null, "e": 4838, "s": 4644, "text": "After this LinearRegression is imported from sklearn.model_selection and the model is fit over the training dataset. The intercept and coefficient of our model can be calculated as shown below:" }, { "code": null, "e": 5075, "s": 4838, "text": "#Fitting the model on training datafrom sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(X_train, y_train)#Calculating the Intercept and Coefficientprint(regressor.intercept_)print(regressor.coef_)" }, { "code": null, "e": 5174, "s": 5075, "text": "The performance of the model can be evaluated by finding the root mean squared error of the model." }, { "code": null, "e": 5443, "s": 5174, "text": "predictions = regressor.predict(X_test)predictions = predictions.reshape(-1,1)#Calculate RMSE of the modelfrom sklearn.metrics import mean_squared_errorprint(β€˜MSE:’, mean_squared_error(y_test,predictions))print(β€˜RMSE:’, np.sqrt(mean_squared_error(y_test,predictions)))" }, { "code": null, "e": 5568, "s": 5443, "text": "The RMSE for our model is 0.6628934048044981. The plot for the calculated values against predicted values is as shown below:" }, { "code": null, "e": 5769, "s": 5568, "text": "When working with multivariate models, it is easy to handle quantitative or numerical data. However, this is not the same for categorical data. They can’t be used directly and needs to be transformed." }, { "code": null, "e": 6006, "s": 5769, "text": "Dummy variables are β€œproxy” variables used in place for categorical data that are sometimes present in the datasets that we use for building regression models. Using all dummy variables for regression models lead to dummy variable trap." }, { "code": null, "e": 6281, "s": 6006, "text": "The Dummy Variable trap is a scenario in which the independent variables are multicollinear i.e. two or more variables are highly correlated. In order to avoid such a scenario it is recommended to design the regression model such that it excludes one of the dummy variables." }, { "code": null, "e": 6580, "s": 6281, "text": "Let’s consider the case of gender which can have either of the two values male (0) or female (1). After using label encoding procedures to transform these categorical features to numerical attributes, if we include both the dummy variables then it causes redundancy, leading to Dummy Variable trap." }, { "code": null, "e": 6792, "s": 6580, "text": "Such a problem can be avoided, if we don’t use both the variables in regression models, as if a person is not male then it is expected that the person is a female. This way the dummy variable trap can be avoided" }, { "code": null, "e": 6913, "s": 6792, "text": "Here are some resources that you can use to get an even deeper understanding of the concepts of multivariate regression." }, { "code": null, "e": 7021, "s": 6913, "text": "GeeksforgeeksMultiple Linear Regression-Beginner’s GuideWriting Multivariate Linear Regression from Scratch" }, { "code": null, "e": 7035, "s": 7021, "text": "Geeksforgeeks" }, { "code": null, "e": 7079, "s": 7035, "text": "Multiple Linear Regression-Beginner’s Guide" }, { "code": null, "e": 7131, "s": 7079, "text": "Writing Multivariate Linear Regression from Scratch" } ]
Codes Conversion
There are many methods or techniques which can be used to convert code from one format to another. We'll demonstrate here the following Binary to BCD Conversion BCD to Binary Conversion BCD to Excess-3 Excess-3 to BCD Steps Step 1 -- Convert the binary number to decimal. Step 1 -- Convert the binary number to decimal. Step 2 -- Convert decimal number to BCD. Step 2 -- Convert decimal number to BCD. Example βˆ’ convert (11101)2 to BCD. Binary Number βˆ’ 111012 Calculating Decimal Equivalent βˆ’ Binary Number βˆ’ 111012 = Decimal Number βˆ’ 2910 Decimal Number βˆ’ 2910 Calculating BCD Equivalent. Convert each digit into groups of four binary digits equivalent. Result (11101)2 = (00101001)BCD Steps Step 1 -- Convert the BCD number to decimal. Step 1 -- Convert the BCD number to decimal. Step 2 -- Convert decimal to binary. Step 2 -- Convert decimal to binary. Example βˆ’ convert (00101001)BCD to Binary. BCD Number βˆ’ (00101001)BCD Calculating Decimal Equivalent. Convert each four digit into a group and get decimal equivalent for each group. BCD Number βˆ’ (00101001)BCD = Decimal Number βˆ’ 2910 Used long division method for decimal to binary conversion. Decimal Number βˆ’ 2910 Calculating Binary Equivalent βˆ’ As mentioned in Steps 2 and 4, the remainders have to be arranged in the reverse order so that the first remainder becomes the least significant digit (LSD) and the last remainder becomes the most significant digit (MSD). Decimal Number βˆ’ 2910 = Binary Number βˆ’ 111012 Result (00101001)BCD = (11101)2 Steps Step 1 -- Convert BCD to decimal. Step 1 -- Convert BCD to decimal. Step 2 -- Add (3)10 to this decimal number. Step 2 -- Add (3)10 to this decimal number. Step 3 -- Convert into binary to get excess-3 code. Step 3 -- Convert into binary to get excess-3 code. Example βˆ’ convert (0110)BCD to Excess-3. (0110)BCD = 610 (6)10 + (3)10 = (9)10 (9)10 = (1001)2 Result (0110)BCD = (1001)XS-3 Steps Step 1 -- Subtract (0011)2 from each 4 bit of excess-3 digit to obtain the corresponding BCD code. Step 1 -- Subtract (0011)2 from each 4 bit of excess-3 digit to obtain the corresponding BCD code. Example βˆ’ convert (10011010)XS-3 to BCD. Given XS-3 number = 1 0 0 1 1 0 1 0 Subtract (0011)2 = 1 0 0 1 0 1 1 1 -------------------- BCD = 0 1 1 0 0 1 1 1 Result (10011010)XS-3 = (01100111)BCD 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2107, "s": 1971, "text": "There are many methods or techniques which can be used to convert code from one format to another. We'll demonstrate here the following" }, { "code": null, "e": 2132, "s": 2107, "text": "Binary to BCD Conversion" }, { "code": null, "e": 2157, "s": 2132, "text": "BCD to Binary Conversion" }, { "code": null, "e": 2173, "s": 2157, "text": "BCD to Excess-3" }, { "code": null, "e": 2189, "s": 2173, "text": "Excess-3 to BCD" }, { "code": null, "e": 2195, "s": 2189, "text": "Steps" }, { "code": null, "e": 2243, "s": 2195, "text": "Step 1 -- Convert the binary number to decimal." }, { "code": null, "e": 2291, "s": 2243, "text": "Step 1 -- Convert the binary number to decimal." }, { "code": null, "e": 2332, "s": 2291, "text": "Step 2 -- Convert decimal number to BCD." }, { "code": null, "e": 2373, "s": 2332, "text": "Step 2 -- Convert decimal number to BCD." }, { "code": null, "e": 2408, "s": 2373, "text": "Example βˆ’ convert (11101)2 to BCD." }, { "code": null, "e": 2431, "s": 2408, "text": "Binary Number βˆ’ 111012" }, { "code": null, "e": 2464, "s": 2431, "text": "Calculating Decimal Equivalent βˆ’" }, { "code": null, "e": 2511, "s": 2464, "text": "Binary Number βˆ’ 111012 = Decimal Number βˆ’ 2910" }, { "code": null, "e": 2533, "s": 2511, "text": "Decimal Number βˆ’ 2910" }, { "code": null, "e": 2626, "s": 2533, "text": "Calculating BCD Equivalent. Convert each digit into groups of four binary digits equivalent." }, { "code": null, "e": 2633, "s": 2626, "text": "Result" }, { "code": null, "e": 2660, "s": 2633, "text": "(11101)2 = (00101001)BCD\n" }, { "code": null, "e": 2666, "s": 2660, "text": "Steps" }, { "code": null, "e": 2711, "s": 2666, "text": "Step 1 -- Convert the BCD number to decimal." }, { "code": null, "e": 2756, "s": 2711, "text": "Step 1 -- Convert the BCD number to decimal." }, { "code": null, "e": 2793, "s": 2756, "text": "Step 2 -- Convert decimal to binary." }, { "code": null, "e": 2830, "s": 2793, "text": "Step 2 -- Convert decimal to binary." }, { "code": null, "e": 2873, "s": 2830, "text": "Example βˆ’ convert (00101001)BCD to Binary." }, { "code": null, "e": 2900, "s": 2873, "text": "BCD Number βˆ’ (00101001)BCD" }, { "code": null, "e": 3012, "s": 2900, "text": "Calculating Decimal Equivalent. Convert each four digit into a group and get decimal equivalent for each group." }, { "code": null, "e": 3063, "s": 3012, "text": "BCD Number βˆ’ (00101001)BCD = Decimal Number βˆ’ 2910" }, { "code": null, "e": 3123, "s": 3063, "text": "Used long division method for decimal to binary conversion." }, { "code": null, "e": 3145, "s": 3123, "text": "Decimal Number βˆ’ 2910" }, { "code": null, "e": 3177, "s": 3145, "text": "Calculating Binary Equivalent βˆ’" }, { "code": null, "e": 3399, "s": 3177, "text": "As mentioned in Steps 2 and 4, the remainders have to be arranged in the reverse order so that the first remainder becomes the least significant digit (LSD) and the last remainder becomes the most significant digit (MSD)." }, { "code": null, "e": 3446, "s": 3399, "text": "Decimal Number βˆ’ 2910 = Binary Number βˆ’ 111012" }, { "code": null, "e": 3453, "s": 3446, "text": "Result" }, { "code": null, "e": 3479, "s": 3453, "text": "(00101001)BCD = (11101)2\n" }, { "code": null, "e": 3485, "s": 3479, "text": "Steps" }, { "code": null, "e": 3519, "s": 3485, "text": "Step 1 -- Convert BCD to decimal." }, { "code": null, "e": 3553, "s": 3519, "text": "Step 1 -- Convert BCD to decimal." }, { "code": null, "e": 3597, "s": 3553, "text": "Step 2 -- Add (3)10 to this decimal number." }, { "code": null, "e": 3641, "s": 3597, "text": "Step 2 -- Add (3)10 to this decimal number." }, { "code": null, "e": 3693, "s": 3641, "text": "Step 3 -- Convert into binary to get excess-3 code." }, { "code": null, "e": 3745, "s": 3693, "text": "Step 3 -- Convert into binary to get excess-3 code." }, { "code": null, "e": 3786, "s": 3745, "text": "Example βˆ’ convert (0110)BCD to Excess-3." }, { "code": null, "e": 3802, "s": 3786, "text": "(0110)BCD = 610" }, { "code": null, "e": 3824, "s": 3802, "text": "(6)10 + (3)10 = (9)10" }, { "code": null, "e": 3840, "s": 3824, "text": "(9)10 = (1001)2" }, { "code": null, "e": 3847, "s": 3840, "text": "Result" }, { "code": null, "e": 3871, "s": 3847, "text": "(0110)BCD = (1001)XS-3\n" }, { "code": null, "e": 3877, "s": 3871, "text": "Steps" }, { "code": null, "e": 3976, "s": 3877, "text": "Step 1 -- Subtract (0011)2 from each 4 bit of excess-3 digit to obtain the corresponding BCD code." }, { "code": null, "e": 4075, "s": 3976, "text": "Step 1 -- Subtract (0011)2 from each 4 bit of excess-3 digit to obtain the corresponding BCD code." }, { "code": null, "e": 4116, "s": 4075, "text": "Example βˆ’ convert (10011010)XS-3 to BCD." }, { "code": null, "e": 4272, "s": 4116, "text": "Given XS-3 number = 1 0 0 1 1 0 1 0 \nSubtract (0011)2 = 1 0 0 1 0 1 1 1\n --------------------\n BCD = 0 1 1 0 0 1 1 1\n" }, { "code": null, "e": 4279, "s": 4272, "text": "Result" }, { "code": null, "e": 4311, "s": 4279, "text": "(10011010)XS-3 = (01100111)BCD\n" }, { "code": null, "e": 4348, "s": 4311, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 4367, "s": 4348, "text": " Arnab Chakraborty" }, { "code": null, "e": 4401, "s": 4367, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 4420, "s": 4401, "text": " Arnab Chakraborty" }, { "code": null, "e": 4453, "s": 4420, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 4472, "s": 4453, "text": " Arnab Chakraborty" }, { "code": null, "e": 4507, "s": 4472, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4515, "s": 4507, "text": " Shweta" }, { "code": null, "e": 4548, "s": 4515, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 4565, "s": 4548, "text": " Abhilash Nelson" }, { "code": null, "e": 4598, "s": 4565, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 4620, "s": 4598, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4627, "s": 4620, "text": " Print" }, { "code": null, "e": 4638, "s": 4627, "text": " Add Notes" } ]
C# - Constants and Literals
The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. The constants are treated just like regular variables except that their values cannot be modified after their definition. An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals βˆ’ 212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */ Following are other examples of various types of Integer literals βˆ’ 85 /* decimal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */ A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. Here are some examples of floating-point literals βˆ’ 3.14159 /* Legal */ 314159E-5F /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */ While representing in decimal form, you must include the decimal point, the exponent, or both; and while representing using exponential form you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Character literals are enclosed in single quotes. For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (such as 'x'), an escape sequence (such as '\t'), or a universal character (such as '\u02C0'). There are certain characters in C# when they are preceded by a backslash. They have special meaning and they are used to represent like newline (\n) or tab (\t). Here, is a list of some of such escape sequence codes βˆ’ Following is the example to show few escape sequence characters βˆ’ using System; namespace EscapeChar { class Program { static void Main(string[] args) { Console.WriteLine("Hello\tWorld\n\n"); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result βˆ’ Hello World String literals or constants are enclosed in double quotes "" or with @"". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating the parts using whitespaces. Here are some examples of string literals. All the three forms are identical strings. "hello, dear" "hello, \ dear" "hello, " "d" "ear" @"hello dear" Constants are defined using the const keyword. Syntax for defining a constant is βˆ’ const <data_type> <constant_name> = value; The following program demonstrates defining and using a constant in your program βˆ’ using System; namespace DeclaringConstants { class Program { static void Main(string[] args) { const double pi = 3.14159; // constant declaration double r; Console.WriteLine("Enter Radius: "); r = Convert.ToDouble(Console.ReadLine()); double areaCircle = pi * r * r; Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result βˆ’ Enter Radius: 3 Radius: 3, Area: 28.27431 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2588, "s": 2270, "text": "The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well." }, { "code": null, "e": 2710, "s": 2588, "text": "The constants are treated just like regular variables except that their values cannot be modified after their definition." }, { "code": null, "e": 2875, "s": 2710, "text": "An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal." }, { "code": null, "e": 3054, "s": 2875, "text": "An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order." }, { "code": null, "e": 3099, "s": 3054, "text": "Here are some examples of integer literals βˆ’" }, { "code": null, "e": 3171, "s": 3099, "text": "212 /* Legal */\n215u /* Legal */\n0xFeeL /* Legal */" }, { "code": null, "e": 3239, "s": 3171, "text": "Following are other examples of various types of Integer literals βˆ’" }, { "code": null, "e": 3397, "s": 3239, "text": "85 /* decimal */\n0x4b /* hexadecimal */\n30 /* int */\n30u /* unsigned int */\n30l /* long */\n30ul /* unsigned long */" }, { "code": null, "e": 3587, "s": 3397, "text": "A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form." }, { "code": null, "e": 3639, "s": 3587, "text": "Here are some examples of floating-point literals βˆ’" }, { "code": null, "e": 3849, "s": 3639, "text": "3.14159 /* Legal */\n314159E-5F /* Legal */\n510E /* Illegal: incomplete exponent */\n210f /* Illegal: no decimal or exponent */\n.e55 /* Illegal: missing integer or fraction */" }, { "code": null, "e": 4100, "s": 3849, "text": "While representing in decimal form, you must include the decimal point, the exponent, or both; and while representing using exponential form you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E." }, { "code": null, "e": 4360, "s": 4100, "text": "Character literals are enclosed in single quotes. For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (such as 'x'), an escape sequence (such as '\\t'), or a universal character (such as '\\u02C0')." }, { "code": null, "e": 4578, "s": 4360, "text": "There are certain characters in C# when they are preceded by a backslash. They have special meaning and they are used to represent like newline (\\n) or tab (\\t). Here, is a list of some of such escape sequence codes βˆ’" }, { "code": null, "e": 4644, "s": 4578, "text": "Following is the example to show few escape sequence characters βˆ’" }, { "code": null, "e": 4833, "s": 4644, "text": "using System;\n\nnamespace EscapeChar {\n class Program {\n static void Main(string[] args) {\n Console.WriteLine(\"Hello\\tWorld\\n\\n\");\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 4914, "s": 4833, "text": "When the above code is compiled and executed, it produces the following result βˆ’" }, { "code": null, "e": 4929, "s": 4914, "text": "Hello World\n" }, { "code": null, "e": 5135, "s": 4929, "text": "String literals or constants are enclosed in double quotes \"\" or with @\"\". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters." }, { "code": null, "e": 5247, "s": 5135, "text": "You can break a long line into multiple lines using string literals and separating the parts using whitespaces." }, { "code": null, "e": 5333, "s": 5247, "text": "Here are some examples of string literals. All the three forms are identical strings." }, { "code": null, "e": 5397, "s": 5333, "text": "\"hello, dear\"\n\"hello, \\\ndear\"\n\"hello, \" \"d\" \"ear\"\n@\"hello dear\"" }, { "code": null, "e": 5480, "s": 5397, "text": "Constants are defined using the const keyword. Syntax for defining a constant is βˆ’" }, { "code": null, "e": 5524, "s": 5480, "text": "const <data_type> <constant_name> = value;\n" }, { "code": null, "e": 5607, "s": 5524, "text": "The following program demonstrates defining and using a constant in your program βˆ’" }, { "code": null, "e": 6081, "s": 5607, "text": "using System;\n\nnamespace DeclaringConstants {\n class Program {\n static void Main(string[] args) {\n const double pi = 3.14159; \n \n // constant declaration \n double r;\n Console.WriteLine(\"Enter Radius: \");\n r = Convert.ToDouble(Console.ReadLine());\n \n double areaCircle = pi * r * r;\n Console.WriteLine(\"Radius: {0}, Area: {1}\", r, areaCircle);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 6162, "s": 6081, "text": "When the above code is compiled and executed, it produces the following result βˆ’" }, { "code": null, "e": 6206, "s": 6162, "text": "Enter Radius: \n3\nRadius: 3, Area: 28.27431\n" }, { "code": null, "e": 6243, "s": 6206, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 6256, "s": 6243, "text": " Raja Biswas" }, { "code": null, "e": 6290, "s": 6256, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 6308, "s": 6290, "text": " Trevoir Williams" }, { "code": null, "e": 6341, "s": 6308, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 6355, "s": 6341, "text": " Peter Jepson" }, { "code": null, "e": 6392, "s": 6355, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 6407, "s": 6392, "text": " Ebenezer Ogbu" }, { "code": null, "e": 6442, "s": 6407, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 6457, "s": 6442, "text": " Arnold Higuit" }, { "code": null, "e": 6492, "s": 6457, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6504, "s": 6492, "text": " Eric Frick" }, { "code": null, "e": 6511, "s": 6504, "text": " Print" }, { "code": null, "e": 6522, "s": 6511, "text": " Add Notes" } ]
How to match any one uppercase character in python using Regular Expression?
The following code matches and prints any uppercase character in the given string using python regular expression as follows. import re foo = 'MozamBiQuE' match = re.findall(r'[A-Z]', foo) print match This gives the output ['M', 'B', 'Q', 'E']
[ { "code": null, "e": 1188, "s": 1062, "text": "The following code matches and prints any uppercase character in the given string using python regular expression as follows." }, { "code": null, "e": 1263, "s": 1188, "text": "import re\nfoo = 'MozamBiQuE'\nmatch = re.findall(r'[A-Z]', foo)\nprint match" }, { "code": null, "e": 1285, "s": 1263, "text": "This gives the output" }, { "code": null, "e": 1308, "s": 1285, "text": "['M', 'B', 'Q', 'E']\n\n" } ]
The Quick and Easy Way to Plot Error Bars in Python Using Pandas | by Max Hilsdorf | Towards Data Science
In scientific studies, displaying error bars in your descriptive visualizations is inevitable. Holding information about the variability of your data, they are a necessary complement to your mean scores. However, scientific visualizations tend to be more beautiful on the inside than on the outside. As data scientists, we are taught to use attractive visualizations to tell stories. Anything that distracts the viewer from the main point we are trying to make is adviced to be removed. This makes perfect sense, as managers and customers usually neither have a good grasp of statistics nor much time and energy to spend on your visualizations. To interpret error bars, you need: a basic understanding of descriptive statistics information on what kind of error bar is displayed (typically standard deviation or standard error) Both of those presuppositions conflict with the aim of a data storyteller. You want anyone to understand the results without having to read through eight lines of notes. Data storytellers see error bars as obstacles, because they prevent easy, comfortable, and uniform interpretation of their data. Scientists, on the other hand, are trained to display all necessary information and let the reader interpret the results on their own. Neither of these approaches is superior. Oversimplifying results in technical reports or data team meetings is just as disadvantagious as annoying your managers and customers with spontaneous lectures in statistics. For anyone willing to justify the β€œscience” in their data science job title, learning when and how to use error bars is inevitable! When I created the visualizations for my first scientific article, I tried lots of different methods. Let me save you some time and introduce you to the quick and easy method I found. All you need to follow this article and apply the method yourself is some basic knowledge of statistics, python and the pandas library. There are two main parameters that are suited for error bars. (2x) Standard DeviationStandard Error (2x) Standard Deviation Standard Error I highly recommend getting familiar with these parameters, so that you can make educated decisions on which parameter to use for your visualizations. In this article by Claudia Clement, the concepts are explained in a perfectly compressed way. First, we need to import our libraries and load our data. We’ll be using the avocado price dataset from kaggle. You don’t need to know much about the dataset. All we want to know is whether conventional and organic avocados (β€œtype” column) have different prices ( β€œAveragePrice” column). # Importsimport pandas as pdimport numpy as np # for calculating standard deviation and meanimport scipy.stats as sp # for calculating standard errorimport matplotlib.pyplot as plt # for improving our visualizations# Read dataavocado = pd.read_csv("avocado.csv") The easiest way to perform our calculations is by using pandas df.groupby function. This function has many useful applications, but in this case, weβ€˜ll use it for aggregated computations of statistical parameters. Below, you can see the code prototype. df.groupby("col_to_group_by").agg([func_1, func_2, func_3]) We use df.groupby.agg for a quick and easy way to compute statistical parameters for group comparisons. We have the dataframe and column to group by, so we need to find the right functions now. Remember, we want the mean, the standard deviation x 2, and the standard error. These are the functions we need: NumPy Mean: np.mean Standard Deviation: np.std SciPy Standard Error: scipy.stats.sem Because the df.groupby.agg function only takes a list of functions as an input, we can’t just use np.std * 2 to get our doubled standard deviation. However, we can just write our own function. def double_std(array): return np.std(array) * 2 Now, let’s use the prototype code and fill the placeholders. # df.groupby("col_to_group_by").agg([func_1, func_2, func_3])avocado_prices = avocado.groupby("type").agg([np.mean, double_std, sp.sem]) Nice! Now, let’s select only the β€œAveragePrice” column, because we don’t need the rest. avocado_prices = avocado_prices["AveragePrice"] avocado_prices.head() now gives us the following output: Great! Now we have all the data we need. Pandas has a really useful function that allows us get a first visualization quickly without going through the whole matplotlib procedure: df.plot It’s basically a matplotlib representation within pandas. To get a first plot without any error bars, we just need one line of code: avocado_prices.plot(kind = "barh", y = "mean", legend = False, title = "Average Avocado Prices") Output: We can see that organic avocados have a higher mean price than conventional avocados. But is this a real difference or just random spread? As I promised in the subtitle, we don’t need a single extra line of code to answer this question using error bars. All we need to do is assign our statistical parameter to the xerr argument. Let’s start with the β€œdouble_std” parameter: avocado_prices.plot(kind = "barh", y = "mean", legend = False, title = "Average Avocado Prices", xerr = "double_std") Output: There they are! Even without any deep knowledge of how to interpret these error bars, we can see that the variability in prices is rather high and that the error bars of each bar touch the other bar. Maybe the difference isn’t as clear and large as we expected from seeing just the first plot? Again, I won’t go in depth on the interpretation of standard deviation and standard error since this is a practical guide. Just note that this plot leaves us with a different impression than the previous one. What happens if we plot the standard error next? avocado_prices.plot(kind = "barh", y = "mean", legend = False, title = "Average Avocado Prices", xerr = "sem") Output: What? The error bars are hardly visible. Standard error is sensitive to sample size, as it is lower in large samples than in small samples. The avocado sample has more than 250k observations, so the results make sense. This third plot leaves as with a completely different impression again! Whether and how you use error bars makes a huge difference in the β€œstory” your visualization tells. It is crucial to understand the statistics behind error bars to use and interpret them correctly. So far, we got very good results from just one line of code. If we take some more time to improve our visualization, we can get something like Figure 4. ax = avocado_prices.plot(kind = "barh", y = "mean", legend = False, title = "Average Avocado Prices", colors = ["steelblue", "seagreen"]) # no error bars added here# Xax.set_xlabel("Price ($)")# Yax.set_ylabel("")ax.set_yticklabels(["Conventional", "Organic"])# Overallfor key, spine in ax.spines.items(): spine.set_visible(False)ax.tick_params(bottom = False, left = False)ax.errorbar(avocado_prices["mean"], avocado_prices.index, xerr = avocado_prices["double_std"], linewidth = 1.5, color = "black", alpha = 0.4, capsize = 4) Output: Creating error bars in python is very easy! Using some advanced pandas functions, we can go from dataframe to a visualization with (or without) error bars in just two lines of code! However, if you haven’t learned the statistics behind error bars yet, you need to do that first. You saw how different the three plots (no error bars vs. dobuled standard deviation vs. standard error) looked. At first this might seem scary, but once you learn it, it’s another very useful tool in your data science skillset. Thanks for reading!
[ { "code": null, "e": 472, "s": 172, "text": "In scientific studies, displaying error bars in your descriptive visualizations is inevitable. Holding information about the variability of your data, they are a necessary complement to your mean scores. However, scientific visualizations tend to be more beautiful on the inside than on the outside." }, { "code": null, "e": 817, "s": 472, "text": "As data scientists, we are taught to use attractive visualizations to tell stories. Anything that distracts the viewer from the main point we are trying to make is adviced to be removed. This makes perfect sense, as managers and customers usually neither have a good grasp of statistics nor much time and energy to spend on your visualizations." }, { "code": null, "e": 852, "s": 817, "text": "To interpret error bars, you need:" }, { "code": null, "e": 900, "s": 852, "text": "a basic understanding of descriptive statistics" }, { "code": null, "e": 1000, "s": 900, "text": "information on what kind of error bar is displayed (typically standard deviation or standard error)" }, { "code": null, "e": 1170, "s": 1000, "text": "Both of those presuppositions conflict with the aim of a data storyteller. You want anyone to understand the results without having to read through eight lines of notes." }, { "code": null, "e": 1650, "s": 1170, "text": "Data storytellers see error bars as obstacles, because they prevent easy, comfortable, and uniform interpretation of their data. Scientists, on the other hand, are trained to display all necessary information and let the reader interpret the results on their own. Neither of these approaches is superior. Oversimplifying results in technical reports or data team meetings is just as disadvantagious as annoying your managers and customers with spontaneous lectures in statistics." }, { "code": null, "e": 1782, "s": 1650, "text": "For anyone willing to justify the β€œscience” in their data science job title, learning when and how to use error bars is inevitable!" }, { "code": null, "e": 2102, "s": 1782, "text": "When I created the visualizations for my first scientific article, I tried lots of different methods. Let me save you some time and introduce you to the quick and easy method I found. All you need to follow this article and apply the method yourself is some basic knowledge of statistics, python and the pandas library." }, { "code": null, "e": 2164, "s": 2102, "text": "There are two main parameters that are suited for error bars." }, { "code": null, "e": 2202, "s": 2164, "text": "(2x) Standard DeviationStandard Error" }, { "code": null, "e": 2226, "s": 2202, "text": "(2x) Standard Deviation" }, { "code": null, "e": 2241, "s": 2226, "text": "Standard Error" }, { "code": null, "e": 2485, "s": 2241, "text": "I highly recommend getting familiar with these parameters, so that you can make educated decisions on which parameter to use for your visualizations. In this article by Claudia Clement, the concepts are explained in a perfectly compressed way." }, { "code": null, "e": 2773, "s": 2485, "text": "First, we need to import our libraries and load our data. We’ll be using the avocado price dataset from kaggle. You don’t need to know much about the dataset. All we want to know is whether conventional and organic avocados (β€œtype” column) have different prices ( β€œAveragePrice” column)." }, { "code": null, "e": 3036, "s": 2773, "text": "# Importsimport pandas as pdimport numpy as np # for calculating standard deviation and meanimport scipy.stats as sp # for calculating standard errorimport matplotlib.pyplot as plt # for improving our visualizations# Read dataavocado = pd.read_csv(\"avocado.csv\")" }, { "code": null, "e": 3289, "s": 3036, "text": "The easiest way to perform our calculations is by using pandas df.groupby function. This function has many useful applications, but in this case, weβ€˜ll use it for aggregated computations of statistical parameters. Below, you can see the code prototype." }, { "code": null, "e": 3349, "s": 3289, "text": "df.groupby(\"col_to_group_by\").agg([func_1, func_2, func_3])" }, { "code": null, "e": 3453, "s": 3349, "text": "We use df.groupby.agg for a quick and easy way to compute statistical parameters for group comparisons." }, { "code": null, "e": 3656, "s": 3453, "text": "We have the dataframe and column to group by, so we need to find the right functions now. Remember, we want the mean, the standard deviation x 2, and the standard error. These are the functions we need:" }, { "code": null, "e": 3662, "s": 3656, "text": "NumPy" }, { "code": null, "e": 3676, "s": 3662, "text": "Mean: np.mean" }, { "code": null, "e": 3703, "s": 3676, "text": "Standard Deviation: np.std" }, { "code": null, "e": 3709, "s": 3703, "text": "SciPy" }, { "code": null, "e": 3741, "s": 3709, "text": "Standard Error: scipy.stats.sem" }, { "code": null, "e": 3934, "s": 3741, "text": "Because the df.groupby.agg function only takes a list of functions as an input, we can’t just use np.std * 2 to get our doubled standard deviation. However, we can just write our own function." }, { "code": null, "e": 3982, "s": 3934, "text": "def double_std(array): return np.std(array) * 2" }, { "code": null, "e": 4043, "s": 3982, "text": "Now, let’s use the prototype code and fill the placeholders." }, { "code": null, "e": 4180, "s": 4043, "text": "# df.groupby(\"col_to_group_by\").agg([func_1, func_2, func_3])avocado_prices = avocado.groupby(\"type\").agg([np.mean, double_std, sp.sem])" }, { "code": null, "e": 4268, "s": 4180, "text": "Nice! Now, let’s select only the β€œAveragePrice” column, because we don’t need the rest." }, { "code": null, "e": 4316, "s": 4268, "text": "avocado_prices = avocado_prices[\"AveragePrice\"]" }, { "code": null, "e": 4373, "s": 4316, "text": "avocado_prices.head() now gives us the following output:" }, { "code": null, "e": 4414, "s": 4373, "text": "Great! Now we have all the data we need." }, { "code": null, "e": 4561, "s": 4414, "text": "Pandas has a really useful function that allows us get a first visualization quickly without going through the whole matplotlib procedure: df.plot" }, { "code": null, "e": 4619, "s": 4561, "text": "It’s basically a matplotlib representation within pandas." }, { "code": null, "e": 4694, "s": 4619, "text": "To get a first plot without any error bars, we just need one line of code:" }, { "code": null, "e": 4791, "s": 4694, "text": "avocado_prices.plot(kind = \"barh\", y = \"mean\", legend = False, title = \"Average Avocado Prices\")" }, { "code": null, "e": 4799, "s": 4791, "text": "Output:" }, { "code": null, "e": 5174, "s": 4799, "text": "We can see that organic avocados have a higher mean price than conventional avocados. But is this a real difference or just random spread? As I promised in the subtitle, we don’t need a single extra line of code to answer this question using error bars. All we need to do is assign our statistical parameter to the xerr argument. Let’s start with the β€œdouble_std” parameter:" }, { "code": null, "e": 5292, "s": 5174, "text": "avocado_prices.plot(kind = \"barh\", y = \"mean\", legend = False, title = \"Average Avocado Prices\", xerr = \"double_std\")" }, { "code": null, "e": 5300, "s": 5292, "text": "Output:" }, { "code": null, "e": 5803, "s": 5300, "text": "There they are! Even without any deep knowledge of how to interpret these error bars, we can see that the variability in prices is rather high and that the error bars of each bar touch the other bar. Maybe the difference isn’t as clear and large as we expected from seeing just the first plot? Again, I won’t go in depth on the interpretation of standard deviation and standard error since this is a practical guide. Just note that this plot leaves us with a different impression than the previous one." }, { "code": null, "e": 5852, "s": 5803, "text": "What happens if we plot the standard error next?" }, { "code": null, "e": 5963, "s": 5852, "text": "avocado_prices.plot(kind = \"barh\", y = \"mean\", legend = False, title = \"Average Avocado Prices\", xerr = \"sem\")" }, { "code": null, "e": 5971, "s": 5963, "text": "Output:" }, { "code": null, "e": 6262, "s": 5971, "text": "What? The error bars are hardly visible. Standard error is sensitive to sample size, as it is lower in large samples than in small samples. The avocado sample has more than 250k observations, so the results make sense. This third plot leaves as with a completely different impression again!" }, { "code": null, "e": 6460, "s": 6262, "text": "Whether and how you use error bars makes a huge difference in the β€œstory” your visualization tells. It is crucial to understand the statistics behind error bars to use and interpret them correctly." }, { "code": null, "e": 6613, "s": 6460, "text": "So far, we got very good results from just one line of code. If we take some more time to improve our visualization, we can get something like Figure 4." }, { "code": null, "e": 7157, "s": 6613, "text": "ax = avocado_prices.plot(kind = \"barh\", y = \"mean\", legend = False, title = \"Average Avocado Prices\", colors = [\"steelblue\", \"seagreen\"]) # no error bars added here# Xax.set_xlabel(\"Price ($)\")# Yax.set_ylabel(\"\")ax.set_yticklabels([\"Conventional\", \"Organic\"])# Overallfor key, spine in ax.spines.items(): spine.set_visible(False)ax.tick_params(bottom = False, left = False)ax.errorbar(avocado_prices[\"mean\"], avocado_prices.index, xerr = avocado_prices[\"double_std\"], linewidth = 1.5, color = \"black\", alpha = 0.4, capsize = 4)" }, { "code": null, "e": 7165, "s": 7157, "text": "Output:" }, { "code": null, "e": 7672, "s": 7165, "text": "Creating error bars in python is very easy! Using some advanced pandas functions, we can go from dataframe to a visualization with (or without) error bars in just two lines of code! However, if you haven’t learned the statistics behind error bars yet, you need to do that first. You saw how different the three plots (no error bars vs. dobuled standard deviation vs. standard error) looked. At first this might seem scary, but once you learn it, it’s another very useful tool in your data science skillset." } ]
How to Integrate Razorpay Payment Gateway in Android? - GeeksforGeeks
31 Jan, 2021 Many apps nowadays require to have a payment gateway inside their application so that users can do any transactions inside their apps to purchase any product or any service. Many apps use the payment gateway features but the integration of this payment gateway is a difficult task in Android applications. So to make this task simple and easy Razorpay have provided a service with the help of this we can integrate the payment solutions in our app very easily and we can also manage all payment methods in our app. In this article, we will take a look at the implementation of a payment gateway in our Android app. We will be building a simple Android application in which we will be displaying an EditText and a button. Inside this screen, we have to add the amount which is to be paid and on clicking the button we will open the Razorpay payment gateway and will make a payment. In this article, we will be adding test credentials for implementing Razorpay in Android. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add dependency of Razor pay library in build.gradle file Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation β€˜com.razorpay:checkout:1.6.4’ After adding this dependency sync your project and now we will move towards the XML part. Step 3: Adding permissions to the Internet Navigate to the app > AndroidManifest.xml file and add the below code to it. XML <uses-permission android:name="android.permission.INTERNET" /> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--EditText text to enter amount--> <EditText android:id="@+id/idEdtAmount" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="20dp" android:hint="Enter amount to be payed" android:inputType="number" /> <!--button to make payment--> <Button android:id="@+id/idBtnPay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idEdtAmount" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:text="Pay using RazorPay" android:textAllCaps="false" /> </RelativeLayout> Step 5: Generating an API key for using Razorpay Browser the Razorpay site in Google or you can click on the link here. After clicking on this link you simply have to signup with your email and password and add some basic information such as your phone number. Note: Here we are creating a testing credential for using Razor Pay. Inside the setting screen, click on Create a new key option your key will be generated. We will be using key ID in our application to test Razor pay. The key-id will start with rzp_test Step 6: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.razorpay.Checkout;import com.razorpay.PaymentResultListener; import org.json.JSONException;import org.json.JSONObject; public class MainActivity extends AppCompatActivity implements PaymentResultListener { // variables for our // edit text and button. private EditText amountEdt; private Button payBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. amountEdt = findViewById(R.id.idEdtAmount); payBtn = findViewById(R.id.idBtnPay); // adding on click listener to our button. payBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting // amount that is entered by user. String samount = amountEdt.getText().toString(); // rounding off the amount. int amount = Math.round(Float.parseFloat(samount) * 100); // initialize Razorpay account. Checkout checkout = new Checkout(); // set your id as below checkout.setKeyID("Enter your key id here"); // set image checkout.setImage(R.drawable.gfgimage); // initialize json object JSONObject object = new JSONObject(); try { // to put name object.put("name", "Geeks for Geeks"); // put description object.put("description", "Test payment"); // to set theme color object.put("theme.color", ""); // put the currency object.put("currency", "INR"); // put amount object.put("amount", amount); // put mobile number object.put("prefill.contact", "9284064503"); // put email object.put("prefill.email", "chaitanyamunje@gmail.com"); // open razorpay to checkout activity checkout.open(MainActivity.this, object); } catch (JSONException e) { e.printStackTrace(); } } }); } @Override public void onPaymentSuccess(String s) { // this method is called on payment success. Toast.makeText(this, "Payment is successful : " + s, Toast.LENGTH_SHORT).show(); } @Override public void onPaymentError(int i, String s) { // on payment failed. Toast.makeText(this, "Payment Failed due to error : " + s, Toast.LENGTH_SHORT).show(); }} Now run your app and see the output of the app. As we are using test credentials so our payment will not be done. For making your payments live you have to make your application live in the Razorpay console and generate a new key. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Content Providers in Android with Example Animation in Android with Example How to View and Locate SQLite Database in Android Studio? Arrays in Java Split() String method in Java with examples For-each loop in Java Initialize an ArrayList in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 23995, "s": 23967, "text": "\n31 Jan, 2021" }, { "code": null, "e": 24611, "s": 23995, "text": "Many apps nowadays require to have a payment gateway inside their application so that users can do any transactions inside their apps to purchase any product or any service. Many apps use the payment gateway features but the integration of this payment gateway is a difficult task in Android applications. So to make this task simple and easy Razorpay have provided a service with the help of this we can integrate the payment solutions in our app very easily and we can also manage all payment methods in our app. In this article, we will take a look at the implementation of a payment gateway in our Android app. " }, { "code": null, "e": 25134, "s": 24611, "text": "We will be building a simple Android application in which we will be displaying an EditText and a button. Inside this screen, we have to add the amount which is to be paid and on clicking the button we will open the Razorpay payment gateway and will make a payment. In this article, we will be adding test credentials for implementing Razorpay in Android. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 25163, "s": 25134, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25325, "s": 25163, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 25390, "s": 25325, "text": "Step 2: Add dependency of Razor pay library in build.gradle file" }, { "code": null, "e": 25509, "s": 25390, "text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 25554, "s": 25509, "text": "implementation β€˜com.razorpay:checkout:1.6.4’" }, { "code": null, "e": 25646, "s": 25554, "text": " After adding this dependency sync your project and now we will move towards the XML part. " }, { "code": null, "e": 25689, "s": 25646, "text": "Step 3: Adding permissions to the Internet" }, { "code": null, "e": 25767, "s": 25689, "text": "Navigate to the app > AndroidManifest.xml file and add the below code to it. " }, { "code": null, "e": 25771, "s": 25767, "text": "XML" }, { "code": "<uses-permission android:name=\"android.permission.INTERNET\" />", "e": 25834, "s": 25771, "text": null }, { "code": null, "e": 25882, "s": 25834, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 26025, "s": 25882, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 26029, "s": 26025, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--EditText text to enter amount--> <EditText android:id=\"@+id/idEdtAmount\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:layout_margin=\"20dp\" android:hint=\"Enter amount to be payed\" android:inputType=\"number\" /> <!--button to make payment--> <Button android:id=\"@+id/idBtnPay\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtAmount\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"20dp\" android:text=\"Pay using RazorPay\" android:textAllCaps=\"false\" /> </RelativeLayout>", "e": 27051, "s": 26029, "text": null }, { "code": null, "e": 27100, "s": 27051, "text": "Step 5: Generating an API key for using Razorpay" }, { "code": null, "e": 27313, "s": 27100, "text": "Browser the Razorpay site in Google or you can click on the link here. After clicking on this link you simply have to signup with your email and password and add some basic information such as your phone number. " }, { "code": null, "e": 27383, "s": 27313, "text": "Note: Here we are creating a testing credential for using Razor Pay. " }, { "code": null, "e": 27570, "s": 27383, "text": "Inside the setting screen, click on Create a new key option your key will be generated. We will be using key ID in our application to test Razor pay. The key-id will start with rzp_test " }, { "code": null, "e": 27618, "s": 27570, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 27808, "s": 27618, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 27813, "s": 27808, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.razorpay.Checkout;import com.razorpay.PaymentResultListener; import org.json.JSONException;import org.json.JSONObject; public class MainActivity extends AppCompatActivity implements PaymentResultListener { // variables for our // edit text and button. private EditText amountEdt; private Button payBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. amountEdt = findViewById(R.id.idEdtAmount); payBtn = findViewById(R.id.idBtnPay); // adding on click listener to our button. payBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting // amount that is entered by user. String samount = amountEdt.getText().toString(); // rounding off the amount. int amount = Math.round(Float.parseFloat(samount) * 100); // initialize Razorpay account. Checkout checkout = new Checkout(); // set your id as below checkout.setKeyID(\"Enter your key id here\"); // set image checkout.setImage(R.drawable.gfgimage); // initialize json object JSONObject object = new JSONObject(); try { // to put name object.put(\"name\", \"Geeks for Geeks\"); // put description object.put(\"description\", \"Test payment\"); // to set theme color object.put(\"theme.color\", \"\"); // put the currency object.put(\"currency\", \"INR\"); // put amount object.put(\"amount\", amount); // put mobile number object.put(\"prefill.contact\", \"9284064503\"); // put email object.put(\"prefill.email\", \"chaitanyamunje@gmail.com\"); // open razorpay to checkout activity checkout.open(MainActivity.this, object); } catch (JSONException e) { e.printStackTrace(); } } }); } @Override public void onPaymentSuccess(String s) { // this method is called on payment success. Toast.makeText(this, \"Payment is successful : \" + s, Toast.LENGTH_SHORT).show(); } @Override public void onPaymentError(int i, String s) { // on payment failed. Toast.makeText(this, \"Payment Failed due to error : \" + s, Toast.LENGTH_SHORT).show(); }}", "e": 31052, "s": 27813, "text": null }, { "code": null, "e": 31100, "s": 31052, "text": "Now run your app and see the output of the app." }, { "code": null, "e": 31284, "s": 31100, "text": "As we are using test credentials so our payment will not be done. For making your payments live you have to make your application live in the Razorpay console and generate a new key. " }, { "code": null, "e": 31292, "s": 31284, "text": "android" }, { "code": null, "e": 31316, "s": 31292, "text": "Technical Scripter 2020" }, { "code": null, "e": 31324, "s": 31316, "text": "Android" }, { "code": null, "e": 31329, "s": 31324, "text": "Java" }, { "code": null, "e": 31348, "s": 31329, "text": "Technical Scripter" }, { "code": null, "e": 31353, "s": 31348, "text": "Java" }, { "code": null, "e": 31361, "s": 31353, "text": "Android" }, { "code": null, "e": 31459, "s": 31361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31468, "s": 31459, "text": "Comments" }, { "code": null, "e": 31481, "s": 31468, "text": "Old Comments" }, { "code": null, "e": 31539, "s": 31481, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 31582, "s": 31539, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 31624, "s": 31582, "text": "Content Providers in Android with Example" }, { "code": null, "e": 31658, "s": 31624, "text": "Animation in Android with Example" }, { "code": null, "e": 31716, "s": 31658, "text": "How to View and Locate SQLite Database in Android Studio?" }, { "code": null, "e": 31731, "s": 31716, "text": "Arrays in Java" }, { "code": null, "e": 31775, "s": 31731, "text": "Split() String method in Java with examples" }, { "code": null, "e": 31797, "s": 31775, "text": "For-each loop in Java" }, { "code": null, "e": 31829, "s": 31797, "text": "Initialize an ArrayList in Java" } ]
Python Program for Fibonacci numbers
In this article, we will learn about the solution and approach to solve the given problem statement. Problem statement βˆ’Our task to compute the nth Fibonacci number. The sequence Fn of Fibonacci numbers is given by the recurrence relation given below Fn = Fn-1 + Fn-2 with seed values (standard) F0 = 0 and F1 = 1. We have two possible solutions to the problem Recursive approach Dynamic approach Live Demo #recursive approach def Fibonacci(n): if n<0: print("Fibbonacci can't be computed") # First Fibonacci number elif n==1: return 0 # Second Fibonacci number elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # main n=10 print(Fibonacci(n)) 34 All the variables are declared in global scope as shown in the image below Live Demo #dynamic approach Fib_Array = [0,1] def fibonacci(n): if n<0: print("Fibbonacci can't be computed") elif n<=len(Fib_Array): return Fib_Array[n-1] else: temp = fibonacci(n-1)+fibonacci(n-2) Fib_Array.append(temp) return temp # Driver Program n=10 print(fibonacci(n)) 34 All the variables are declared in global scope as shown in the image below In this article, we learnt about the approach to compute Fibonacci numbers
[ { "code": null, "e": 1163, "s": 1062, "text": "In this article, we will learn about the solution and approach to solve the given problem statement." }, { "code": null, "e": 1228, "s": 1163, "text": "Problem statement βˆ’Our task to compute the nth Fibonacci number." }, { "code": null, "e": 1313, "s": 1228, "text": "The sequence Fn of Fibonacci numbers is given by the recurrence relation given below" }, { "code": null, "e": 1330, "s": 1313, "text": "Fn = Fn-1 + Fn-2" }, { "code": null, "e": 1358, "s": 1330, "text": "with seed values (standard)" }, { "code": null, "e": 1377, "s": 1358, "text": "F0 = 0 and F1 = 1." }, { "code": null, "e": 1423, "s": 1377, "text": "We have two possible solutions to the problem" }, { "code": null, "e": 1442, "s": 1423, "text": "Recursive approach" }, { "code": null, "e": 1459, "s": 1442, "text": "Dynamic approach" }, { "code": null, "e": 1470, "s": 1459, "text": " Live Demo" }, { "code": null, "e": 1762, "s": 1470, "text": "#recursive approach\ndef Fibonacci(n):\n if n<0:\n print(\"Fibbonacci can't be computed\")\n # First Fibonacci number\n elif n==1:\n return 0\n # Second Fibonacci number\n elif n==2:\n return 1\n else:\n return Fibonacci(n-1)+Fibonacci(n-2)\n# main\nn=10\nprint(Fibonacci(n))" }, { "code": null, "e": 1765, "s": 1762, "text": "34" }, { "code": null, "e": 1840, "s": 1765, "text": "All the variables are declared in global scope as shown in the image below" }, { "code": null, "e": 1851, "s": 1840, "text": " Live Demo" }, { "code": null, "e": 2157, "s": 1851, "text": "#dynamic approach\nFib_Array = [0,1]\n\ndef fibonacci(n):\n if n<0:\n print(\"Fibbonacci can't be computed\")\n elif n<=len(Fib_Array):\n return Fib_Array[n-1]\n else:\n temp = fibonacci(n-1)+fibonacci(n-2)\n Fib_Array.append(temp)\n return temp\n# Driver Program\nn=10\nprint(fibonacci(n))" }, { "code": null, "e": 2160, "s": 2157, "text": "34" }, { "code": null, "e": 2235, "s": 2160, "text": "All the variables are declared in global scope as shown in the image below" }, { "code": null, "e": 2310, "s": 2235, "text": "In this article, we learnt about the approach to compute Fibonacci numbers" } ]
Break Statement Implementation
The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop. The Batch Script language does not have a direct β€˜for’ statement which does a break but this can be implemented by using labels. The following diagram shows the diagrammatic explanation of the break statement implementation in Batch Script. The key thing to note about the above implementation is the involvement of two β€˜if’ conditions. The second β€˜if’ condition is used to control when the break is implemented. If the second β€˜if’ condition is evaluated to be true, then the code block is not executed and the counter is directly implemented. Following is an example of how to carry out the implementation of the break statement. @echo off SET /A "index=1" SET /A "count=5" :while if %index% leq %count% ( if %index%==2 goto :Increment echo The value of index is %index% :Increment SET /A "index=index + 1" goto :while ) The key thing to note about the above program is the addition of a label called :Increment. When the value of index reaches 2, we want to skip the statement which echoes its value to the command prompt and directly just increment the value of index. The above command produces the following output. The value of index is 1 The value of index is 3 The value of index is 4 The value of index is 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2407, "s": 2169, "text": "The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop." }, { "code": null, "e": 2648, "s": 2407, "text": "The Batch Script language does not have a direct β€˜for’ statement which does a break but this can be implemented by using labels. The following diagram shows the diagrammatic explanation of the break statement implementation in Batch Script." }, { "code": null, "e": 2951, "s": 2648, "text": "The key thing to note about the above implementation is the involvement of two β€˜if’ conditions. The second β€˜if’ condition is used to control when the break is implemented. If the second β€˜if’ condition is evaluated to be true, then the code block is not executed and the counter is directly implemented." }, { "code": null, "e": 3038, "s": 2951, "text": "Following is an example of how to carry out the implementation of the break statement." }, { "code": null, "e": 3254, "s": 3038, "text": "@echo off \nSET /A \"index=1\" \nSET /A \"count=5\" \n:while \nif %index% leq %count% ( \n if %index%==2 goto :Increment \n echo The value of index is %index% \n:Increment \n SET /A \"index=index + 1\" \n goto :while \n)" }, { "code": null, "e": 3504, "s": 3254, "text": "The key thing to note about the above program is the addition of a label called :Increment. When the value of index reaches 2, we want to skip the statement which echoes its value to the command prompt and directly just increment the value of index." }, { "code": null, "e": 3553, "s": 3504, "text": "The above command produces the following output." }, { "code": null, "e": 3653, "s": 3553, "text": "The value of index is 1 \nThe value of index is 3 \nThe value of index is 4 \nThe value of index is 5\n" }, { "code": null, "e": 3660, "s": 3653, "text": " Print" }, { "code": null, "e": 3671, "s": 3660, "text": " Add Notes" } ]
Preprocess and prepare a face dataset ready for CNN models | by Nachi Muthu | Towards Data Science
Hola amigos! in this article, I’m going to preprocess the IMDB-WIKI datasets and extract faces from those images and save them to Google Drive along with other useful information such as name, age, and gender. The data will be stored as an object itself in .pickle format. The best part of all this is that you don’t have to run a single line of code on your machine but instead it will be run on Google Colab. Before we dive into our code I’ll give you a brief about Google Colabs. Have you ever worried that your computer’s processing power is not enough or that you lacked a GPU, well you need to worry no more as Google has provided a solution through Google Colab. Dazzling fast execution using GPU on google’s servers through your browser.Google Colabs provides the user with a Jupyter notebook for interactive coding experience. It seamlessly connects with GitHub. All the notebooks created by you are stored in your google drive. As we are going to be using Google Colabs, I recommend you to learn the working of Jupyter notebooks as it will make you feel more comfortable with the environment. If you would want to learn more about Google Colabs you can read this article Google Colab Free GPU Tutorial written by fuat. Before we start coding let me give a brief idea on how we are going to proceed from here on. I’ll be creating a notebook on Google Colab We’ll mount our Google drive to the notebook. We will use this notebook for extracting and processing the dataset and saving it in our Google Drive. At the end of this article, you’ll have a ready to use the dataset for CNN models. In this article, I have explained in detail about each step that is required during our preprocessing. I have also explained each line of code so that you don’t feel lost. Visit Google Colabs home page. You’ll be taken to a welcome notebook. Sign in to your Google account if you already haven’t. Those who have already signed in can skip this step. After you have signed in you’ll be shown a pop-up box. Click on the β€œNew Notebook” button on the bottom right. A new notebook will be created and you’ll be redirected to it. It will also be stored inside a folder named Colab Notebooks in your drive. Now rename your notebook to β€œextract_data_and_preprocess.ipynb”. Open the β€œextractdata_and_preprocess.ipynb” notebook that you have created. Change the runtime type to GPU: Click on runtime option and go to β€œchange runtime type”. select hardware accelerator option and change it to GPU from None and save it. Mount your Google drive to your notebook. Note: You will be able to mount your drive only after you have connected to a runtime. To connect to a runtime if not connected already click on the connect button on the top right corner. Now, we have to import all the packages that we’ll be using throughout data preprocessing. In Colab it is possible to write code in different cells and execute them in one by one in any order you like. Now, execute the cell in which you import all the packages. We’ll be using dlib’s CNN based face recognition model to detect and extract faces from the images in our dataset. CNN based model is slower than the Hog model present in dlib, but it is more precise. To know more about their differences read the article CNN based face detector from dlib written by Arun Ponnusamy. We have to download the weights required for the CNN model to work. So in a new cell let’s write the code to download the weights. I’ll explain the code: Line 2: I have used the get_file function in Keras library to download the weights. The downloaded file will be stored as β€˜mmod_human_face_detector.dat.bz2’ Line 3: β€˜cache_subdir’ β€” the path where the downloaded file has to be stored has to be given here. Line 4: β€˜origin’ β€” the download URL of the file to be downloaded Line 6–10: In these lines, the downloaded compressed file is opened using bz2 package, the content is read in binary format and stored in β€œmmod_human_face_detector.dat” file. This file will be later used by the CNN model. Let’s download the dataset next. The IMDB-WIKI dataset has over 4.5 lakh images. It will take a lot of time to process that many images and extract data from them so, I’ll be using only those images from WIKI dataset. Those who wish to use the IMDB-WIKI can replace the β€œdataset_url”, change β€œdata_key” value to β€œimdb” and β€œmat_file” value to β€œimdb.mat” in the below code. Line 1–2: The download URL of the dataset and the folder name which will be extracted from the file. The folder name has nothing to do with the extraction, it will be used later in our code. Line 4–7: Using the same function as before and giving it a different download URL. We set the β€œextract” parameter to True so, the function will itself extract the dataset. Earlier we didn’t extract using the same function as bz2 file format is not supported for extract. Line 9: β€˜wiki’ is the key in which all the metadata to the images are present. You’ll understand this when you load the .mat file and view it. Line 10: The name of the .mat file that contains the metadata to the images. The dataset is now downloaded and extracted. Let’s load the .mat file present inside the extracted folder. As the file is in MatLab format we have to convert it to a Python datatype. Line 1: We are loading the .mat file using scipy package which will handle the conversion of data format. Line 2: The file loaded is in dictionary format. It has a key β€˜wiki’ which has the rest of the data. To get more understanding about all the data present in the loaded file, you can either print the dictionary or visit the IMDB_WIKI website. Line 3: We are loading the path to all the images into the route variable. The data from the file is not in a very easily accessible format, so don’t be confused with the multi-dimensional array access that I have used. Line 4–9: Initialising all essential variables. All the requirements for preparing our dataset has been now completed. Before we start processing it, let’s write the code to have a look at what we get from the dataset, how we are processing it and what we are going to be storing. Line 1: Creating an object of dlib’s CNN based face detection model. The .dat file passed as parameter is the one that we first downloaded and extracted. Line 6: Picking a random index to load the image from that path and display. Line 7: Let this line be as it is, I will explain in briefly in the next step. Line 8: Loading the image from the given path Line 9: As OpenCV uses BRG format, we are converting the image to standard RGB format. Line 10: Finding the face coordinates for the given image.It will return a list of coordinates for the faces in the image. Line 11–22: Using the face coordinates provided by the dlib model we are drawing a box around the face. We are then cropping out that region using crop_to_bounding_box function provided by TensorFlow. We then display both the images. The cropped face image is what is going to be taken and stored for each image. When you execute the above cell you will see two random images from your dataset that will show you how the images are going to be processed. It’s finally time to process the entire dataset and extract the data we need from it. Line 4: Running a loop for all the images in the dataset, β€˜i’ is the index that we use to fetch the ith path from the list present in the route variable. We then fetch the image at that path. By this, we read all the images in our dataset. Line 7: Using try-except blocks to not let few faulty images stop our process. Line 8–9: The data that I’m accessing is the face score of the image set by the people who have created this dataset. So we are ignoring all the images that do not have a face in it. This will fasten the extraction speed. We are also checking if the gender data for the image we are trying to access is also available. This will help us to neglect all the broken images present in the dataset. Line 10–14: As explained earlier, reading the image and detecting the faces in it. Line 15: We are considering an image only if it has one face in it. Line 18: Taking the face coordinate that was returned by the CNN model. Sometimes the when the face is present in the corner of the image, the model tends to give coordinates outside the image, using the max function we are making sure the coordinates are within the image. Line 19–22: Taking the height and the width of the face. The model returns β€œtop-left” and β€œbottom-right” coordinates. In the next line, we are making sure that the coordinates are within the image. Line 24: Cropping the face from the image using a function provided by TensorFlow’s image class. Line 28: Resizing the image as 32x32 as the image size does not matter for the training of any CNN model, so, we can reduce the space consumed by the image. Line 31: Appending the extracted, resized face image to the images list. Line 32: The date of birth is given in ordinal date format. So, using datetime class we are converting ordinal date to a datetime class object from which we can take the year alone. Line 33–35: Appending the respective data into their respective array. Line 37–51: Handling exceptions that occur during the above process. The consistency of the data in all the arrays is important. So, when an error occurs we are popping out the data of the image and other meta-data from the lists. Now that we have finished processing our dataset, it’s time for us to store the data in our drive. Line 1–7: Creating a dictionary with the data we extracted. Line 8–9: Checking if the directory that we are going to store our data exists, if it does not exists then we create it. Line 10–12: We create a file in append binary mode and dump our dictionary into it. Note: While dumping a huge object to Google Drive, it is advisable to break the data into parts and store it. The session may crash and the runtime will restart if a large file is being stored in the drive. I have attached a link to my β€œextract_data_and_preprocess.ipynb” notebook for your reference https://colab.research.google.com/drive/1U5Or-riULEZTsmO7En_h85_HqgIPEVlN. Hope this article was worth your read. Feel free to contact me regarding any queries. Instagram: nachijr4 E-Mail: nachi2muthu13@gmail.com Medium: Nachi Muthu LinkedIn: Nachi Muthu
[ { "code": null, "e": 583, "s": 172, "text": "Hola amigos! in this article, I’m going to preprocess the IMDB-WIKI datasets and extract faces from those images and save them to Google Drive along with other useful information such as name, age, and gender. The data will be stored as an object itself in .pickle format. The best part of all this is that you don’t have to run a single line of code on your machine but instead it will be run on Google Colab." }, { "code": null, "e": 1110, "s": 583, "text": "Before we dive into our code I’ll give you a brief about Google Colabs. Have you ever worried that your computer’s processing power is not enough or that you lacked a GPU, well you need to worry no more as Google has provided a solution through Google Colab. Dazzling fast execution using GPU on google’s servers through your browser.Google Colabs provides the user with a Jupyter notebook for interactive coding experience. It seamlessly connects with GitHub. All the notebooks created by you are stored in your google drive." }, { "code": null, "e": 1401, "s": 1110, "text": "As we are going to be using Google Colabs, I recommend you to learn the working of Jupyter notebooks as it will make you feel more comfortable with the environment. If you would want to learn more about Google Colabs you can read this article Google Colab Free GPU Tutorial written by fuat." }, { "code": null, "e": 1494, "s": 1401, "text": "Before we start coding let me give a brief idea on how we are going to proceed from here on." }, { "code": null, "e": 1538, "s": 1494, "text": "I’ll be creating a notebook on Google Colab" }, { "code": null, "e": 1584, "s": 1538, "text": "We’ll mount our Google drive to the notebook." }, { "code": null, "e": 1687, "s": 1584, "text": "We will use this notebook for extracting and processing the dataset and saving it in our Google Drive." }, { "code": null, "e": 1770, "s": 1687, "text": "At the end of this article, you’ll have a ready to use the dataset for CNN models." }, { "code": null, "e": 1942, "s": 1770, "text": "In this article, I have explained in detail about each step that is required during our preprocessing. I have also explained each line of code so that you don’t feel lost." }, { "code": null, "e": 2120, "s": 1942, "text": "Visit Google Colabs home page. You’ll be taken to a welcome notebook. Sign in to your Google account if you already haven’t. Those who have already signed in can skip this step." }, { "code": null, "e": 2231, "s": 2120, "text": "After you have signed in you’ll be shown a pop-up box. Click on the β€œNew Notebook” button on the bottom right." }, { "code": null, "e": 2370, "s": 2231, "text": "A new notebook will be created and you’ll be redirected to it. It will also be stored inside a folder named Colab Notebooks in your drive." }, { "code": null, "e": 2435, "s": 2370, "text": "Now rename your notebook to β€œextract_data_and_preprocess.ipynb”." }, { "code": null, "e": 2511, "s": 2435, "text": "Open the β€œextractdata_and_preprocess.ipynb” notebook that you have created." }, { "code": null, "e": 2543, "s": 2511, "text": "Change the runtime type to GPU:" }, { "code": null, "e": 2600, "s": 2543, "text": "Click on runtime option and go to β€œchange runtime type”." }, { "code": null, "e": 2679, "s": 2600, "text": "select hardware accelerator option and change it to GPU from None and save it." }, { "code": null, "e": 2721, "s": 2679, "text": "Mount your Google drive to your notebook." }, { "code": null, "e": 2910, "s": 2721, "text": "Note: You will be able to mount your drive only after you have connected to a runtime. To connect to a runtime if not connected already click on the connect button on the top right corner." }, { "code": null, "e": 3001, "s": 2910, "text": "Now, we have to import all the packages that we’ll be using throughout data preprocessing." }, { "code": null, "e": 3172, "s": 3001, "text": "In Colab it is possible to write code in different cells and execute them in one by one in any order you like. Now, execute the cell in which you import all the packages." }, { "code": null, "e": 3488, "s": 3172, "text": "We’ll be using dlib’s CNN based face recognition model to detect and extract faces from the images in our dataset. CNN based model is slower than the Hog model present in dlib, but it is more precise. To know more about their differences read the article CNN based face detector from dlib written by Arun Ponnusamy." }, { "code": null, "e": 3619, "s": 3488, "text": "We have to download the weights required for the CNN model to work. So in a new cell let’s write the code to download the weights." }, { "code": null, "e": 3642, "s": 3619, "text": "I’ll explain the code:" }, { "code": null, "e": 3799, "s": 3642, "text": "Line 2: I have used the get_file function in Keras library to download the weights. The downloaded file will be stored as β€˜mmod_human_face_detector.dat.bz2’" }, { "code": null, "e": 3898, "s": 3799, "text": "Line 3: β€˜cache_subdir’ β€” the path where the downloaded file has to be stored has to be given here." }, { "code": null, "e": 3963, "s": 3898, "text": "Line 4: β€˜origin’ β€” the download URL of the file to be downloaded" }, { "code": null, "e": 4185, "s": 3963, "text": "Line 6–10: In these lines, the downloaded compressed file is opened using bz2 package, the content is read in binary format and stored in β€œmmod_human_face_detector.dat” file. This file will be later used by the CNN model." }, { "code": null, "e": 4558, "s": 4185, "text": "Let’s download the dataset next. The IMDB-WIKI dataset has over 4.5 lakh images. It will take a lot of time to process that many images and extract data from them so, I’ll be using only those images from WIKI dataset. Those who wish to use the IMDB-WIKI can replace the β€œdataset_url”, change β€œdata_key” value to β€œimdb” and β€œmat_file” value to β€œimdb.mat” in the below code." }, { "code": null, "e": 4749, "s": 4558, "text": "Line 1–2: The download URL of the dataset and the folder name which will be extracted from the file. The folder name has nothing to do with the extraction, it will be used later in our code." }, { "code": null, "e": 5021, "s": 4749, "text": "Line 4–7: Using the same function as before and giving it a different download URL. We set the β€œextract” parameter to True so, the function will itself extract the dataset. Earlier we didn’t extract using the same function as bz2 file format is not supported for extract." }, { "code": null, "e": 5164, "s": 5021, "text": "Line 9: β€˜wiki’ is the key in which all the metadata to the images are present. You’ll understand this when you load the .mat file and view it." }, { "code": null, "e": 5241, "s": 5164, "text": "Line 10: The name of the .mat file that contains the metadata to the images." }, { "code": null, "e": 5424, "s": 5241, "text": "The dataset is now downloaded and extracted. Let’s load the .mat file present inside the extracted folder. As the file is in MatLab format we have to convert it to a Python datatype." }, { "code": null, "e": 5530, "s": 5424, "text": "Line 1: We are loading the .mat file using scipy package which will handle the conversion of data format." }, { "code": null, "e": 5772, "s": 5530, "text": "Line 2: The file loaded is in dictionary format. It has a key β€˜wiki’ which has the rest of the data. To get more understanding about all the data present in the loaded file, you can either print the dictionary or visit the IMDB_WIKI website." }, { "code": null, "e": 5992, "s": 5772, "text": "Line 3: We are loading the path to all the images into the route variable. The data from the file is not in a very easily accessible format, so don’t be confused with the multi-dimensional array access that I have used." }, { "code": null, "e": 6040, "s": 5992, "text": "Line 4–9: Initialising all essential variables." }, { "code": null, "e": 6273, "s": 6040, "text": "All the requirements for preparing our dataset has been now completed. Before we start processing it, let’s write the code to have a look at what we get from the dataset, how we are processing it and what we are going to be storing." }, { "code": null, "e": 6427, "s": 6273, "text": "Line 1: Creating an object of dlib’s CNN based face detection model. The .dat file passed as parameter is the one that we first downloaded and extracted." }, { "code": null, "e": 6504, "s": 6427, "text": "Line 6: Picking a random index to load the image from that path and display." }, { "code": null, "e": 6583, "s": 6504, "text": "Line 7: Let this line be as it is, I will explain in briefly in the next step." }, { "code": null, "e": 6629, "s": 6583, "text": "Line 8: Loading the image from the given path" }, { "code": null, "e": 6716, "s": 6629, "text": "Line 9: As OpenCV uses BRG format, we are converting the image to standard RGB format." }, { "code": null, "e": 6839, "s": 6716, "text": "Line 10: Finding the face coordinates for the given image.It will return a list of coordinates for the faces in the image." }, { "code": null, "e": 7152, "s": 6839, "text": "Line 11–22: Using the face coordinates provided by the dlib model we are drawing a box around the face. We are then cropping out that region using crop_to_bounding_box function provided by TensorFlow. We then display both the images. The cropped face image is what is going to be taken and stored for each image." }, { "code": null, "e": 7294, "s": 7152, "text": "When you execute the above cell you will see two random images from your dataset that will show you how the images are going to be processed." }, { "code": null, "e": 7380, "s": 7294, "text": "It’s finally time to process the entire dataset and extract the data we need from it." }, { "code": null, "e": 7620, "s": 7380, "text": "Line 4: Running a loop for all the images in the dataset, β€˜i’ is the index that we use to fetch the ith path from the list present in the route variable. We then fetch the image at that path. By this, we read all the images in our dataset." }, { "code": null, "e": 7699, "s": 7620, "text": "Line 7: Using try-except blocks to not let few faulty images stop our process." }, { "code": null, "e": 8093, "s": 7699, "text": "Line 8–9: The data that I’m accessing is the face score of the image set by the people who have created this dataset. So we are ignoring all the images that do not have a face in it. This will fasten the extraction speed. We are also checking if the gender data for the image we are trying to access is also available. This will help us to neglect all the broken images present in the dataset." }, { "code": null, "e": 8176, "s": 8093, "text": "Line 10–14: As explained earlier, reading the image and detecting the faces in it." }, { "code": null, "e": 8244, "s": 8176, "text": "Line 15: We are considering an image only if it has one face in it." }, { "code": null, "e": 8518, "s": 8244, "text": "Line 18: Taking the face coordinate that was returned by the CNN model. Sometimes the when the face is present in the corner of the image, the model tends to give coordinates outside the image, using the max function we are making sure the coordinates are within the image." }, { "code": null, "e": 8716, "s": 8518, "text": "Line 19–22: Taking the height and the width of the face. The model returns β€œtop-left” and β€œbottom-right” coordinates. In the next line, we are making sure that the coordinates are within the image." }, { "code": null, "e": 8813, "s": 8716, "text": "Line 24: Cropping the face from the image using a function provided by TensorFlow’s image class." }, { "code": null, "e": 8970, "s": 8813, "text": "Line 28: Resizing the image as 32x32 as the image size does not matter for the training of any CNN model, so, we can reduce the space consumed by the image." }, { "code": null, "e": 9043, "s": 8970, "text": "Line 31: Appending the extracted, resized face image to the images list." }, { "code": null, "e": 9225, "s": 9043, "text": "Line 32: The date of birth is given in ordinal date format. So, using datetime class we are converting ordinal date to a datetime class object from which we can take the year alone." }, { "code": null, "e": 9296, "s": 9225, "text": "Line 33–35: Appending the respective data into their respective array." }, { "code": null, "e": 9527, "s": 9296, "text": "Line 37–51: Handling exceptions that occur during the above process. The consistency of the data in all the arrays is important. So, when an error occurs we are popping out the data of the image and other meta-data from the lists." }, { "code": null, "e": 9626, "s": 9527, "text": "Now that we have finished processing our dataset, it’s time for us to store the data in our drive." }, { "code": null, "e": 9686, "s": 9626, "text": "Line 1–7: Creating a dictionary with the data we extracted." }, { "code": null, "e": 9807, "s": 9686, "text": "Line 8–9: Checking if the directory that we are going to store our data exists, if it does not exists then we create it." }, { "code": null, "e": 9891, "s": 9807, "text": "Line 10–12: We create a file in append binary mode and dump our dictionary into it." }, { "code": null, "e": 10098, "s": 9891, "text": "Note: While dumping a huge object to Google Drive, it is advisable to break the data into parts and store it. The session may crash and the runtime will restart if a large file is being stored in the drive." }, { "code": null, "e": 10266, "s": 10098, "text": "I have attached a link to my β€œextract_data_and_preprocess.ipynb” notebook for your reference https://colab.research.google.com/drive/1U5Or-riULEZTsmO7En_h85_HqgIPEVlN." }, { "code": null, "e": 10305, "s": 10266, "text": "Hope this article was worth your read." }, { "code": null, "e": 10352, "s": 10305, "text": "Feel free to contact me regarding any queries." }, { "code": null, "e": 10372, "s": 10352, "text": "Instagram: nachijr4" }, { "code": null, "e": 10404, "s": 10372, "text": "E-Mail: nachi2muthu13@gmail.com" }, { "code": null, "e": 10424, "s": 10404, "text": "Medium: Nachi Muthu" } ]
The new operator in Java
The new operator is used in Java to create new objects. It can also be used to create an array object. Let us first see the steps when creating an object from a class βˆ’ Declaration βˆ’ A variable declaration with a variable name with an object type. Declaration βˆ’ A variable declaration with a variable name with an object type. Instantiation βˆ’ The 'new' keyword is used to create the object. Instantiation βˆ’ The 'new' keyword is used to create the object. Initialization βˆ’ The 'new' keyword is followed by a call to a constructor. This call initializes the new object. Initialization βˆ’ The 'new' keyword is followed by a call to a constructor. This call initializes the new object. Now, let us see an example βˆ’ public class Puppy { public Puppy(String name) { // This constructor has one parameter, name. System.out.println("Passed Name is : " + name ); } public static void main(String []args) { // Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "jackie" ); } } Passed Name is : jackie Now, let us see an example to create an array using the new operator βˆ’ public class Main { public static void main(String[] args) { double[] myList = new double[] {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } } 1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5
[ { "code": null, "e": 1165, "s": 1062, "text": "The new operator is used in Java to create new objects. It can also be used to create an array object." }, { "code": null, "e": 1231, "s": 1165, "text": "Let us first see the steps when creating an object from a class βˆ’" }, { "code": null, "e": 1310, "s": 1231, "text": "Declaration βˆ’ A variable declaration with a variable name with an object type." }, { "code": null, "e": 1389, "s": 1310, "text": "Declaration βˆ’ A variable declaration with a variable name with an object type." }, { "code": null, "e": 1453, "s": 1389, "text": "Instantiation βˆ’ The 'new' keyword is used to create the object." }, { "code": null, "e": 1517, "s": 1453, "text": "Instantiation βˆ’ The 'new' keyword is used to create the object." }, { "code": null, "e": 1630, "s": 1517, "text": "Initialization βˆ’ The 'new' keyword is followed by a call to a constructor. This call initializes the new object." }, { "code": null, "e": 1743, "s": 1630, "text": "Initialization βˆ’ The 'new' keyword is followed by a call to a constructor. This call initializes the new object." }, { "code": null, "e": 1772, "s": 1743, "text": "Now, let us see an example βˆ’" }, { "code": null, "e": 2091, "s": 1772, "text": "public class Puppy {\n public Puppy(String name) {\n // This constructor has one parameter, name.\n System.out.println(\"Passed Name is : \" + name );\n }\n public static void main(String []args) {\n // Following statement would create an object myPuppy\n Puppy myPuppy = new Puppy( \"jackie\" );\n }\n}" }, { "code": null, "e": 2115, "s": 2091, "text": "Passed Name is : jackie" }, { "code": null, "e": 2186, "s": 2115, "text": "Now, let us see an example to create an array using the new operator βˆ’" }, { "code": null, "e": 2855, "s": 2186, "text": "public class Main {\n public static void main(String[] args) {\n double[] myList = new double[] {1.9, 2.9, 3.4, 3.5};\n // Print all the array elements\n for (int i = 0; i < myList.length; i++) {\n System.out.println(myList[i] + \" \");\n }\n // Summing all elements\n double total = 0;\n for (int i = 0; i < myList.length; i++) {\n total += myList[i];\n }\n System.out.println(\"Total is \" + total);\n // Finding the largest element\n double max = myList[0];\n for (int i = 1; i < myList.length; i++) {\n if (myList[i] > max) max = myList[i];\n }\n System.out.println(\"Max is \" + max);\n }\n}" }, { "code": null, "e": 2896, "s": 2855, "text": "1.9\n2.9\n3.4\n3.5\nTotal is 11.7\nMax is 3.5" } ]
deque_insert( ) in C++ in STL
Given is the task to show the functionality of Deque insert( ) function in C++ STL Deque is the Double Ended Queues that are the sequence containers which provides the functionality of expansion and contraction on both the ends. A queue data structure allow user to insert data only at the END and delete data from the FRONT. Let’s take the analogy of queues at bus stops where the person can be inserted to a queue from the END only and the person standing in the FRONT is the first to be removed whereas in Double ended queue the insertion and deletion of data is possible at both the ends. The deque insert( ) function is used to insert the elements in the deque. The function is use to insert the element at specified position. The function is use to insert the element at specified position. The function is also use to insert the n No. of element in deque. The function is also use to insert the n No. of element in deque. It is also use insert the elements in the range at the specified. It is also use insert the elements in the range at the specified. deque_name.insert (iterator position, const_value_type& value) deque_name.insert (iterator position, size_type n, const_value_type& value) deque_name.insert (iterator position, iterator first, iterator last) Value – specifies the new element to be inserted. Value – specifies the new element to be inserted. n – specifies the number of elements to insert. n – specifies the number of elements to insert. first, last – It specifies the iterator which specifying a range of elements to be inserted. first, last – It specifies the iterator which specifying a range of elements to be inserted. It returns the iterator that points to first of new inserted element. Input Deque βˆ’ 1 2 3 4 5 Output New Deque βˆ’ 1 1 2 3 4 5 Input Deque βˆ’ 11 12 13 14 15 Output New Deque βˆ’ 11 12 12 12 13 14 15 First we declare the deque. First we declare the deque. Then we print the deque. Then we print the deque. Then we declare insert( ) function. Then we declare insert( ) function. By using above approach we can insert new element. // C++ code to demonstrate the working of deque insert( ) function #include<iostream.h> #include<deque.h> Using namespace std; int main ( ){ // declaring the deque Deque<int> deque = { 55, 84, 38, 66, 67 }; // print the deque cout<< β€œ Deque: β€œ; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< *x << β€œ β€œ; // declaring insert( ) function x = deque.insert(x, 22); // printing deque after inserting new element cout<< β€œ New Deque:”; for( x = deque.begin( ); x != deque.end( ); ++x) cout<< β€œ β€œ <<*x; return 0; } If we run the above code then it will generate the following output Input - Deque: 55 84 38 66 67 Output - New Deque: 22 55 84 38 66 67 // C++ code to demonstrate the working of deque insert( ) function #include<iostream.h> #include<deque.h> Using namespace std; int main( ){ deque<char> deque ={ β€˜B’ , β€˜L’ , β€˜D’ }; cout<< β€œ Deque: β€œ; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< *x << β€œ β€œ; deque.insert(x + 1, 2, β€˜O’); // printing deque after inserting new element cout<< β€œ New Deque:”; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< β€œ β€œ <<*x; return 0; } If we run the above code then it will generate the following output Input – Deque: B L D Output – New Deque: B L O O D // C++ code to demonstrate the working of deque insert( ) function #include<iostream.h> #include<deque.h> #include<vector.h> Using namespace std; int main( ){ deque<int> deque ={ 65, 54, 32, 98, 55 }; cout<< β€œ Deque: β€œ; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< *x << β€œ β€œ; vector<int7gt; v(3, 19); deque.insert(x, v.begin( ), v.end( ) ); // printing deque after inserting new element cout<< β€œ New Deque:”; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< β€œ β€œ <<*x; return 0; } If we run the above code then it will generate the following output Input – Deque: 65 54 32 98 55 Output – New Deque: 65 19 19 19 65 54 32 98 55
[ { "code": null, "e": 1145, "s": 1062, "text": "Given is the task to show the functionality of Deque insert( ) function in C++ STL" }, { "code": null, "e": 1655, "s": 1145, "text": "Deque is the Double Ended Queues that are the sequence containers which provides the functionality of expansion and contraction on both the ends. A queue data structure allow user to insert data only at the END and delete data from the FRONT. Let’s take the analogy of queues at bus stops where the person can be inserted to a queue from the END only and the person standing in the FRONT is the first to be removed whereas in Double ended queue the insertion and deletion of data is possible at both the ends." }, { "code": null, "e": 1729, "s": 1655, "text": "The deque insert( ) function is used to insert the elements in the deque." }, { "code": null, "e": 1794, "s": 1729, "text": "The function is use to insert the element at specified position." }, { "code": null, "e": 1859, "s": 1794, "text": "The function is use to insert the element at specified position." }, { "code": null, "e": 1925, "s": 1859, "text": "The function is also use to insert the n No. of element in deque." }, { "code": null, "e": 1991, "s": 1925, "text": "The function is also use to insert the n No. of element in deque." }, { "code": null, "e": 2057, "s": 1991, "text": "It is also use insert the elements in the range at the specified." }, { "code": null, "e": 2123, "s": 2057, "text": "It is also use insert the elements in the range at the specified." }, { "code": null, "e": 2331, "s": 2123, "text": "deque_name.insert (iterator position, const_value_type& value)\ndeque_name.insert (iterator position, size_type n, const_value_type& value)\ndeque_name.insert (iterator position, iterator first, iterator last)" }, { "code": null, "e": 2381, "s": 2331, "text": "Value – specifies the new element to be inserted." }, { "code": null, "e": 2431, "s": 2381, "text": "Value – specifies the new element to be inserted." }, { "code": null, "e": 2479, "s": 2431, "text": "n – specifies the number of elements to insert." }, { "code": null, "e": 2527, "s": 2479, "text": "n – specifies the number of elements to insert." }, { "code": null, "e": 2620, "s": 2527, "text": "first, last – It specifies the iterator which specifying a range of elements to be inserted." }, { "code": null, "e": 2713, "s": 2620, "text": "first, last – It specifies the iterator which specifying a range of elements to be inserted." }, { "code": null, "e": 2783, "s": 2713, "text": "It returns the iterator that points to first of new inserted element." }, { "code": null, "e": 2807, "s": 2783, "text": "Input Deque βˆ’ 1 2 3 4 5" }, { "code": null, "e": 2838, "s": 2807, "text": "Output New Deque βˆ’ 1 1 2 3 4 5" }, { "code": null, "e": 2867, "s": 2838, "text": "Input Deque βˆ’ 11 12 13 14 15" }, { "code": null, "e": 2907, "s": 2867, "text": "Output New Deque βˆ’ 11 12 12 12 13 14 15" }, { "code": null, "e": 2935, "s": 2907, "text": "First we declare the deque." }, { "code": null, "e": 2963, "s": 2935, "text": "First we declare the deque." }, { "code": null, "e": 2988, "s": 2963, "text": "Then we print the deque." }, { "code": null, "e": 3013, "s": 2988, "text": "Then we print the deque." }, { "code": null, "e": 3049, "s": 3013, "text": "Then we declare insert( ) function." }, { "code": null, "e": 3085, "s": 3049, "text": "Then we declare insert( ) function." }, { "code": null, "e": 3136, "s": 3085, "text": "By using above approach we can insert new element." }, { "code": null, "e": 3701, "s": 3136, "text": "// C++ code to demonstrate the working of deque insert( ) function\n#include<iostream.h>\n#include<deque.h>\nUsing namespace std;\nint main ( ){\n // declaring the deque\n Deque<int> deque = { 55, 84, 38, 66, 67 };\n // print the deque\n cout<< β€œ Deque: β€œ;\n for( auto x = deque.begin( ); x != deque.end( ); ++x)\n cout<< *x << β€œ β€œ;\n // declaring insert( ) function\n x = deque.insert(x, 22);\n // printing deque after inserting new element\n cout<< β€œ New Deque:”;\n for( x = deque.begin( ); x != deque.end( ); ++x)\n cout<< β€œ β€œ <<*x;\n return 0;\n}" }, { "code": null, "e": 3769, "s": 3701, "text": "If we run the above code then it will generate the following output" }, { "code": null, "e": 3837, "s": 3769, "text": "Input - Deque: 55 84 38 66 67\nOutput - New Deque: 22 55 84 38 66 67" }, { "code": null, "e": 4324, "s": 3837, "text": "// C++ code to demonstrate the working of deque insert( ) function\n#include<iostream.h>\n#include<deque.h>\nUsing namespace std;\nint main( ){\n deque<char> deque ={ β€˜B’ , β€˜L’ , β€˜D’ };\n cout<< β€œ Deque: β€œ;\n for( auto x = deque.begin( ); x != deque.end( ); ++x)\n cout<< *x << β€œ β€œ;\n deque.insert(x + 1, 2, β€˜O’);\n // printing deque after inserting new element\n cout<< β€œ New Deque:”;\n for( auto x = deque.begin( ); x != deque.end( ); ++x)\n cout<< β€œ β€œ <<*x;\n return 0;\n}" }, { "code": null, "e": 4392, "s": 4324, "text": "If we run the above code then it will generate the following output" }, { "code": null, "e": 4443, "s": 4392, "text": "Input – Deque: B L D\nOutput – New Deque: B L O O D" }, { "code": null, "e": 4990, "s": 4443, "text": "// C++ code to demonstrate the working of deque insert( ) function\n#include<iostream.h>\n#include<deque.h>\n#include<vector.h>\nUsing namespace std;\nint main( ){\n deque<int> deque ={ 65, 54, 32, 98, 55 };\n cout<< β€œ Deque: β€œ;\n for( auto x = deque.begin( ); x != deque.end( ); ++x)\n cout<< *x << β€œ β€œ;\n vector<int7gt; v(3, 19);\n deque.insert(x, v.begin( ), v.end( ) );\n // printing deque after inserting new element\n cout<< β€œ New Deque:”;\n for( auto x = deque.begin( ); x != deque.end( ); ++x)\n cout<< β€œ β€œ <<*x;\n return 0;\n}" }, { "code": null, "e": 5058, "s": 4990, "text": "If we run the above code then it will generate the following output" }, { "code": null, "e": 5135, "s": 5058, "text": "Input – Deque: 65 54 32 98 55\nOutput – New Deque: 65 19 19 19 65 54 32 98 55" } ]
CopyOnWriteArrayList Class in Java
public class CopyOnWriteArrayList extends Object implements List, RandomAccess, Cloneable, Serializable CopyOnWriteArrayList is a thread-safe variant of ArrayList where operations which can change the ArrayList (add, update, set methods) creates a clone of the underlying array. CopyOnWriteArrayList is a thread-safe variant of ArrayList where operations which can change the ArrayList (add, update, set methods) creates a clone of the underlying array. CopyOnWriteArrayList is to be used in a Thread based environment where read operations are very frequent and update operations are rare. CopyOnWriteArrayList is to be used in a Thread based environment where read operations are very frequent and update operations are rare. Iterator of CopyOnWriteArrayList will never throw ConcurrentModificationException. Iterator of CopyOnWriteArrayList will never throw ConcurrentModificationException. Any type of modification to CopyOnWriteArrayList will not reflect during iteration since the iterator was created. Any type of modification to CopyOnWriteArrayList will not reflect during iteration since the iterator was created. List modification methods like remove, set and add are not supported in the iteration. This method will throw UnsupportedOperationException. List modification methods like remove, set and add are not supported in the iteration. This method will throw UnsupportedOperationException. null can be added to the list. null can be added to the list. Following is the list of important methods available in the CopyOnWriteArrayList class. The following program illustrates several of the methods supported by ArrayList βˆ’ Live Demo import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; public class Tester { public static void main(String args[]) { // create an array list CopyOnWriteArrayList al = new CopyOnWriteArrayList(); System.out.println("Initial size of al: " + al.size()); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); try { Iterator iterator = al.iterator(); while(iterator.hasNext()) { iterator.remove(); } }catch(UnsupportedOperationException e) { System.out.println("Method not supported:"); } System.out.println("Size of al: " + al.size()); } } This will produce the following result βˆ’ Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D] Method not supported: Size of al: 5
[ { "code": null, "e": 1169, "s": 1062, "text": "public class CopyOnWriteArrayList\n extends Object\nimplements List, RandomAccess, Cloneable, Serializable" }, { "code": null, "e": 1344, "s": 1169, "text": "CopyOnWriteArrayList is a thread-safe variant of ArrayList where operations which can change the ArrayList (add, update, set methods) creates a clone of the underlying array." }, { "code": null, "e": 1519, "s": 1344, "text": "CopyOnWriteArrayList is a thread-safe variant of ArrayList where operations which can change the ArrayList (add, update, set methods) creates a clone of the underlying array." }, { "code": null, "e": 1656, "s": 1519, "text": "CopyOnWriteArrayList is to be used in a Thread based environment where read operations are very frequent and update operations are rare." }, { "code": null, "e": 1793, "s": 1656, "text": "CopyOnWriteArrayList is to be used in a Thread based environment where read operations are very frequent and update operations are rare." }, { "code": null, "e": 1876, "s": 1793, "text": "Iterator of CopyOnWriteArrayList will never throw ConcurrentModificationException." }, { "code": null, "e": 1959, "s": 1876, "text": "Iterator of CopyOnWriteArrayList will never throw ConcurrentModificationException." }, { "code": null, "e": 2074, "s": 1959, "text": "Any type of modification to CopyOnWriteArrayList will not reflect during iteration since the iterator was created." }, { "code": null, "e": 2189, "s": 2074, "text": "Any type of modification to CopyOnWriteArrayList will not reflect during iteration since the iterator was created." }, { "code": null, "e": 2330, "s": 2189, "text": "List modification methods like remove, set and add are not supported in the iteration. This method will throw UnsupportedOperationException." }, { "code": null, "e": 2471, "s": 2330, "text": "List modification methods like remove, set and add are not supported in the iteration. This method will throw UnsupportedOperationException." }, { "code": null, "e": 2502, "s": 2471, "text": "null can be added to the list." }, { "code": null, "e": 2533, "s": 2502, "text": "null can be added to the list." }, { "code": null, "e": 2621, "s": 2533, "text": "Following is the list of important methods available in the CopyOnWriteArrayList class." }, { "code": null, "e": 2703, "s": 2621, "text": "The following program illustrates several of the methods supported by ArrayList βˆ’" }, { "code": null, "e": 2713, "s": 2703, "text": "Live Demo" }, { "code": null, "e": 3857, "s": 2713, "text": "import java.util.Iterator;\nimport java.util.concurrent.CopyOnWriteArrayList;\npublic class Tester {\n\n public static void main(String args[]) {\n // create an array list\n CopyOnWriteArrayList al = new CopyOnWriteArrayList();\n System.out.println(\"Initial size of al: \" + al.size());\n\n // add elements to the array list\n al.add(\"C\");\n al.add(\"A\");\n al.add(\"E\");\n al.add(\"B\");\n al.add(\"D\");\n al.add(\"F\");\n al.add(1, \"A2\");\n System.out.println(\"Size of al after additions: \" + al.size());\n\n // display the array list\n System.out.println(\"Contents of al: \" + al);\n\n // Remove elements from the array list\n al.remove(\"F\");\n al.remove(2);\n System.out.println(\"Size of al after deletions: \" + al.size());\n System.out.println(\"Contents of al: \" + al);\n\n try {\n Iterator iterator = al.iterator();\n while(iterator.hasNext()) {\n iterator.remove();\n }\n }catch(UnsupportedOperationException e) {\n System.out.println(\"Method not supported:\");\n }\n System.out.println(\"Size of al: \" + al.size());\n }\n}" }, { "code": null, "e": 3898, "s": 3857, "text": "This will produce the following result βˆ’" }, { "code": null, "e": 4088, "s": 3898, "text": "Initial size of al: 0\nSize of al after additions: 7\nContents of al: [C, A2, A, E, B, D, F]\nSize of al after deletions: 5\nContents of al: [C, A2, E, B, D]\nMethod not supported:\nSize of al: 5" } ]
PyTorch - Installation
PyTorch is a popular deep learning framework. In this tutorial, we consider β€œWindows 10” as our operating system. The steps for a successful environmental setup are as follows βˆ’ The following link includes a list of packages which includes suitable packages for PyTorch. All you need to do is download the respective packages and install it as shown in the following screenshots βˆ’ It involves verifying the installation of PyTorch framework using Anaconda Framework. Following command is used to verify the same βˆ’ conda list β€œConda list” shows the list of frameworks which is installed. The highlighted part shows that PyTorch has been successfully installed in our system. Print Add Notes Bookmark this page
[ { "code": null, "e": 2437, "s": 2259, "text": "PyTorch is a popular deep learning framework. In this tutorial, we consider β€œWindows 10” as our operating system. The steps for a successful environmental setup are as follows βˆ’" }, { "code": null, "e": 2530, "s": 2437, "text": "The following link includes a list of packages which includes suitable packages for PyTorch." }, { "code": null, "e": 2640, "s": 2530, "text": "All you need to do is download the respective packages and install it as shown in the following screenshots βˆ’" }, { "code": null, "e": 2726, "s": 2640, "text": "It involves verifying the installation of PyTorch framework using Anaconda Framework." }, { "code": null, "e": 2773, "s": 2726, "text": "Following command is used to verify the same βˆ’" }, { "code": null, "e": 2785, "s": 2773, "text": "conda list\n" }, { "code": null, "e": 2847, "s": 2785, "text": "β€œConda list” shows the list of frameworks which is installed." }, { "code": null, "e": 2934, "s": 2847, "text": "The highlighted part shows that PyTorch has been successfully installed in our system." }, { "code": null, "e": 2941, "s": 2934, "text": " Print" }, { "code": null, "e": 2952, "s": 2941, "text": " Add Notes" } ]
C - Environment Setup
If you want to set up your environment for C programming language, you need the following two software tools available on your computer, (a) Text Editor and (b) The C Compiler. This will be used to type your program. Examples of few a editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. The name and version of text editors can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX. The files you create with your editor are called the source files and they contain the program source codes. The source files for C programs are typically named with the extension ".c". Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it. The source code written in source file is the human readable source for your program. It needs to be "compiled", into machine language so that your CPU can actually execute the program as per the instructions given. The compiler compiles the source codes into final executable programs. The most frequently used and free available compiler is the GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective operating systems. The following section explains how to install GNU C/C++ compiler on various OS. We keep mentioning C/C++ together because GNU gcc compiler works for both C and C++ programming languages. If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line βˆ’ $ gcc -v If you have GNU compiler installed on your machine, then it should print a message as follows βˆ’ Using built-in specs. Target: i386-redhat-linux Configured with: ../configure --prefix=/usr ....... Thread model: posix gcc version 4.1.2 20080704 (Red Hat 4.1.2-46) If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/ This tutorial has been written based on Linux and all the given examples have been compiled on the Cent OS flavor of the Linux system. If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use GNU compiler for C/C++. Xcode is currently available at developer.apple.com/technologies/tools/. To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-<version>.exe. While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more. Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can specify these tools on the command line by their simple names. After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line. Print Add Notes Bookmark this page
[ { "code": null, "e": 2261, "s": 2084, "text": "If you want to set up your environment for C programming language, you need the following two software tools available on your computer, (a) Text Editor and (b) The C Compiler." }, { "code": null, "e": 2407, "s": 2261, "text": "This will be used to type your program. Examples of few a editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi." }, { "code": null, "e": 2597, "s": 2407, "text": "The name and version of text editors can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX." }, { "code": null, "e": 2783, "s": 2597, "text": "The files you create with your editor are called the source files and they contain the program source codes. The source files for C programs are typically named with the extension \".c\"." }, { "code": null, "e": 2975, "s": 2783, "text": "Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it." }, { "code": null, "e": 3191, "s": 2975, "text": "The source code written in source file is the human readable source for your program. It needs to be \"compiled\", into machine language so that your CPU can actually execute the program as per the instructions given." }, { "code": null, "e": 3447, "s": 3191, "text": "The compiler compiles the source codes into final executable programs. The most frequently used and free available compiler is the GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective operating systems." }, { "code": null, "e": 3634, "s": 3447, "text": "The following section explains how to install GNU C/C++ compiler on various OS. We keep mentioning C/C++ together because GNU gcc compiler works for both C and C++ programming languages." }, { "code": null, "e": 3775, "s": 3634, "text": "If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line βˆ’" }, { "code": null, "e": 3785, "s": 3775, "text": "$ gcc -v\n" }, { "code": null, "e": 3881, "s": 3785, "text": "If you have GNU compiler installed on your machine, then it should print a message as follows βˆ’" }, { "code": null, "e": 4048, "s": 3881, "text": "Using built-in specs.\nTarget: i386-redhat-linux\nConfigured with: ../configure --prefix=/usr .......\nThread model: posix\ngcc version 4.1.2 20080704 (Red Hat 4.1.2-46)\n" }, { "code": null, "e": 4189, "s": 4048, "text": "If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/" }, { "code": null, "e": 4324, "s": 4189, "text": "This tutorial has been written based on Linux and all the given examples have been compiled on the Cent OS flavor of the Linux system." }, { "code": null, "e": 4570, "s": 4324, "text": "If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use GNU compiler for C/C++." }, { "code": null, "e": 4643, "s": 4570, "text": "Xcode is currently available at developer.apple.com/technologies/tools/." }, { "code": null, "e": 4911, "s": 4643, "text": "To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-<version>.exe." }, { "code": null, "e": 5053, "s": 4911, "text": "While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more." }, { "code": null, "e": 5219, "s": 5053, "text": "Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can specify these tools on the command line by their simple names." }, { "code": null, "e": 5369, "s": 5219, "text": "After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line." }, { "code": null, "e": 5376, "s": 5369, "text": " Print" }, { "code": null, "e": 5387, "s": 5376, "text": " Add Notes" } ]
Tryit Editor v3.7
CSS 2D Transforms Tryit: The matrix() method
[ { "code": null, "e": 27, "s": 9, "text": "CSS 2D Transforms" } ]
BigDecimal max() Method in Java - GeeksforGeeks
04 Dec, 2018 The java.math.BigDecimal.max(BigDecimal val) method in Java is used to compare two BigDecimal values and return the maximum of the two. This is opposite to BigDecimal max() method in Java. Syntax: public BigDecimal max(BigDecimal val) Parameters: The function accepts a BigDecimal object val as parameter whose value is compared with that of this BigDecimal object and the maximum value is returned. Return Values: This method returns the BigDecimal whose value is the greater of this BigDecimal and val. In case if both are equal, this BigDecimal is returned. Examples: Input : a = 17.000041900, b = 17.0000418999 Output : 17.000041900 Input : a = 235900000146, b = 236000000000 Output : 236000000000 Below programs will illustrate max() function of BigDecimal class. Program 1: // Java program to illustrate use of// BigDecimal max() function in Java import java.math.*; public class GFG { public static void main(String[] args) { // create 2 BigDecimal objects BigDecimal a, b; a = new BigDecimal("235900000146"); b = new BigDecimal("236000000000"); // print the maximum value System.out.println("Maximum Value among " + a + " and " + b + " is " + a.max(b)); }} Maximum Value among 235900000146 and 236000000000 is 236000000000 Program 2: // Java program to illustrate use of BigDecimal max() // to display maximum length among two strings in Java import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal a, b; String s = "GeeksforGeeks"; String str = "GeeksClasses"; int l1, l2; l1 = s.length(); l2 = str.length(); a = new BigDecimal(l1); b = new BigDecimal(l2); // Print the respective lengths System.out.println("Length of string " + s + " is " + a); System.out.println("Length of string " + str + " is " + b); // Print the maximum value System.out.println("Maximum length is " + a.max(b)); }} Length of string GeeksforGeeks is 13 Length of string GeeksClasses is 12 Maximum length is 13 Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#max() Java-BigDecimal Java-Functions java-math Java-math-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n04 Dec, 2018" }, { "code": null, "e": 24137, "s": 23948, "text": "The java.math.BigDecimal.max(BigDecimal val) method in Java is used to compare two BigDecimal values and return the maximum of the two. This is opposite to BigDecimal max() method in Java." }, { "code": null, "e": 24145, "s": 24137, "text": "Syntax:" }, { "code": null, "e": 24183, "s": 24145, "text": "public BigDecimal max(BigDecimal val)" }, { "code": null, "e": 24348, "s": 24183, "text": "Parameters: The function accepts a BigDecimal object val as parameter whose value is compared with that of this BigDecimal object and the maximum value is returned." }, { "code": null, "e": 24509, "s": 24348, "text": "Return Values: This method returns the BigDecimal whose value is the greater of this BigDecimal and val. In case if both are equal, this BigDecimal is returned." }, { "code": null, "e": 24519, "s": 24509, "text": "Examples:" }, { "code": null, "e": 24653, "s": 24519, "text": "Input : a = 17.000041900, b = 17.0000418999\nOutput : 17.000041900\n\nInput : a = 235900000146, b = 236000000000\nOutput : 236000000000\n" }, { "code": null, "e": 24720, "s": 24653, "text": "Below programs will illustrate max() function of BigDecimal class." }, { "code": null, "e": 24731, "s": 24720, "text": "Program 1:" }, { "code": "// Java program to illustrate use of// BigDecimal max() function in Java import java.math.*; public class GFG { public static void main(String[] args) { // create 2 BigDecimal objects BigDecimal a, b; a = new BigDecimal(\"235900000146\"); b = new BigDecimal(\"236000000000\"); // print the maximum value System.out.println(\"Maximum Value among \" + a + \" and \" + b + \" is \" + a.max(b)); }}", "e": 25204, "s": 24731, "text": null }, { "code": null, "e": 25271, "s": 25204, "text": "Maximum Value among 235900000146 and 236000000000 is 236000000000\n" }, { "code": null, "e": 25282, "s": 25271, "text": "Program 2:" }, { "code": "// Java program to illustrate use of BigDecimal max() // to display maximum length among two strings in Java import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigDecimal objects BigDecimal a, b; String s = \"GeeksforGeeks\"; String str = \"GeeksClasses\"; int l1, l2; l1 = s.length(); l2 = str.length(); a = new BigDecimal(l1); b = new BigDecimal(l2); // Print the respective lengths System.out.println(\"Length of string \" + s + \" is \" + a); System.out.println(\"Length of string \" + str + \" is \" + b); // Print the maximum value System.out.println(\"Maximum length is \" + a.max(b)); }}", "e": 26034, "s": 25282, "text": null }, { "code": null, "e": 26129, "s": 26034, "text": "Length of string GeeksforGeeks is 13\nLength of string GeeksClasses is 12\nMaximum length is 13\n" }, { "code": null, "e": 26214, "s": 26129, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#max()" }, { "code": null, "e": 26230, "s": 26214, "text": "Java-BigDecimal" }, { "code": null, "e": 26245, "s": 26230, "text": "Java-Functions" }, { "code": null, "e": 26255, "s": 26245, "text": "java-math" }, { "code": null, "e": 26273, "s": 26255, "text": "Java-math-package" }, { "code": null, "e": 26278, "s": 26273, "text": "Java" }, { "code": null, "e": 26283, "s": 26278, "text": "Java" }, { "code": null, "e": 26381, "s": 26283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26396, "s": 26381, "text": "Stream In Java" }, { "code": null, "e": 26442, "s": 26396, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26463, "s": 26442, "text": "Constructors in Java" }, { "code": null, "e": 26482, "s": 26463, "text": "Exceptions in Java" }, { "code": null, "e": 26512, "s": 26482, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26529, "s": 26512, "text": "Generics in Java" }, { "code": null, "e": 26572, "s": 26529, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26601, "s": 26572, "text": "HashMap get() Method in Java" }, { "code": null, "e": 26622, "s": 26601, "text": "Introduction to Java" } ]
How can I get Webdriver Session ID in Selenium?
We can get the webdriver session id with Selenium webdriver using the SessionId class. A session id is a distinctive number that is given to the webdriver by the server. This number is utilized by the webdriver to establish communication with the browser. The commands in our Selenium tests are directed to the browser with the help of this session id. The method getSessionId is used to obtain the webdriver session id. SessionId s = ((RemoteWebDriver) driver).getSessionId(); import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.remote.SessionId; import org.openqa.selenium.remote.RemoteWebDriver; public class BrwSessionId{ public static void main(String[] args) { //set chromedriver.exe file path System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/index.htm"); //get webdriver session id SessionId s = ((RemoteWebDriver) driver).getSessionId(); System.out.println("Session Id is: " + s); //browser close driver.quit(); } }
[ { "code": null, "e": 1232, "s": 1062, "text": "We can get the webdriver session id with Selenium webdriver using the SessionId class. A session id is a distinctive number that is given to the webdriver by the server." }, { "code": null, "e": 1483, "s": 1232, "text": "This number is utilized by the webdriver to establish communication with the browser. The commands in our Selenium tests are directed to the browser with the help of this session id. The method getSessionId is used to obtain the webdriver session id." }, { "code": null, "e": 1540, "s": 1483, "text": "SessionId s = ((RemoteWebDriver) driver).getSessionId();" }, { "code": null, "e": 2439, "s": 1540, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.remote.SessionId;\nimport org.openqa.selenium.remote.RemoteWebDriver;\npublic class BrwSessionId{\n public static void main(String[] args) {\n //set chromedriver.exe file path\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n //get webdriver session id\n SessionId s = ((RemoteWebDriver) driver).getSessionId();\n System.out.println(\"Session Id is: \" + s);\n //browser close\n driver.quit();\n }\n}" } ]
Cuckoo Hashing - Worst case O(1) Lookup! - GeeksforGeeks
13 Sep, 2021 Background : There are three basic operations that must be supported by a hash table (or a dictionary): Lookup(key): return true if key is there on the table, else false Insert(key): add the item β€˜key’ to the table if not already present Delete(key): removes β€˜key’ from the table Collisions are very likely even if we have a big table to store keys. Using the results from the birthday paradox: with only 23 persons, the probability that two people share the same birth date is 50%! There are 3 general strategies towards resolving hash collisions: Closed addressing or Chaining: store colliding elements in an auxiliary data structure like a linked list or a binary search tree. Open addressing: allow elements to overflow out of their target bucket and into other spaces. Although above solutions provide expected lookup cost as O(1), the expected worst-case cost of a lookup in Open Addressing (with linear probing) is Ξ©(log n) and Θ(log n / log log n) in simple chaining (Source : Standford Lecture Notes). To close the gap of expected time and worst case expected time, two ideas are used: Multiple-choice hashing: Give each element multiple choices for positions where it can reside in the hash table Relocation hashing: Allow elements in the hash table to move after being placed Cuckoo Hashing : Cuckoo hashing applies the idea of multiple-choice and relocation together and guarantees O(1) worst case lookup time! Multiple-choice: We give a key two choices the h1(key) and h2(key) for residing. Relocation: It may happen that h1(key) and h2(key) are preoccupied. This is resolved by imitating the Cuckoo bird: it pushes the other eggs or young out of the nest when it hatches. Analogously, inserting a new key into a cuckoo hashing table may push an older key to a different location. This leaves us with the problem of re-placing the older key. If the alternate position of older key is vacant, there is no problem.Otherwise, the older key displaces another key. This continues until the procedure finds a vacant position, or enters a cycle. In the case of a cycle, new hash functions are chosen and the whole data structure is β€˜rehashed’. Multiple rehashes might be necessary before Cuckoo succeeds. If the alternate position of older key is vacant, there is no problem. Otherwise, the older key displaces another key. This continues until the procedure finds a vacant position, or enters a cycle. In the case of a cycle, new hash functions are chosen and the whole data structure is β€˜rehashed’. Multiple rehashes might be necessary before Cuckoo succeeds. Insertion is expected O(1) (amortized) with high probability, even considering the possibility of rehashing, as long as the number of keys is kept below half of the capacity of the hash table, i.e., the load factor is below 50%. Deletion is O(1) worst-case as it requires inspection of just two locations in the hash table. Illustration Input: {20, 50, 53, 75, 100, 67, 105, 3, 36, 39} Hash Functions: h1(key) = key%11 h2(key) = (key/11)%11 Let’s start by inserting 20 at its possible position in the first table determined by h1(20): Next: 50 Next: 53. h1(53) = 9. But 20 is already there at 9. We place 53 in table 1 & 20 in table 2 at h2(20) Next: 75. h1(75) = 9. But 53 is already there at 9. We place 75 in table 1 & 53 in table 2 at h2(53) Next: 100. h1(100) = 1. Next: 67. h1(67) = 1. But 100 is already there at 1. We place 67 in table 1 & 100 in table 2 Next: 105. h1(105) = 6. But 50 is already there at 6. We place 105 in table 1 & 50 in table 2 at h2(50) = 4. Now 53 has been displaced. h1(53) = 9. 75 displaced: h2(75) = 6. Next: 3. h1(3) = 3. Next: 36. h1(36) = 3. h2(3) = 0. Next: 39. h1(39) = 6. h2(105) = 9. h1(100) = 1. h2(67) = 6. h1(75) = 9. h2(53) = 4. h1(50) = 6. h2(39) = 3.Here, the new key 39 is displaced later in the recursive calls to place 105, which it displaced. Implementation: Below is the implementation of Cuckoo hashing C++ Java C# Javascript // C++ program to demonstrate working of Cuckoo// hashing.#include<bits/stdc++.h> // upper bound on number of elements in our set#define MAXN 11 // choices for position#define ver 2 // Auxiliary space bounded by a small multiple// of MAXN, minimizing wastageint hashtable[ver][MAXN]; // Array to store possible positions for a keyint pos[ver]; /* function to fill hash table with dummy value * dummy value: INT_MIN * number of hashtables: ver */void initTable(){ for (int j=0; j<MAXN; j++) for (int i=0; i<ver; i++) hashtable[i][j] = INT_MIN;} /* return hashed value for a key * function: ID of hash function according to which key has to hashed * key: item to be hashed */int hash(int function, int key){ switch (function) { case 1: return key%MAXN; case 2: return (key/MAXN)%MAXN; }} /* function to place a key in one of its possible positions * tableID: table in which key has to be placed, also equal to function according to which key must be hashed * cnt: number of times function has already been called in order to place the first input key * n: maximum number of times function can be recursively called before stopping and declaring presence of cycle */void place(int key, int tableID, int cnt, int n){ /* if function has been recursively called max number of times, stop and declare cycle. Rehash. */ if (cnt==n) { printf("%d unpositioned\n", key); printf("Cycle present. REHASH.\n"); return; } /* calculate and store possible positions for the key. * check if key already present at any of the positions. If YES, return. */ for (int i=0; i<ver; i++) { pos[i] = hash(i+1, key); if (hashtable[i][pos[i]] == key) return; } /* check if another key is already present at the position for the new key in the table * If YES: place the new key in its position * and place the older key in an alternate position for it in the next table */ if (hashtable[tableID][pos[tableID]]!=INT_MIN) { int dis = hashtable[tableID][pos[tableID]]; hashtable[tableID][pos[tableID]] = key; place(dis, (tableID+1)%ver, cnt+1, n); } else //else: place the new key in its position hashtable[tableID][pos[tableID]] = key;} /* function to print hash table contents */void printTable(){ printf("Final hash tables:\n"); for (int i=0; i<ver; i++, printf("\n")) for (int j=0; j<MAXN; j++) (hashtable[i][j]==INT_MIN)? printf("- "): printf("%d ", hashtable[i][j]); printf("\n");} /* function for Cuckoo-hashing keys * keys[]: input array of keys * n: size of input array */void cuckoo(int keys[], int n){ // initialize hash tables to a dummy value (INT-MIN) // indicating empty position initTable(); // start with placing every key at its position in // the first hash table according to first hash // function for (int i=0, cnt=0; i<n; i++, cnt=0) place(keys[i], 0, cnt, n); //print the final hash tables printTable();} /* driver function */int main(){ /* following array doesn't have any cycles and hence all keys will be inserted without any rehashing */ int keys_1[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39}; int n = sizeof(keys_1)/sizeof(int); cuckoo(keys_1, n); /* following array has a cycle and hence we will have to rehash to position every key */ int keys_2[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39, 6}; int m = sizeof(keys_2)/sizeof(int); cuckoo(keys_2, m); return 0;} // Java program to demonstrate working of// Cuckoo hashing.import java.util.*; class GFG{ // upper bound on number of elements in our setstatic int MAXN = 11; // choices for positionstatic int ver = 2; // Auxiliary space bounded by a small multiple// of MAXN, minimizing wastagestatic int [][]hashtable = new int[ver][MAXN]; // Array to store possible positions for a keystatic int []pos = new int[ver]; /* function to fill hash table with dummy value* dummy value: INT_MIN* number of hashtables: ver */static void initTable(){ for (int j = 0; j < MAXN; j++) for (int i = 0; i < ver; i++) hashtable[i][j] = Integer.MIN_VALUE;} /* return hashed value for a key* function: ID of hash function according to which key has to hashed* key: item to be hashed */static int hash(int function, int key){ switch (function) { case 1: return key % MAXN; case 2: return (key / MAXN) % MAXN; } return Integer.MIN_VALUE;} /* function to place a key in one of its possible positions* tableID: table in which key has to be placed, also equal to function according to which key must be hashed* cnt: number of times function has already been called in order to place the first input key* n: maximum number of times function can be recursively called before stopping and declaring presence of cycle */static void place(int key, int tableID, int cnt, int n){ /* if function has been recursively called max number of times, stop and declare cycle. Rehash. */ if (cnt == n) { System.out.printf("%d unpositioned\n", key); System.out.printf("Cycle present. REHASH.\n"); return; } /* calculate and store possible positions for the key. * check if key already present at any of the positions. If YES, return. */ for (int i = 0; i < ver; i++) { pos[i] = hash(i + 1, key); if (hashtable[i][pos[i]] == key) return; } /* check if another key is already present at the position for the new key in the table * If YES: place the new key in its position * and place the older key in an alternate position for it in the next table */ if (hashtable[tableID][pos[tableID]] != Integer.MIN_VALUE) { int dis = hashtable[tableID][pos[tableID]]; hashtable[tableID][pos[tableID]] = key; place(dis, (tableID + 1) % ver, cnt + 1, n); } else // else: place the new key in its position hashtable[tableID][pos[tableID]] = key;} /* function to print hash table contents */static void printTable(){ System.out.printf("Final hash tables:\n"); for (int i = 0; i < ver; i++, System.out.printf("\n")) for (int j = 0; j < MAXN; j++) if(hashtable[i][j] == Integer.MIN_VALUE) System.out.printf("- "); else System.out.printf("%d ", hashtable[i][j]); System.out.printf("\n");} /* function for Cuckoo-hashing keys* keys[]: input array of keys* n: size of input array */static void cuckoo(int keys[], int n){ // initialize hash tables to a dummy value // (INT-MIN) indicating empty position initTable(); // start with placing every key at its position in // the first hash table according to first hash // function for (int i = 0, cnt = 0; i < n; i++, cnt = 0) place(keys[i], 0, cnt, n); // print the final hash tables printTable();} // Driver Codepublic static void main(String[] args){ /* following array doesn't have any cycles and hence all keys will be inserted without any rehashing */ int keys_1[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39}; int n = keys_1.length; cuckoo(keys_1, n); /* following array has a cycle and hence we will have to rehash to position every key */ int keys_2[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39, 6}; int m = keys_2.length; cuckoo(keys_2, m);}} // This code is contributed by Princi Singh // C# program to demonstrate working of// Cuckoo hashing.using System; class GFG{ // upper bound on number of// elements in our setstatic int MAXN = 11; // choices for positionstatic int ver = 2; // Auxiliary space bounded by a small// multiple of MAXN, minimizing wastagestatic int [,]hashtable = new int[ver, MAXN]; // Array to store// possible positions for a keystatic int []pos = new int[ver]; /* function to fill hash tablewith dummy value* dummy value: INT_MIN* number of hashtables: ver */static void initTable(){ for (int j = 0; j < MAXN; j++) for (int i = 0; i < ver; i++) hashtable[i, j] = int.MinValue;} /* return hashed value for a key* function: ID of hash functionaccording to which key has to hashed* key: item to be hashed */static int hash(int function, int key){ switch (function) { case 1: return key % MAXN; case 2: return (key / MAXN) % MAXN; } return int.MinValue;} /* function to place a key in one ofits possible positions* tableID: table in which keyhas to be placed, also equal to functionaccording to which key must be hashed* cnt: number of times function has alreadybeen called in order to place the first input key* n: maximum number of times functioncan be recursively called before stopping anddeclaring presence of cycle */static void place(int key, int tableID, int cnt, int n){ /* if function has been recursively called max number of times, stop and declare cycle. Rehash. */ if (cnt == n) { Console.Write("{0} unpositioned\n", key); Console.Write("Cycle present. REHASH.\n"); return; } /* calculate and store possible positions * for the key. Check if key already present at any of the positions. If YES, return. */ for (int i = 0; i < ver; i++) { pos[i] = hash(i + 1, key); if (hashtable[i, pos[i]] == key) return; } /* check if another key is already present at the position for the new key in the table * If YES: place the new key in its position * and place the older key in an alternate position for it in the next table */ if (hashtable[tableID, pos[tableID]] != int.MinValue) { int dis = hashtable[tableID, pos[tableID]]; hashtable[tableID, pos[tableID]] = key; place(dis, (tableID + 1) % ver, cnt + 1, n); } else // else: place the new key in its position hashtable[tableID, pos[tableID]] = key;} /* function to print hash table contents */static void printTable(){ Console.Write("Final hash tables:\n"); for (int i = 0; i < ver; i++, Console.Write("\n")) for (int j = 0; j < MAXN; j++) if(hashtable[i, j] == int.MinValue) Console.Write("- "); else Console.Write("{0} ", hashtable[i, j]); Console.Write("\n");} /* function for Cuckoo-hashing keys* keys[]: input array of keys* n: size of input array */static void cuckoo(int []keys, int n){ // initialize hash tables to a // dummy value (INT-MIN) // indicating empty position initTable(); // start with placing every key // at its position in the first // hash table according to first // hash function for (int i = 0, cnt = 0; i < n; i++, cnt = 0) place(keys[i], 0, cnt, n); // print the final hash tables printTable();} // Driver Codepublic static void Main(String[] args){ /* following array doesn't have any cycles and hence all keys will be inserted without any rehashing */ int []keys_1 = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39}; int n = keys_1.Length; cuckoo(keys_1, n); /* following array has a cycle and hence we will have to rehash to position every key */ int []keys_2 = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39, 6}; int m = keys_2.Length; cuckoo(keys_2, m);}} // This code is contributed by PrinciRaj1992 <script> // Javascript program to demonstrate working of// Cuckoo hashing. // upper bound on number of elements in our setlet MAXN = 11; // choices for positionlet ver = 2; // Auxiliary space bounded by a small multiple// of MAXN, minimizing wastagelet hashtable = new Array(ver);for (var i = 0; i < hashtable.length; i++) { hashtable[i] = new Array(2);} // Array to store possible positions for a keylet pos = Array(ver).fill(0); /* function to fill hash table with dummy value* dummy value: let_MIN* number of hashtables: ver */function initTable(){ for (let j = 0; j < MAXN; j++) for (let i = 0; i < ver; i++) hashtable[i][j] = Number.MIN_VALUE;} /* return hashed value for a key* function: ID of hash function according to which key has to hashed* key: item to be hashed */function hash(function, key){ switch (function) { case 1: return key % MAXN; case 2: return (Math.floor(key / MAXN)) % MAXN; } return Number.MIN_VALUE;} /* function to place a key in one of its possible positions* tableID: table in which key has to be placed, also equal to function according to which key must be hashed* cnt: number of times function has already been called in order to place the first input key* n: maximum number of times function can be recursively called before stopping and declaring presence of cycle */function place(key, tableID, cnt, n){ /* if function has been recursively called max number of times, stop and declare cycle. Rehash. */ if (cnt == n) { document.write(key + " unpositioned" + "<br/>"); document.write("Cycle present. REHASH." + "<br/>"); return; } /* calculate and store possible positions for the key. * check if key already present at any of the positions. If YES, return. */ for (let i = 0; i < ver; i++) { pos[i] = hash(i + 1, key); if (hashtable[i][pos[i]] == key) return; } /* check if another key is already present at the position for the new key in the table * If YES: place the new key in its position * and place the older key in an alternate position for it in the next table */ if (hashtable[tableID][pos[tableID]] != Number.MIN_VALUE) { let dis = hashtable[tableID][pos[tableID]]; hashtable[tableID][pos[tableID]] = key; place(dis, (tableID + 1) % ver, cnt + 1, n); } else // else: place the new key in its position hashtable[tableID][pos[tableID]] = key;} /* function to print hash table contents */function printTable(){ document.write("Final hash tables:" + "<br/>"); for (let i = 0; i < ver; i++, document.write("<br/>")) for (let j = 0; j < MAXN; j++) if(hashtable[i][j] == Number.MIN_VALUE) document.write("- "); else document.write(hashtable[i][j] + " "); document.write("<br/>");} /* function for Cuckoo-hashing keys* keys[]: input array of keys* n: size of input array */function cuckoo(keys, n){ // initialize hash tables to a dummy value // (let-MIN) indicating empty position initTable(); // start with placing every key at its position in // the first hash table according to first hash // function for (let i = 0, cnt = 0; i < n; i++, cnt = 0) place(keys[i], 0, cnt, n); // print the final hash tables printTable();} // Driver program /* following array doesn't have any cycles and hence all keys will be inserted without any rehashing */ let keys_1 = [20, 50, 53, 75, 100, 67, 105, 3, 36, 39]; let n = keys_1.length; cuckoo(keys_1, n); /* following array has a cycle and hence we will have to rehash to position every key */ let keys_2 = [20, 50, 53, 75, 100, 67, 105, 3, 36, 39, 6]; let m = keys_2.length; cuckoo(keys_2, m); </script> Output: Final hash tables: - 100 - 36 - - 50 - - 75 - 3 20 - 39 53 - 67 - - 105 - 105 unpositioned Cycle present. REHASH. Final hash tables: - 67 - 3 - - 39 - - 53 - 6 20 - 36 50 - 75 - - 100 - Generalizations of cuckoo hashing that use more than 2 alternative hash functions can be expected to utilize a larger part of the capacity of the hash table efficiently while sacrificing some lookup and insertion speed. Example: if we use 3 hash functions, it’s safe to load 91% and still be operating within expected bounds. This article is contributed by Yash Varyani. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princi singh princiraj1992 target_2 ankita_saini surindertarika1234 Hash Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hashing | Set 2 (Separate Chaining) Most frequent element in an array Sort string of characters Counting frequencies of array elements Sorting a Map by value in C++ STL Double Hashing C++ program for hashing with chaining Quadratic Probing in Hashing Return maximum occurring character in an input string Rearrange an array such that arr[i] = i
[ { "code": null, "e": 24794, "s": 24766, "text": "\n13 Sep, 2021" }, { "code": null, "e": 24900, "s": 24794, "text": "Background : There are three basic operations that must be supported by a hash table (or a dictionary): " }, { "code": null, "e": 24966, "s": 24900, "text": "Lookup(key): return true if key is there on the table, else false" }, { "code": null, "e": 25034, "s": 24966, "text": "Insert(key): add the item β€˜key’ to the table if not already present" }, { "code": null, "e": 25076, "s": 25034, "text": "Delete(key): removes β€˜key’ from the table" }, { "code": null, "e": 25346, "s": 25076, "text": "Collisions are very likely even if we have a big table to store keys. Using the results from the birthday paradox: with only 23 persons, the probability that two people share the same birth date is 50%! There are 3 general strategies towards resolving hash collisions: " }, { "code": null, "e": 25477, "s": 25346, "text": "Closed addressing or Chaining: store colliding elements in an auxiliary data structure like a linked list or a binary search tree." }, { "code": null, "e": 25571, "s": 25477, "text": "Open addressing: allow elements to overflow out of their target bucket and into other spaces." }, { "code": null, "e": 25893, "s": 25571, "text": "Although above solutions provide expected lookup cost as O(1), the expected worst-case cost of a lookup in Open Addressing (with linear probing) is Ξ©(log n) and Θ(log n / log log n) in simple chaining (Source : Standford Lecture Notes). To close the gap of expected time and worst case expected time, two ideas are used: " }, { "code": null, "e": 26005, "s": 25893, "text": "Multiple-choice hashing: Give each element multiple choices for positions where it can reside in the hash table" }, { "code": null, "e": 26085, "s": 26005, "text": "Relocation hashing: Allow elements in the hash table to move after being placed" }, { "code": null, "e": 26224, "s": 26085, "text": " Cuckoo Hashing : Cuckoo hashing applies the idea of multiple-choice and relocation together and guarantees O(1) worst case lookup time! " }, { "code": null, "e": 26305, "s": 26224, "text": "Multiple-choice: We give a key two choices the h1(key) and h2(key) for residing." }, { "code": null, "e": 27012, "s": 26305, "text": "Relocation: It may happen that h1(key) and h2(key) are preoccupied. This is resolved by imitating the Cuckoo bird: it pushes the other eggs or young out of the nest when it hatches. Analogously, inserting a new key into a cuckoo hashing table may push an older key to a different location. This leaves us with the problem of re-placing the older key. If the alternate position of older key is vacant, there is no problem.Otherwise, the older key displaces another key. This continues until the procedure finds a vacant position, or enters a cycle. In the case of a cycle, new hash functions are chosen and the whole data structure is β€˜rehashed’. Multiple rehashes might be necessary before Cuckoo succeeds." }, { "code": null, "e": 27083, "s": 27012, "text": "If the alternate position of older key is vacant, there is no problem." }, { "code": null, "e": 27369, "s": 27083, "text": "Otherwise, the older key displaces another key. This continues until the procedure finds a vacant position, or enters a cycle. In the case of a cycle, new hash functions are chosen and the whole data structure is β€˜rehashed’. Multiple rehashes might be necessary before Cuckoo succeeds." }, { "code": null, "e": 27598, "s": 27369, "text": "Insertion is expected O(1) (amortized) with high probability, even considering the possibility of rehashing, as long as the number of keys is kept below half of the capacity of the hash table, i.e., the load factor is below 50%." }, { "code": null, "e": 27710, "s": 27598, "text": "Deletion is O(1) worst-case as it requires inspection of just two locations in the hash table. Illustration " }, { "code": null, "e": 27718, "s": 27710, "text": "Input: " }, { "code": null, "e": 27760, "s": 27718, "text": "{20, 50, 53, 75, 100, 67, 105, 3, 36, 39}" }, { "code": null, "e": 27778, "s": 27760, "text": " Hash Functions: " }, { "code": null, "e": 27817, "s": 27778, "text": "h1(key) = key%11\nh2(key) = (key/11)%11" }, { "code": null, "e": 27911, "s": 27817, "text": "Let’s start by inserting 20 at its possible position in the first table determined by h1(20):" }, { "code": null, "e": 27920, "s": 27911, "text": "Next: 50" }, { "code": null, "e": 28022, "s": 27920, "text": "Next: 53. h1(53) = 9. But 20 is already there at 9. We place 53 in table 1 & 20 in table 2 at h2(20) " }, { "code": null, "e": 28124, "s": 28022, "text": "Next: 75. h1(75) = 9. But 53 is already there at 9. We place 75 in table 1 & 53 in table 2 at h2(53) " }, { "code": null, "e": 28149, "s": 28124, "text": "Next: 100. h1(100) = 1. " }, { "code": null, "e": 28243, "s": 28149, "text": "Next: 67. h1(67) = 1. But 100 is already there at 1. We place 67 in table 1 & 100 in table 2 " }, { "code": null, "e": 28417, "s": 28243, "text": "Next: 105. h1(105) = 6. But 50 is already there at 6. We place 105 in table 1 & 50 in table 2 at h2(50) = 4. Now 53 has been displaced. h1(53) = 9. 75 displaced: h2(75) = 6." }, { "code": null, "e": 28437, "s": 28417, "text": "Next: 3. h1(3) = 3." }, { "code": null, "e": 28470, "s": 28437, "text": "Next: 36. h1(36) = 3. h2(3) = 0." }, { "code": null, "e": 28674, "s": 28470, "text": "Next: 39. h1(39) = 6. h2(105) = 9. h1(100) = 1. h2(67) = 6. h1(75) = 9. h2(53) = 4. h1(50) = 6. h2(39) = 3.Here, the new key 39 is displaced later in the recursive calls to place 105, which it displaced." }, { "code": null, "e": 28738, "s": 28674, "text": " Implementation: Below is the implementation of Cuckoo hashing" }, { "code": null, "e": 28742, "s": 28738, "text": "C++" }, { "code": null, "e": 28747, "s": 28742, "text": "Java" }, { "code": null, "e": 28750, "s": 28747, "text": "C#" }, { "code": null, "e": 28761, "s": 28750, "text": "Javascript" }, { "code": "// C++ program to demonstrate working of Cuckoo// hashing.#include<bits/stdc++.h> // upper bound on number of elements in our set#define MAXN 11 // choices for position#define ver 2 // Auxiliary space bounded by a small multiple// of MAXN, minimizing wastageint hashtable[ver][MAXN]; // Array to store possible positions for a keyint pos[ver]; /* function to fill hash table with dummy value * dummy value: INT_MIN * number of hashtables: ver */void initTable(){ for (int j=0; j<MAXN; j++) for (int i=0; i<ver; i++) hashtable[i][j] = INT_MIN;} /* return hashed value for a key * function: ID of hash function according to which key has to hashed * key: item to be hashed */int hash(int function, int key){ switch (function) { case 1: return key%MAXN; case 2: return (key/MAXN)%MAXN; }} /* function to place a key in one of its possible positions * tableID: table in which key has to be placed, also equal to function according to which key must be hashed * cnt: number of times function has already been called in order to place the first input key * n: maximum number of times function can be recursively called before stopping and declaring presence of cycle */void place(int key, int tableID, int cnt, int n){ /* if function has been recursively called max number of times, stop and declare cycle. Rehash. */ if (cnt==n) { printf(\"%d unpositioned\\n\", key); printf(\"Cycle present. REHASH.\\n\"); return; } /* calculate and store possible positions for the key. * check if key already present at any of the positions. If YES, return. */ for (int i=0; i<ver; i++) { pos[i] = hash(i+1, key); if (hashtable[i][pos[i]] == key) return; } /* check if another key is already present at the position for the new key in the table * If YES: place the new key in its position * and place the older key in an alternate position for it in the next table */ if (hashtable[tableID][pos[tableID]]!=INT_MIN) { int dis = hashtable[tableID][pos[tableID]]; hashtable[tableID][pos[tableID]] = key; place(dis, (tableID+1)%ver, cnt+1, n); } else //else: place the new key in its position hashtable[tableID][pos[tableID]] = key;} /* function to print hash table contents */void printTable(){ printf(\"Final hash tables:\\n\"); for (int i=0; i<ver; i++, printf(\"\\n\")) for (int j=0; j<MAXN; j++) (hashtable[i][j]==INT_MIN)? printf(\"- \"): printf(\"%d \", hashtable[i][j]); printf(\"\\n\");} /* function for Cuckoo-hashing keys * keys[]: input array of keys * n: size of input array */void cuckoo(int keys[], int n){ // initialize hash tables to a dummy value (INT-MIN) // indicating empty position initTable(); // start with placing every key at its position in // the first hash table according to first hash // function for (int i=0, cnt=0; i<n; i++, cnt=0) place(keys[i], 0, cnt, n); //print the final hash tables printTable();} /* driver function */int main(){ /* following array doesn't have any cycles and hence all keys will be inserted without any rehashing */ int keys_1[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39}; int n = sizeof(keys_1)/sizeof(int); cuckoo(keys_1, n); /* following array has a cycle and hence we will have to rehash to position every key */ int keys_2[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39, 6}; int m = sizeof(keys_2)/sizeof(int); cuckoo(keys_2, m); return 0;}", "e": 32399, "s": 28761, "text": null }, { "code": "// Java program to demonstrate working of// Cuckoo hashing.import java.util.*; class GFG{ // upper bound on number of elements in our setstatic int MAXN = 11; // choices for positionstatic int ver = 2; // Auxiliary space bounded by a small multiple// of MAXN, minimizing wastagestatic int [][]hashtable = new int[ver][MAXN]; // Array to store possible positions for a keystatic int []pos = new int[ver]; /* function to fill hash table with dummy value* dummy value: INT_MIN* number of hashtables: ver */static void initTable(){ for (int j = 0; j < MAXN; j++) for (int i = 0; i < ver; i++) hashtable[i][j] = Integer.MIN_VALUE;} /* return hashed value for a key* function: ID of hash function according to which key has to hashed* key: item to be hashed */static int hash(int function, int key){ switch (function) { case 1: return key % MAXN; case 2: return (key / MAXN) % MAXN; } return Integer.MIN_VALUE;} /* function to place a key in one of its possible positions* tableID: table in which key has to be placed, also equal to function according to which key must be hashed* cnt: number of times function has already been called in order to place the first input key* n: maximum number of times function can be recursively called before stopping and declaring presence of cycle */static void place(int key, int tableID, int cnt, int n){ /* if function has been recursively called max number of times, stop and declare cycle. Rehash. */ if (cnt == n) { System.out.printf(\"%d unpositioned\\n\", key); System.out.printf(\"Cycle present. REHASH.\\n\"); return; } /* calculate and store possible positions for the key. * check if key already present at any of the positions. If YES, return. */ for (int i = 0; i < ver; i++) { pos[i] = hash(i + 1, key); if (hashtable[i][pos[i]] == key) return; } /* check if another key is already present at the position for the new key in the table * If YES: place the new key in its position * and place the older key in an alternate position for it in the next table */ if (hashtable[tableID][pos[tableID]] != Integer.MIN_VALUE) { int dis = hashtable[tableID][pos[tableID]]; hashtable[tableID][pos[tableID]] = key; place(dis, (tableID + 1) % ver, cnt + 1, n); } else // else: place the new key in its position hashtable[tableID][pos[tableID]] = key;} /* function to print hash table contents */static void printTable(){ System.out.printf(\"Final hash tables:\\n\"); for (int i = 0; i < ver; i++, System.out.printf(\"\\n\")) for (int j = 0; j < MAXN; j++) if(hashtable[i][j] == Integer.MIN_VALUE) System.out.printf(\"- \"); else System.out.printf(\"%d \", hashtable[i][j]); System.out.printf(\"\\n\");} /* function for Cuckoo-hashing keys* keys[]: input array of keys* n: size of input array */static void cuckoo(int keys[], int n){ // initialize hash tables to a dummy value // (INT-MIN) indicating empty position initTable(); // start with placing every key at its position in // the first hash table according to first hash // function for (int i = 0, cnt = 0; i < n; i++, cnt = 0) place(keys[i], 0, cnt, n); // print the final hash tables printTable();} // Driver Codepublic static void main(String[] args){ /* following array doesn't have any cycles and hence all keys will be inserted without any rehashing */ int keys_1[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39}; int n = keys_1.length; cuckoo(keys_1, n); /* following array has a cycle and hence we will have to rehash to position every key */ int keys_2[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39, 6}; int m = keys_2.length; cuckoo(keys_2, m);}} // This code is contributed by Princi Singh", "e": 36332, "s": 32399, "text": null }, { "code": "// C# program to demonstrate working of// Cuckoo hashing.using System; class GFG{ // upper bound on number of// elements in our setstatic int MAXN = 11; // choices for positionstatic int ver = 2; // Auxiliary space bounded by a small// multiple of MAXN, minimizing wastagestatic int [,]hashtable = new int[ver, MAXN]; // Array to store// possible positions for a keystatic int []pos = new int[ver]; /* function to fill hash tablewith dummy value* dummy value: INT_MIN* number of hashtables: ver */static void initTable(){ for (int j = 0; j < MAXN; j++) for (int i = 0; i < ver; i++) hashtable[i, j] = int.MinValue;} /* return hashed value for a key* function: ID of hash functionaccording to which key has to hashed* key: item to be hashed */static int hash(int function, int key){ switch (function) { case 1: return key % MAXN; case 2: return (key / MAXN) % MAXN; } return int.MinValue;} /* function to place a key in one ofits possible positions* tableID: table in which keyhas to be placed, also equal to functionaccording to which key must be hashed* cnt: number of times function has alreadybeen called in order to place the first input key* n: maximum number of times functioncan be recursively called before stopping anddeclaring presence of cycle */static void place(int key, int tableID, int cnt, int n){ /* if function has been recursively called max number of times, stop and declare cycle. Rehash. */ if (cnt == n) { Console.Write(\"{0} unpositioned\\n\", key); Console.Write(\"Cycle present. REHASH.\\n\"); return; } /* calculate and store possible positions * for the key. Check if key already present at any of the positions. If YES, return. */ for (int i = 0; i < ver; i++) { pos[i] = hash(i + 1, key); if (hashtable[i, pos[i]] == key) return; } /* check if another key is already present at the position for the new key in the table * If YES: place the new key in its position * and place the older key in an alternate position for it in the next table */ if (hashtable[tableID, pos[tableID]] != int.MinValue) { int dis = hashtable[tableID, pos[tableID]]; hashtable[tableID, pos[tableID]] = key; place(dis, (tableID + 1) % ver, cnt + 1, n); } else // else: place the new key in its position hashtable[tableID, pos[tableID]] = key;} /* function to print hash table contents */static void printTable(){ Console.Write(\"Final hash tables:\\n\"); for (int i = 0; i < ver; i++, Console.Write(\"\\n\")) for (int j = 0; j < MAXN; j++) if(hashtable[i, j] == int.MinValue) Console.Write(\"- \"); else Console.Write(\"{0} \", hashtable[i, j]); Console.Write(\"\\n\");} /* function for Cuckoo-hashing keys* keys[]: input array of keys* n: size of input array */static void cuckoo(int []keys, int n){ // initialize hash tables to a // dummy value (INT-MIN) // indicating empty position initTable(); // start with placing every key // at its position in the first // hash table according to first // hash function for (int i = 0, cnt = 0; i < n; i++, cnt = 0) place(keys[i], 0, cnt, n); // print the final hash tables printTable();} // Driver Codepublic static void Main(String[] args){ /* following array doesn't have any cycles and hence all keys will be inserted without any rehashing */ int []keys_1 = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39}; int n = keys_1.Length; cuckoo(keys_1, n); /* following array has a cycle and hence we will have to rehash to position every key */ int []keys_2 = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39, 6}; int m = keys_2.Length; cuckoo(keys_2, m);}} // This code is contributed by PrinciRaj1992", "e": 40297, "s": 36332, "text": null }, { "code": "<script> // Javascript program to demonstrate working of// Cuckoo hashing. // upper bound on number of elements in our setlet MAXN = 11; // choices for positionlet ver = 2; // Auxiliary space bounded by a small multiple// of MAXN, minimizing wastagelet hashtable = new Array(ver);for (var i = 0; i < hashtable.length; i++) { hashtable[i] = new Array(2);} // Array to store possible positions for a keylet pos = Array(ver).fill(0); /* function to fill hash table with dummy value* dummy value: let_MIN* number of hashtables: ver */function initTable(){ for (let j = 0; j < MAXN; j++) for (let i = 0; i < ver; i++) hashtable[i][j] = Number.MIN_VALUE;} /* return hashed value for a key* function: ID of hash function according to which key has to hashed* key: item to be hashed */function hash(function, key){ switch (function) { case 1: return key % MAXN; case 2: return (Math.floor(key / MAXN)) % MAXN; } return Number.MIN_VALUE;} /* function to place a key in one of its possible positions* tableID: table in which key has to be placed, also equal to function according to which key must be hashed* cnt: number of times function has already been called in order to place the first input key* n: maximum number of times function can be recursively called before stopping and declaring presence of cycle */function place(key, tableID, cnt, n){ /* if function has been recursively called max number of times, stop and declare cycle. Rehash. */ if (cnt == n) { document.write(key + \" unpositioned\" + \"<br/>\"); document.write(\"Cycle present. REHASH.\" + \"<br/>\"); return; } /* calculate and store possible positions for the key. * check if key already present at any of the positions. If YES, return. */ for (let i = 0; i < ver; i++) { pos[i] = hash(i + 1, key); if (hashtable[i][pos[i]] == key) return; } /* check if another key is already present at the position for the new key in the table * If YES: place the new key in its position * and place the older key in an alternate position for it in the next table */ if (hashtable[tableID][pos[tableID]] != Number.MIN_VALUE) { let dis = hashtable[tableID][pos[tableID]]; hashtable[tableID][pos[tableID]] = key; place(dis, (tableID + 1) % ver, cnt + 1, n); } else // else: place the new key in its position hashtable[tableID][pos[tableID]] = key;} /* function to print hash table contents */function printTable(){ document.write(\"Final hash tables:\" + \"<br/>\"); for (let i = 0; i < ver; i++, document.write(\"<br/>\")) for (let j = 0; j < MAXN; j++) if(hashtable[i][j] == Number.MIN_VALUE) document.write(\"- \"); else document.write(hashtable[i][j] + \" \"); document.write(\"<br/>\");} /* function for Cuckoo-hashing keys* keys[]: input array of keys* n: size of input array */function cuckoo(keys, n){ // initialize hash tables to a dummy value // (let-MIN) indicating empty position initTable(); // start with placing every key at its position in // the first hash table according to first hash // function for (let i = 0, cnt = 0; i < n; i++, cnt = 0) place(keys[i], 0, cnt, n); // print the final hash tables printTable();} // Driver program /* following array doesn't have any cycles and hence all keys will be inserted without any rehashing */ let keys_1 = [20, 50, 53, 75, 100, 67, 105, 3, 36, 39]; let n = keys_1.length; cuckoo(keys_1, n); /* following array has a cycle and hence we will have to rehash to position every key */ let keys_2 = [20, 50, 53, 75, 100, 67, 105, 3, 36, 39, 6]; let m = keys_2.length; cuckoo(keys_2, m); </script>", "e": 44206, "s": 40297, "text": null }, { "code": null, "e": 44216, "s": 44206, "text": "Output: " }, { "code": null, "e": 44411, "s": 44216, "text": "Final hash tables:\n\n- 100 - 36 - - 50 - - 75 - \n\n3 20 - 39 53 - 67 - - 105 - \n105 unpositioned\n\nCycle present. REHASH.\n\nFinal hash tables:\n\n- 67 - 3 - - 39 - - 53 - \n\n6 20 - 36 50 - 75 - - 100 -" }, { "code": null, "e": 44737, "s": 44411, "text": "Generalizations of cuckoo hashing that use more than 2 alternative hash functions can be expected to utilize a larger part of the capacity of the hash table efficiently while sacrificing some lookup and insertion speed. Example: if we use 3 hash functions, it’s safe to load 91% and still be operating within expected bounds." }, { "code": null, "e": 45129, "s": 44737, "text": "This article is contributed by Yash Varyani. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 45142, "s": 45129, "text": "princi singh" }, { "code": null, "e": 45156, "s": 45142, "text": "princiraj1992" }, { "code": null, "e": 45165, "s": 45156, "text": "target_2" }, { "code": null, "e": 45178, "s": 45165, "text": "ankita_saini" }, { "code": null, "e": 45197, "s": 45178, "text": "surindertarika1234" }, { "code": null, "e": 45202, "s": 45197, "text": "Hash" }, { "code": null, "e": 45207, "s": 45202, "text": "Hash" }, { "code": null, "e": 45305, "s": 45207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45341, "s": 45305, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 45375, "s": 45341, "text": "Most frequent element in an array" }, { "code": null, "e": 45401, "s": 45375, "text": "Sort string of characters" }, { "code": null, "e": 45440, "s": 45401, "text": "Counting frequencies of array elements" }, { "code": null, "e": 45474, "s": 45440, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 45489, "s": 45474, "text": "Double Hashing" }, { "code": null, "e": 45527, "s": 45489, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 45556, "s": 45527, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 45610, "s": 45556, "text": "Return maximum occurring character in an input string" } ]
JSF - h:inputTextarea
The h:inputText tag renders an HTML input element of the type "text". <h:inputTextarea row = "10" col = "10" value = "Hello World! Everything is fine!" readonly = "true"/> <textarea name = "j_idt18:j_idt20" readonly = "readonly"> Hello World! Everything is fine!</textarea> id Identifier for a component binding Reference to the component that can be used in a backing bean rendered A boolean; false suppresses rendering styleClass Cascading stylesheet (CSS) class name value A component’s value, typically a value binding valueChangeListener A method binding to a method that responds to value changes converter Converter class name validator Class name of a validator that’s created and attached to a component required A boolean; if true, requires a value to be entered in the associated field accesskey A key, typically combined with a system-defined metakey, that gives focus to an element accept Comma-separated list of content types for a form accept-charset Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset. cols Number of columns border Pixel value for an element’s border width charset Character encoding for a linked resource coords Coordinates for an element whose shape is a rectangle, circle, or polygon dir Direction for text. Valid values are ltr (left to right) and rtl (right to left). disabled Disabled state of an input element or button hreflang Base language of a resource specified with the href attribute; hreflang may only be used with href. lang Base language of an element’s attributes and text rows Number of rows readonly Read-only state of an input field; the text can be selected in a readonly field but not edited style Inline style information tabindex Numerical value specifying a tab index target The name of a frame in which a document is opened title A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value type Type of a link; for example, stylesheet width Width of an element onblur Element loses focus onchange Element’s value changes onclick Mouse button is clicked over the element ondblclick Mouse button is double-clicked over the element onfocus Element receives focus onkeydown Key is pressed onkeypress Key is pressed and subsequently released onkeyup Key is released onmousedown Mouse button is pressed over the element onmousemove Mouse moves over the element onmouseout Mouse leaves the element’s area onmouseover Mouse moves onto an element onmouseup Mouse button is released onreset Form is reset onselect Text is selected in an input field immediate Process validation early in the life cycle Let us create a test JSF application to test the above tag. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF Tutorial!</title> </head> <body> <h2>h:inputTextArea example</h2> <hr /> <h:form> <h3>Read-Only input text area</h3> <h:inputTextarea row = "10" col = "10" value = "Hello World! <br/> Everything is fine!" readonly = "true"/> <h3>Normal input text area</h3> <h:inputTextarea value = "Hello World! <br/> Everything is fine!"/> </h:form> </body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2022, "s": 1952, "text": "The h:inputText tag renders an HTML input element of the type \"text\"." }, { "code": null, "e": 2130, "s": 2022, "text": "<h:inputTextarea row = \"10\" col = \"10\" value = \"Hello World! \n Everything is fine!\" readonly = \"true\"/>" }, { "code": null, "e": 2238, "s": 2130, "text": "<textarea name = \"j_idt18:j_idt20\" readonly = \"readonly\"> \n Hello World! Everything is fine!</textarea> \n" }, { "code": null, "e": 2241, "s": 2238, "text": "id" }, { "code": null, "e": 2268, "s": 2241, "text": "Identifier for a component" }, { "code": null, "e": 2276, "s": 2268, "text": "binding" }, { "code": null, "e": 2338, "s": 2276, "text": "Reference to the component that can be used in a backing bean" }, { "code": null, "e": 2347, "s": 2338, "text": "rendered" }, { "code": null, "e": 2385, "s": 2347, "text": "A boolean; false suppresses rendering" }, { "code": null, "e": 2396, "s": 2385, "text": "styleClass" }, { "code": null, "e": 2434, "s": 2396, "text": "Cascading stylesheet (CSS) class name" }, { "code": null, "e": 2440, "s": 2434, "text": "value" }, { "code": null, "e": 2487, "s": 2440, "text": "A component’s value, typically a value binding" }, { "code": null, "e": 2507, "s": 2487, "text": "valueChangeListener" }, { "code": null, "e": 2567, "s": 2507, "text": "A method binding to a method that responds to value changes" }, { "code": null, "e": 2577, "s": 2567, "text": "converter" }, { "code": null, "e": 2598, "s": 2577, "text": "Converter class name" }, { "code": null, "e": 2608, "s": 2598, "text": "validator" }, { "code": null, "e": 2677, "s": 2608, "text": "Class name of a validator that’s created and attached to a component" }, { "code": null, "e": 2686, "s": 2677, "text": "required" }, { "code": null, "e": 2761, "s": 2686, "text": "A boolean; if true, requires a value to be entered in the associated field" }, { "code": null, "e": 2771, "s": 2761, "text": "accesskey" }, { "code": null, "e": 2859, "s": 2771, "text": "A key, typically combined with a system-defined metakey, that gives focus to an element" }, { "code": null, "e": 2866, "s": 2859, "text": "accept" }, { "code": null, "e": 2915, "s": 2866, "text": "Comma-separated list of content types for a form" }, { "code": null, "e": 2930, "s": 2915, "text": "accept-charset" }, { "code": null, "e": 3087, "s": 2930, "text": "Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset." }, { "code": null, "e": 3092, "s": 3087, "text": "cols" }, { "code": null, "e": 3110, "s": 3092, "text": "Number of columns" }, { "code": null, "e": 3117, "s": 3110, "text": "border" }, { "code": null, "e": 3159, "s": 3117, "text": "Pixel value for an element’s border width" }, { "code": null, "e": 3167, "s": 3159, "text": "charset" }, { "code": null, "e": 3208, "s": 3167, "text": "Character encoding for a linked resource" }, { "code": null, "e": 3215, "s": 3208, "text": "coords" }, { "code": null, "e": 3289, "s": 3215, "text": "Coordinates for an element whose shape is a rectangle, circle, or polygon" }, { "code": null, "e": 3293, "s": 3289, "text": "dir" }, { "code": null, "e": 3375, "s": 3293, "text": "Direction for text. Valid values are ltr (left to right) and rtl (right to left)." }, { "code": null, "e": 3384, "s": 3375, "text": "disabled" }, { "code": null, "e": 3429, "s": 3384, "text": "Disabled state of an input element or button" }, { "code": null, "e": 3438, "s": 3429, "text": "hreflang" }, { "code": null, "e": 3538, "s": 3438, "text": "Base language of a resource specified with the href attribute; hreflang may only be used with href." }, { "code": null, "e": 3543, "s": 3538, "text": "lang" }, { "code": null, "e": 3593, "s": 3543, "text": "Base language of an element’s attributes and text" }, { "code": null, "e": 3598, "s": 3593, "text": "rows" }, { "code": null, "e": 3613, "s": 3598, "text": "Number of rows" }, { "code": null, "e": 3622, "s": 3613, "text": "readonly" }, { "code": null, "e": 3717, "s": 3622, "text": "Read-only state of an input field; the text can be selected in a readonly field but not edited" }, { "code": null, "e": 3723, "s": 3717, "text": "style" }, { "code": null, "e": 3748, "s": 3723, "text": "Inline style information" }, { "code": null, "e": 3757, "s": 3748, "text": "tabindex" }, { "code": null, "e": 3796, "s": 3757, "text": "Numerical value specifying a tab index" }, { "code": null, "e": 3803, "s": 3796, "text": "target" }, { "code": null, "e": 3853, "s": 3803, "text": "The name of a frame in which a document is opened" }, { "code": null, "e": 3859, "s": 3853, "text": "title" }, { "code": null, "e": 3983, "s": 3859, "text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value" }, { "code": null, "e": 3988, "s": 3983, "text": "type" }, { "code": null, "e": 4028, "s": 3988, "text": "Type of a link; for example, stylesheet" }, { "code": null, "e": 4034, "s": 4028, "text": "width" }, { "code": null, "e": 4054, "s": 4034, "text": "Width of an element" }, { "code": null, "e": 4061, "s": 4054, "text": "onblur" }, { "code": null, "e": 4081, "s": 4061, "text": "Element loses focus" }, { "code": null, "e": 4090, "s": 4081, "text": "onchange" }, { "code": null, "e": 4114, "s": 4090, "text": "Element’s value changes" }, { "code": null, "e": 4122, "s": 4114, "text": "onclick" }, { "code": null, "e": 4163, "s": 4122, "text": "Mouse button is clicked over the element" }, { "code": null, "e": 4174, "s": 4163, "text": "ondblclick" }, { "code": null, "e": 4222, "s": 4174, "text": "Mouse button is double-clicked over the element" }, { "code": null, "e": 4230, "s": 4222, "text": "onfocus" }, { "code": null, "e": 4253, "s": 4230, "text": "Element receives focus" }, { "code": null, "e": 4263, "s": 4253, "text": "onkeydown" }, { "code": null, "e": 4278, "s": 4263, "text": "Key is pressed" }, { "code": null, "e": 4289, "s": 4278, "text": "onkeypress" }, { "code": null, "e": 4330, "s": 4289, "text": "Key is pressed and subsequently released" }, { "code": null, "e": 4338, "s": 4330, "text": "onkeyup" }, { "code": null, "e": 4354, "s": 4338, "text": "Key is released" }, { "code": null, "e": 4366, "s": 4354, "text": "onmousedown" }, { "code": null, "e": 4407, "s": 4366, "text": "Mouse button is pressed over the element" }, { "code": null, "e": 4419, "s": 4407, "text": "onmousemove" }, { "code": null, "e": 4448, "s": 4419, "text": "Mouse moves over the element" }, { "code": null, "e": 4459, "s": 4448, "text": "onmouseout" }, { "code": null, "e": 4491, "s": 4459, "text": "Mouse leaves the element’s area" }, { "code": null, "e": 4503, "s": 4491, "text": "onmouseover" }, { "code": null, "e": 4531, "s": 4503, "text": "Mouse moves onto an element" }, { "code": null, "e": 4541, "s": 4531, "text": "onmouseup" }, { "code": null, "e": 4566, "s": 4541, "text": "Mouse button is released" }, { "code": null, "e": 4574, "s": 4566, "text": "onreset" }, { "code": null, "e": 4588, "s": 4574, "text": "Form is reset" }, { "code": null, "e": 4597, "s": 4588, "text": "onselect" }, { "code": null, "e": 4632, "s": 4597, "text": "Text is selected in an input field" }, { "code": null, "e": 4642, "s": 4632, "text": "immediate" }, { "code": null, "e": 4685, "s": 4642, "text": "Process validation early in the life cycle" }, { "code": null, "e": 4745, "s": 4685, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 5393, "s": 4745, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <body>\n <h2>h:inputTextArea example</h2>\n <hr />\n \n <h:form>\n <h3>Read-Only input text area</h3>\n <h:inputTextarea row = \"10\" col = \"10\" value = \"Hello World! \n <br/> Everything is fine!\" readonly = \"true\"/>\n <h3>Normal input text area</h3>\n <h:inputTextarea value = \"Hello World! <br/> Everything is fine!\"/>\n </h:form> \n \n </body>\n</html>" }, { "code": null, "e": 5609, "s": 5393, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 5644, "s": 5609, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5659, "s": 5644, "text": " Chaand Sheikh" }, { "code": null, "e": 5666, "s": 5659, "text": " Print" }, { "code": null, "e": 5677, "s": 5666, "text": " Add Notes" } ]
EMOJIFY- Machine Learning Web App using Flask + Containerization +Deployment on AWS | by Sriram TM | Towards Data Science
In this tutorial, I will share my learning on building a simple end to end Machine Learning web app using Flask and later deploying it on AWS. The purpose of an ML model is well served only if it can be used interactively through a web app by the users. The traditional Jupyter notebooks only provide an interactive console and are not much useful for leveraging it to a web app. Flask is a micro-framework written in Python which can help us in quickly getting started in building the app. We will train the data from Deep Moji dataset using Long Short Term Memory(LSTM) units in Keras. We will then save the final model as a HDF5 file and use it later for prediction purpose. The final application will be working similarly like the one mentioned in this link. Let’s dive deeper on how the whole web app can be built and deployed in AWS using a Docker container. The code for this project can be found in my Github repo. The Data The Data 2. Data Extraction and Processing 3. Embedding Layer 4. Bi-Directional RNN Model 5. Training the model 6. Building the Flask App 7. Containerization using Docker containers 8. Pushing the Docker image to AWS ECR 9. Deploying the Flask app on AWS EC2 We will be using the Deep Moji dataset and in particular the PsychExp dataset for building the model. The dataset consists of 7840 samples, in which each line contains a text message and the labels which are encoded as a One Hot vector. The labels belong to one of these 7 classes β€” [Joy, Fear, Anger, Sadness, Disgust, Shame, Guilt]. An example line in the dataset looks like this: [ 1. 0. 0. 0. 0. 0. 0.] I am very happy today. In this function we are extracting the texts and labels from the pickle file and then writing them to a text file. In read text file function we are returning a list which contains the text messages and labels. Then we are separating out the messages and labels into separate lists. For any ML model, we have to feed the data in a numerical format so that they can be processed. Similarly, in order to classify our input text among the 7 classes, we have to convert our input sentence into a word vector representation. We will be using the pre-trained 50-dimensional Glove word embeddings for this purpose. The above β€˜read_glove_vector’ function returns a list of indices given their words, words given their indices and the corresponding 50-dimensional representation for each word. Before building the embedding layer let us know why an Embedding layer is used. Let us consider that we have a text corpus of 1000 words. The one hot encoding of each word in the text will be a vector having 999 zeros and 1 non zero value. These vectors are very sparse and are not very suitable for large datasets. In word embeddings, the words are represented by dense vectors where each vector is the projection of a word in continuous vector space. So, instead of projecting the words in a higher dimension, word embeddings help in projecting them into a much lower dimension. Moreover, word embeddings help us in capturing the relationship between words which are otherwise difficult to capture using one hot encoded vectors. Let us see how we implement this embedding layer for our app: Here the first argument to the embedding layer is the total number of words in the Glove word embeddings and the second argument is the dimension in which each word is represented in the vector space. Bi-Directional RNN’s have two networks- one which trains information in the forward direction and the other in the reverse direction. Hence these models have access to both past as well as the future data unlike the standard LSTM’s which have access to only the past data. Let us see its implementation in our app using Keras. Here we are building a deep recurrent neural network which contains a Bi-Directional LSTM with Batch Normalization and Dropout. Softmax activation is used here to get the probability distribution across the 7 classes. This is a simplified image showing the architecture of our whole LSTM model. We will be using Categorical Cross Entropy as our loss function since we will be classifying the output among the 7 classes. We will be trying to minimize this loss in each epoch so that it performs well on the test data. Adam optimizer is used which helps us in speeding up the training process. Accuracy is the performance metric that we use here to evaluate the model. X_train = pad_sequences(train_tokenized, maxlen = maxlen)X_test = pad_sequences(test_tokenized, maxlen = maxlen)model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.fit(X_train, np.array(y_train), epochs = 30, batch_size = 32, shuffle=True) We will be then using the save_model of Tensorflow to save the Keras model so that we can load it later to give out predictions. An accuracy of 86% was achieved after training for 30 epochs. model.save('emoji_model.h5')model = load_model('emoji_model.h5') First we have to install flask using the command- pip install flask. Then create a file called application.py which is the main backend file for our application. First, we have to instantiate an object of the Flask class. We are then loading the already trained model using the load_model function. We have also saved a pickle file for the text tokenizer so that it can be used for tokenizing the future text inputs. There are two routes- predict and update. The β€˜predict’ route receives the values entered in the input text field and we tokenize the text using the tokenizer object. We make predictions for the input text using the loaded model and then return the response back in JSON format. The β€˜update’ route is used for updating the predicted values if they are incorrect in order to fine tune the model for new inputs. Although this might not be the correct way of updating the model in large scale systems, I wanted to try out how model retraining works. To return back the correct Emoji responses for the prediction, the following Javascript file is created. Another Javascript file can help us in the update action by choosing the values from the dropdown and send a POST request to the β€˜update’ route to update the values. I’m not very great in building the UI and hence the frontend part can very well be changed according to our needs. We will be making our app to run on host 0.0.0.0 and port 5000. We will configure this in the Docker file also. This is how the final application after running in our localhost looks like. Docker is an open source application that allows users to create, manage, deploy applications using containers. Applications that are run using Docker reside in an environment of their own and house dependencies that are needed for running the application. Docker can be installed on Mac using the following link. After installing docker move to our application folder in the terminal. Create a Docker file which instructs the docker to install the dependencies and perform other commands while building the docker image. The above Dockerfile instructs the docker to install python from the Docker hub and then create an β€˜app’ directory to copy all the contents of our web app. It then installs all the packages mentioned in the requirements.txt file. Then the port 5000 is exposed to access the application from outside the container. By default, the application.py file is run using the CMD command. We will name the docker image β€˜flaskapp’. Now we have to build the docker image using the following command. docker build -t flaskapp:latest . The β€˜.’ at the end of this command copies all the files in the current directory to build the image. We will then run the docker container at port 5000 using the docker image that is created above. The command is as follows: docker run -p 5000:5000 flaskapp Check if the application is accessible outside the container by launching the app on port 5000 in the browser. I assume that there is already an account created in AWS. If not, anyone can get started for free by following this link. We have to install the awscli in our desktop by using pip install awscli --upgrade --user in order to perform actions in AWS directly from the terminal. We have to configure our AWS credentials using the command aws configure from our terminal where we enter our access key ID, secret access key, default region, and output format. We will be using the AWS Elastic Container Registry to store and deploy our docker container images. We have to first create a repository in AWS ECR in order to store Docker images. This is done using the following command: aws ecr create-repository --repository-name ml_flask_app Then to get permission to access the AWS ECR we enter the following command- $(aws ecr get-login --region region_name --no-include-email) Then we tag our flaskapp container in local with the repository that is created. Here account_id and region name differs for each user. docker tag flaskapp:latest aws_account_id.dkr.ecr.region_name.amazonaws.com/ Then we have to push our local docker image to the repository created in AWS ECR. docker push aws_account_id.dkr.ecr.region_name.amazonaws.com/ml_flask_app After pushing the image to AWS ECR, we have to create an EC2 instance in which we can serve the web app. AWS offers many instances in the free tier range and we can make use of that. We will be launching a Linux machine with most of the configurations which are set by default and the security groups alone which are changed as follows: SSH -> Only from our IP and Custom TCP -> Port 5000. These security group rules are necessary for our web app to run. Once the instance is launched and is running, we can ssh into the instance by entering the following command in the terminal in the same folder in which our β€˜pem’ file is present. ssh -i "test_ml_app.pem" ec2-user@ec2-12-345-67-89.us-east-1.compute.amazonaws.com Once we are logged into the instance we can install docker by using the following command and start it. sudo yum install -y dockersudo docker service start We have to configure the AWS credentials as we did before by entering aws configure command again. Then enter the following commands so that the ec2 user is added to perform docker commands in Linux machine. sudo groupadd dockersudo gpasswd -a ${USER} dockersudo service docker restart Then exit the instance and ssh again into the instance. Run the following commands to pull the docker image from AWS ECR and then run the docker container in the Linux machine. docker pull account_id.dkr.ecr.region_name.amazonaws.com/ml_flask_app_:latestdocker run -p 5000:5000 account_id.dkr.ecr.region_name.amazonaws.com/ml_flask_app Get the public IP of the instance from the instance details page and add port 5000 while launching it in the browser. Voila!!! The app is finally up and running on AWS. Let us check for some inputs where wrong predictions are given. Now we shall update the model with the label as β€˜Sad’ for the above input. There it is!! The model has updated its response for the new input text and will try to improve its predictions for future inputs. Since this is my first blog, I request you folks to share your views about the content and quality of this blog. If there are any doubts, I am more than happy to help. You can connect with me on Linkedin @ Sriram Muralishankar . Deep Moji Dataset-https://github.com/bfelbo/DeepMoji/tree/master/dataCoursera Sequence Models Tutorial- https://github.com/Kulbear/deep-learning-coursera/blob/master/Sequence%20Models/Emojify%20-%20v2.ipynbAWS Documentation- https://docs.aws.amazon.com/Docker Documentation- https://docs.docker.com/ Deep Moji Dataset-https://github.com/bfelbo/DeepMoji/tree/master/data Coursera Sequence Models Tutorial- https://github.com/Kulbear/deep-learning-coursera/blob/master/Sequence%20Models/Emojify%20-%20v2.ipynb AWS Documentation- https://docs.aws.amazon.com/ Docker Documentation- https://docs.docker.com/
[ { "code": null, "e": 427, "s": 47, "text": "In this tutorial, I will share my learning on building a simple end to end Machine Learning web app using Flask and later deploying it on AWS. The purpose of an ML model is well served only if it can be used interactively through a web app by the users. The traditional Jupyter notebooks only provide an interactive console and are not much useful for leveraging it to a web app." }, { "code": null, "e": 970, "s": 427, "text": "Flask is a micro-framework written in Python which can help us in quickly getting started in building the app. We will train the data from Deep Moji dataset using Long Short Term Memory(LSTM) units in Keras. We will then save the final model as a HDF5 file and use it later for prediction purpose. The final application will be working similarly like the one mentioned in this link. Let’s dive deeper on how the whole web app can be built and deployed in AWS using a Docker container. The code for this project can be found in my Github repo." }, { "code": null, "e": 979, "s": 970, "text": "The Data" }, { "code": null, "e": 988, "s": 979, "text": "The Data" }, { "code": null, "e": 1022, "s": 988, "text": "2. Data Extraction and Processing" }, { "code": null, "e": 1041, "s": 1022, "text": "3. Embedding Layer" }, { "code": null, "e": 1069, "s": 1041, "text": "4. Bi-Directional RNN Model" }, { "code": null, "e": 1091, "s": 1069, "text": "5. Training the model" }, { "code": null, "e": 1117, "s": 1091, "text": "6. Building the Flask App" }, { "code": null, "e": 1161, "s": 1117, "text": "7. Containerization using Docker containers" }, { "code": null, "e": 1200, "s": 1161, "text": "8. Pushing the Docker image to AWS ECR" }, { "code": null, "e": 1238, "s": 1200, "text": "9. Deploying the Flask app on AWS EC2" }, { "code": null, "e": 1668, "s": 1238, "text": "We will be using the Deep Moji dataset and in particular the PsychExp dataset for building the model. The dataset consists of 7840 samples, in which each line contains a text message and the labels which are encoded as a One Hot vector. The labels belong to one of these 7 classes β€” [Joy, Fear, Anger, Sadness, Disgust, Shame, Guilt]. An example line in the dataset looks like this: [ 1. 0. 0. 0. 0. 0. 0.] I am very happy today." }, { "code": null, "e": 1783, "s": 1668, "text": "In this function we are extracting the texts and labels from the pickle file and then writing them to a text file." }, { "code": null, "e": 1951, "s": 1783, "text": "In read text file function we are returning a list which contains the text messages and labels. Then we are separating out the messages and labels into separate lists." }, { "code": null, "e": 2276, "s": 1951, "text": "For any ML model, we have to feed the data in a numerical format so that they can be processed. Similarly, in order to classify our input text among the 7 classes, we have to convert our input sentence into a word vector representation. We will be using the pre-trained 50-dimensional Glove word embeddings for this purpose." }, { "code": null, "e": 2453, "s": 2276, "text": "The above β€˜read_glove_vector’ function returns a list of indices given their words, words given their indices and the corresponding 50-dimensional representation for each word." }, { "code": null, "e": 3246, "s": 2453, "text": "Before building the embedding layer let us know why an Embedding layer is used. Let us consider that we have a text corpus of 1000 words. The one hot encoding of each word in the text will be a vector having 999 zeros and 1 non zero value. These vectors are very sparse and are not very suitable for large datasets. In word embeddings, the words are represented by dense vectors where each vector is the projection of a word in continuous vector space. So, instead of projecting the words in a higher dimension, word embeddings help in projecting them into a much lower dimension. Moreover, word embeddings help us in capturing the relationship between words which are otherwise difficult to capture using one hot encoded vectors. Let us see how we implement this embedding layer for our app:" }, { "code": null, "e": 3447, "s": 3246, "text": "Here the first argument to the embedding layer is the total number of words in the Glove word embeddings and the second argument is the dimension in which each word is represented in the vector space." }, { "code": null, "e": 3720, "s": 3447, "text": "Bi-Directional RNN’s have two networks- one which trains information in the forward direction and the other in the reverse direction. Hence these models have access to both past as well as the future data unlike the standard LSTM’s which have access to only the past data." }, { "code": null, "e": 3774, "s": 3720, "text": "Let us see its implementation in our app using Keras." }, { "code": null, "e": 3992, "s": 3774, "text": "Here we are building a deep recurrent neural network which contains a Bi-Directional LSTM with Batch Normalization and Dropout. Softmax activation is used here to get the probability distribution across the 7 classes." }, { "code": null, "e": 4069, "s": 3992, "text": "This is a simplified image showing the architecture of our whole LSTM model." }, { "code": null, "e": 4441, "s": 4069, "text": "We will be using Categorical Cross Entropy as our loss function since we will be classifying the output among the 7 classes. We will be trying to minimize this loss in each epoch so that it performs well on the test data. Adam optimizer is used which helps us in speeding up the training process. Accuracy is the performance metric that we use here to evaluate the model." }, { "code": null, "e": 4721, "s": 4441, "text": "X_train = pad_sequences(train_tokenized, maxlen = maxlen)X_test = pad_sequences(test_tokenized, maxlen = maxlen)model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.fit(X_train, np.array(y_train), epochs = 30, batch_size = 32, shuffle=True)" }, { "code": null, "e": 4912, "s": 4721, "text": "We will be then using the save_model of Tensorflow to save the Keras model so that we can load it later to give out predictions. An accuracy of 86% was achieved after training for 30 epochs." }, { "code": null, "e": 4977, "s": 4912, "text": "model.save('emoji_model.h5')model = load_model('emoji_model.h5')" }, { "code": null, "e": 5139, "s": 4977, "text": "First we have to install flask using the command- pip install flask. Then create a file called application.py which is the main backend file for our application." }, { "code": null, "e": 6046, "s": 5139, "text": "First, we have to instantiate an object of the Flask class. We are then loading the already trained model using the load_model function. We have also saved a pickle file for the text tokenizer so that it can be used for tokenizing the future text inputs. There are two routes- predict and update. The β€˜predict’ route receives the values entered in the input text field and we tokenize the text using the tokenizer object. We make predictions for the input text using the loaded model and then return the response back in JSON format. The β€˜update’ route is used for updating the predicted values if they are incorrect in order to fine tune the model for new inputs. Although this might not be the correct way of updating the model in large scale systems, I wanted to try out how model retraining works. To return back the correct Emoji responses for the prediction, the following Javascript file is created." }, { "code": null, "e": 6327, "s": 6046, "text": "Another Javascript file can help us in the update action by choosing the values from the dropdown and send a POST request to the β€˜update’ route to update the values. I’m not very great in building the UI and hence the frontend part can very well be changed according to our needs." }, { "code": null, "e": 6516, "s": 6327, "text": "We will be making our app to run on host 0.0.0.0 and port 5000. We will configure this in the Docker file also. This is how the final application after running in our localhost looks like." }, { "code": null, "e": 7038, "s": 6516, "text": "Docker is an open source application that allows users to create, manage, deploy applications using containers. Applications that are run using Docker reside in an environment of their own and house dependencies that are needed for running the application. Docker can be installed on Mac using the following link. After installing docker move to our application folder in the terminal. Create a Docker file which instructs the docker to install the dependencies and perform other commands while building the docker image." }, { "code": null, "e": 7527, "s": 7038, "text": "The above Dockerfile instructs the docker to install python from the Docker hub and then create an β€˜app’ directory to copy all the contents of our web app. It then installs all the packages mentioned in the requirements.txt file. Then the port 5000 is exposed to access the application from outside the container. By default, the application.py file is run using the CMD command. We will name the docker image β€˜flaskapp’. Now we have to build the docker image using the following command." }, { "code": null, "e": 7561, "s": 7527, "text": "docker build -t flaskapp:latest ." }, { "code": null, "e": 7786, "s": 7561, "text": "The β€˜.’ at the end of this command copies all the files in the current directory to build the image. We will then run the docker container at port 5000 using the docker image that is created above. The command is as follows:" }, { "code": null, "e": 7819, "s": 7786, "text": "docker run -p 5000:5000 flaskapp" }, { "code": null, "e": 7930, "s": 7819, "text": "Check if the application is accessible outside the container by launching the app on port 5000 in the browser." }, { "code": null, "e": 8384, "s": 7930, "text": "I assume that there is already an account created in AWS. If not, anyone can get started for free by following this link. We have to install the awscli in our desktop by using pip install awscli --upgrade --user in order to perform actions in AWS directly from the terminal. We have to configure our AWS credentials using the command aws configure from our terminal where we enter our access key ID, secret access key, default region, and output format." }, { "code": null, "e": 8608, "s": 8384, "text": "We will be using the AWS Elastic Container Registry to store and deploy our docker container images. We have to first create a repository in AWS ECR in order to store Docker images. This is done using the following command:" }, { "code": null, "e": 8665, "s": 8608, "text": "aws ecr create-repository --repository-name ml_flask_app" }, { "code": null, "e": 8742, "s": 8665, "text": "Then to get permission to access the AWS ECR we enter the following command-" }, { "code": null, "e": 8803, "s": 8742, "text": "$(aws ecr get-login --region region_name --no-include-email)" }, { "code": null, "e": 8939, "s": 8803, "text": "Then we tag our flaskapp container in local with the repository that is created. Here account_id and region name differs for each user." }, { "code": null, "e": 9016, "s": 8939, "text": "docker tag flaskapp:latest aws_account_id.dkr.ecr.region_name.amazonaws.com/" }, { "code": null, "e": 9098, "s": 9016, "text": "Then we have to push our local docker image to the repository created in AWS ECR." }, { "code": null, "e": 9172, "s": 9098, "text": "docker push aws_account_id.dkr.ecr.region_name.amazonaws.com/ml_flask_app" }, { "code": null, "e": 9509, "s": 9172, "text": "After pushing the image to AWS ECR, we have to create an EC2 instance in which we can serve the web app. AWS offers many instances in the free tier range and we can make use of that. We will be launching a Linux machine with most of the configurations which are set by default and the security groups alone which are changed as follows:" }, { "code": null, "e": 9537, "s": 9509, "text": "SSH -> Only from our IP and" }, { "code": null, "e": 9562, "s": 9537, "text": "Custom TCP -> Port 5000." }, { "code": null, "e": 9807, "s": 9562, "text": "These security group rules are necessary for our web app to run. Once the instance is launched and is running, we can ssh into the instance by entering the following command in the terminal in the same folder in which our β€˜pem’ file is present." }, { "code": null, "e": 9890, "s": 9807, "text": "ssh -i \"test_ml_app.pem\" ec2-user@ec2-12-345-67-89.us-east-1.compute.amazonaws.com" }, { "code": null, "e": 9994, "s": 9890, "text": "Once we are logged into the instance we can install docker by using the following command and start it." }, { "code": null, "e": 10046, "s": 9994, "text": "sudo yum install -y dockersudo docker service start" }, { "code": null, "e": 10254, "s": 10046, "text": "We have to configure the AWS credentials as we did before by entering aws configure command again. Then enter the following commands so that the ec2 user is added to perform docker commands in Linux machine." }, { "code": null, "e": 10332, "s": 10254, "text": "sudo groupadd dockersudo gpasswd -a ${USER} dockersudo service docker restart" }, { "code": null, "e": 10509, "s": 10332, "text": "Then exit the instance and ssh again into the instance. Run the following commands to pull the docker image from AWS ECR and then run the docker container in the Linux machine." }, { "code": null, "e": 10668, "s": 10509, "text": "docker pull account_id.dkr.ecr.region_name.amazonaws.com/ml_flask_app_:latestdocker run -p 5000:5000 account_id.dkr.ecr.region_name.amazonaws.com/ml_flask_app" }, { "code": null, "e": 10837, "s": 10668, "text": "Get the public IP of the instance from the instance details page and add port 5000 while launching it in the browser. Voila!!! The app is finally up and running on AWS." }, { "code": null, "e": 10901, "s": 10837, "text": "Let us check for some inputs where wrong predictions are given." }, { "code": null, "e": 10976, "s": 10901, "text": "Now we shall update the model with the label as β€˜Sad’ for the above input." }, { "code": null, "e": 11107, "s": 10976, "text": "There it is!! The model has updated its response for the new input text and will try to improve its predictions for future inputs." }, { "code": null, "e": 11336, "s": 11107, "text": "Since this is my first blog, I request you folks to share your views about the content and quality of this blog. If there are any doubts, I am more than happy to help. You can connect with me on Linkedin @ Sriram Muralishankar ." }, { "code": null, "e": 11636, "s": 11336, "text": "Deep Moji Dataset-https://github.com/bfelbo/DeepMoji/tree/master/dataCoursera Sequence Models Tutorial- https://github.com/Kulbear/deep-learning-coursera/blob/master/Sequence%20Models/Emojify%20-%20v2.ipynbAWS Documentation- https://docs.aws.amazon.com/Docker Documentation- https://docs.docker.com/" }, { "code": null, "e": 11706, "s": 11636, "text": "Deep Moji Dataset-https://github.com/bfelbo/DeepMoji/tree/master/data" }, { "code": null, "e": 11844, "s": 11706, "text": "Coursera Sequence Models Tutorial- https://github.com/Kulbear/deep-learning-coursera/blob/master/Sequence%20Models/Emojify%20-%20v2.ipynb" }, { "code": null, "e": 11892, "s": 11844, "text": "AWS Documentation- https://docs.aws.amazon.com/" } ]
Solidity - Functions
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions. Like any other advanced programming language, Solidity also supports all the features necessary to write modular code using functions. This section explains how to write your own functions in Solidity. Before we use a function, we need to define it. The most common way to define a function in Solidity is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here. function function-name(parameter-list) scope returns() { //statements } Try the following example. It defines a function called getResult that takes no parameters βˆ’ pragma solidity ^0.5.0; contract Test { function getResult() public view returns(uint){ uint a = 1; // local variable uint b = 2; uint result = a + b; return result; } } To invoke a function somewhere later in the Contract, you would simply need to write the name of that function as shown in the following code. Try the following code to understand how the string works in Solidity. pragma solidity ^0.5.0; contract SolidityTest { constructor() public{ } function getResult() public view returns(string memory){ uint a = 1; uint b = 2; uint result = a + b; return integerToString(result); } function integerToString(uint _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr);//access local variable } } Run the above program using steps provided in Solidity First Application chapter. 0: string: 3 Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma. Try the following example. We have used a uint2str function here. It takes one parameter. pragma solidity ^0.5.0; contract SolidityTest { constructor() public{ } function getResult() public view returns(string memory){ uint a = 1; uint b = 2; uint result = a + b; return integerToString(result); } function integerToString(uint _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr);//access local variable } } Run the above program using steps provided in Solidity First Application chapter. 0: string: 3 A Solidity function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function. As in above example, we are using uint2str function to return a string. In Solidity, a function can return multiple values as well. See the example below βˆ’ pragma solidity ^0.5.0; contract Test { function getResult() public view returns(uint product, uint sum){ uint a = 1; // local variable uint b = 2; product = a * b; sum = a + b; //alternative return statement to return //multiple values //return(a*b, a+b); } } Run the above program using steps provided in Solidity First Application chapter. 0: uint256: product 2 1: uint256: sum 3 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2856, "s": 2555, "text": "A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions." }, { "code": null, "e": 3058, "s": 2856, "text": "Like any other advanced programming language, Solidity also supports all the features necessary to write modular code using functions. This section explains how to write your own functions in Solidity." }, { "code": null, "e": 3323, "s": 3058, "text": "Before we use a function, we need to define it. The most common way to define a function in Solidity is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces." }, { "code": null, "e": 3355, "s": 3323, "text": "The basic syntax is shown here." }, { "code": null, "e": 3431, "s": 3355, "text": "function function-name(parameter-list) scope returns() {\n //statements\n}\n" }, { "code": null, "e": 3524, "s": 3431, "text": "Try the following example. It defines a function called getResult that takes no parameters βˆ’" }, { "code": null, "e": 3725, "s": 3524, "text": "pragma solidity ^0.5.0;\n\ncontract Test {\n function getResult() public view returns(uint){\n uint a = 1; // local variable\n uint b = 2;\n uint result = a + b;\n return result;\n }\n}" }, { "code": null, "e": 3868, "s": 3725, "text": "To invoke a function somewhere later in the Contract, you would simply need to write the name of that function as shown in the following code." }, { "code": null, "e": 3939, "s": 3868, "text": "Try the following code to understand how the string works in Solidity." }, { "code": null, "e": 4673, "s": 3939, "text": "pragma solidity ^0.5.0;\n\ncontract SolidityTest { \n constructor() public{ \n }\n function getResult() public view returns(string memory){\n uint a = 1; \n uint b = 2;\n uint result = a + b;\n return integerToString(result); \n }\n function integerToString(uint _i) internal pure \n returns (string memory) {\n \n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n \n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint k = len - 1;\n \n while (_i != 0) {\n bstr[k--] = byte(uint8(48 + _i % 10));\n _i /= 10;\n }\n return string(bstr);//access local variable\n }\n}" }, { "code": null, "e": 4755, "s": 4673, "text": "Run the above program using steps provided in Solidity First Application chapter." }, { "code": null, "e": 4769, "s": 4755, "text": "0: string: 3\n" }, { "code": null, "e": 5077, "s": 4769, "text": "Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma." }, { "code": null, "e": 5167, "s": 5077, "text": "Try the following example. We have used a uint2str function here. It takes one parameter." }, { "code": null, "e": 5901, "s": 5167, "text": "pragma solidity ^0.5.0;\n\ncontract SolidityTest { \n constructor() public{ \n }\n function getResult() public view returns(string memory){\n uint a = 1; \n uint b = 2;\n uint result = a + b;\n return integerToString(result); \n }\n function integerToString(uint _i) internal pure \n returns (string memory) {\n \n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n \n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint k = len - 1;\n \n while (_i != 0) {\n bstr[k--] = byte(uint8(48 + _i % 10));\n _i /= 10;\n }\n return string(bstr);//access local variable\n }\n}" }, { "code": null, "e": 5983, "s": 5901, "text": "Run the above program using steps provided in Solidity First Application chapter." }, { "code": null, "e": 5997, "s": 5983, "text": "0: string: 3\n" }, { "code": null, "e": 6179, "s": 5997, "text": "A Solidity function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function." }, { "code": null, "e": 6251, "s": 6179, "text": "As in above example, we are using uint2str function to return a string." }, { "code": null, "e": 6335, "s": 6251, "text": "In Solidity, a function can return multiple values as well. See the example below βˆ’" }, { "code": null, "e": 6649, "s": 6335, "text": "pragma solidity ^0.5.0;\n\ncontract Test {\n function getResult() public view returns(uint product, uint sum){\n uint a = 1; // local variable\n uint b = 2;\n product = a * b;\n sum = a + b;\n \n //alternative return statement to return \n //multiple values\n //return(a*b, a+b);\n }\n}" }, { "code": null, "e": 6731, "s": 6649, "text": "Run the above program using steps provided in Solidity First Application chapter." }, { "code": null, "e": 6772, "s": 6731, "text": "0: uint256: product 2\n1: uint256: sum 3\n" }, { "code": null, "e": 6807, "s": 6772, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6824, "s": 6807, "text": " Abhilash Nelson" }, { "code": null, "e": 6859, "s": 6824, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6876, "s": 6859, "text": " Frahaan Hussain" }, { "code": null, "e": 6911, "s": 6876, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6925, "s": 6911, "text": " Swapnil Kole" }, { "code": null, "e": 6932, "s": 6925, "text": " Print" }, { "code": null, "e": 6943, "s": 6932, "text": " Add Notes" } ]
Fake News Classification with Recurrent Convolutional Neural Networks | by Amol Mavuduru | Towards Data Science
Fake news is a topic that has gained a lot of attention in the past few years, and for good reasons. As social media becomes widely accessible, it becomes easier to influence millions of people by spreading misinformation. As humans, we often fail to recognize if the news we read is real or fake. A study from the University of Michigan found that human participants were able to detect fake news stories only 70 percent of the time. But can a neural network do any better? Keep reading to find out. The goal of this article is to answer the following questions: What kinds of topics or keywords appear frequently in real news versus fake news? How can we use a deep neural network to identify fake news stories? While most of the libraries I imported below are commonly used (NumPy, Pandas, Matplotlib, etc.), I also made use of the following helpful libraries: Pandarallel is a helpful library for running operations on Pandas data frames in parallel and monitoring the progress of each worker in real-time. Spacy is a library for advanced natural language processing. It comes with language models for languages such as English, Spanish, and German. In this project, I installed and imported the English language model, en_core_web_md. import numpy as npimport pandas as pdfrom pandarallel import pandarallelpandarallel.initialize(progress_bar=True, use_memory_fs=False, )import spacyimport en_core_web_mdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline The dataset that I used for this project contains data selected and aggregated from multiple Kaggle news datasets listed below: Getting Real About Fake News Fake and Real News Dataset Source-Based Fake News Classification All The News: 143,000 articles from 15 American publications As shown in the output of the Pandas code below, the dataset has around 74,000 rows with three columns: the title of the news article, the text of the news article, and a binary label indicating whether the news is real or fake. data = pd.read_csv('./data/combined_news_data.csv')data.dropna(inplace=True)data.info()<class 'pandas.core.frame.DataFrame'>Int64Index: 74012 entries, 0 to 74783Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 title 74012 non-null object 1 text 74012 non-null object 2 label 74012 non-null int64 dtypes: int64(1), object(2)memory usage: 2.3+ MB As demonstrated in the plot generated using Seaborn below, the dataset has a roughly even distribution of fake and real news articles, which is optimal for this binary classification task. sns.set(rc={'figure.figsize':(11.7,8.27)})sns.countplot(data['label']) We can also examine the distribution of article lengths for the news articles using the code below, which creates a column that counts the word count of each article and displays the distribution of article lengths using Seaborn’s distplot function. data['length'] = data['text'].apply(lambda x: len(x.split(' ')))sns.distplot(data['length']) Taking a closer look at this distribution using the describe function from Pandas produces the following output. data['length'].describe()count 74012.000000mean 549.869251std 629.223073min 1.00000025% 235.00000050% 404.00000075% 672.000000max 24234.000000Name: length, dtype: float64 The average article length is about 550 words and the median article length is 404 words. The distribution is right-skewed with 75 percent of the articles having a word count under 672 words while the longest article is clearly an outlier with over 24,000 words. For the purpose of building a model, we could likely achieve satisfactory results by only using the first 500 or so words in each article to determine if it is fake news. The first step in preparing data for most natural language processing tasks is preprocessing the text data. For this task, I performed the following preprocessing steps in the preprocessor function defined below: Removing unwanted characters such as punctuation, HTML tags, and emoticons using regular expressions. Removing stop words (words that are extremely common in the English language and are generally not necessary for text classification purposes). Lemmatization, which is the process of reducing a word to its lemma or dictionary form. For example, the word run is the lemma for the words runs, ran, and running. I used Python’s regex library to remove unwanted characters from the text data and Spacy’s medium-sized English language model (en_core_web_md) to perform stopword removal and lemmatization. In order to speed up the computation process for this expensive text-processing function, I made use of the parallel_apply function from Pandarallel, which parallelized the execution process across four cores. import re from spacy.lang.en.stop_words import STOP_WORDSnlp = en_core_web_md.load()def preprocessor(text): text = re.sub('<[^>]*>', '', text) emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text) text = re.sub('[\W]+', ' ', text.lower()) + ''.join(emoticons).replace('-', '') doc = nlp(text) text = ' '.join([token.lemma_ for token in doc if token.text not in STOP_WORDS]) return textX = data['text'].parallel_apply(preprocessor)y = data['label']data_processed = pd.DataFrame({'title': data['title'], 'text': X, 'label': y}) After preprocessing the text data, I was able to use latent Dirichlet allocation (LDA) to compare the topics and most significant terms in real and fake news articles. LDA is an unsupervised topic modeling technique based on the following assumptions: Each document (in this case each news article) is a bag of words, meaning the order of words in the document is not taken into account when extracting topics. Each document has a distribution of topics and each topic is defined by a distribution of words. There are k topics across all documents. The parameter k is specified beforehand for the algorithm. The probability of a document containing words belonging to a specific topic can be modeled as a Dirichlet distribution. In its simplest form, the LDA algorithm follows these steps for every document D in the collection of documents: Distribute each of the k topics across the document D by assigning each word a topic according to the Dirichlet distribution.For each word in D assume its topic is wrong but every other word is assigned the correct topic.Assign this word a probability of belonging to each topic based on:- the topics in document D- how many times this word has been assigned to each topic across all documents.Repeat steps 1–4 for all documents. Distribute each of the k topics across the document D by assigning each word a topic according to the Dirichlet distribution. For each word in D assume its topic is wrong but every other word is assigned the correct topic. Assign this word a probability of belonging to each topic based on:- the topics in document D- how many times this word has been assigned to each topic across all documents. Repeat steps 1–4 for all documents. For a more detailed yet easily understandable overview of LDA, check out this page on Edwin Chen’s blog. I used the LDA module from Scikit-learn to perform topic modeling and a useful Python library called pyLDAvis to create interactive visualizations of the topic models for both real and fake news. The necessary imports for this task are given below. from sklearn.decomposition import LatentDirichletAllocationfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.manifold import TSNEfrom sklearn.pipeline import Pipelineimport pyLDAvis.sklearn The code given below performs topic modeling on the preprocessed real news articles with ten different topics and then creates an interactive visualization that displays each topic in two-dimensional space using pyLDAvis. real_news = data_processed[data_processed['label'] == 1]num_topics = 10num_features=5000vectorizer = CountVectorizer(max_df=0.95, min_df=2, max_features=num_features, stop_words='english')lda = LatentDirichletAllocation(n_components=num_topics, max_iter=5, learning_method='online', learning_offset=50., random_state=0)lda_pipeline = Pipeline([('vectorizer', vectorizer), ('lda', lda)])lda_pipeline.fit(real_news['text'])pyLDAvis.enable_notebook()data_vectorized = vectorizer.fit_transform(data_processed['text'])dash = pyLDAvis.sklearn.prepare(lda_pipeline.steps[1][1], data_vectorized, vectorizer, mds='tsne')pyLDAvis.save_html(dash, 'real_news_lda.html') The visualization above allows the user to view the relative size of each of the ten extracted topics while displaying the most relevant terms for each topic. You can check out the full interactive visualization here. The code given below replicates the previous steps for the fake news articles to produce a similar interactive visualization. fake_news = data_processed[data_processed['label'] == 0]num_topics = 10num_features=5000vectorizer = CountVectorizer(max_df=0.95, min_df=2, max_features=num_features, stop_words='english')lda = LatentDirichletAllocation(n_components=num_topics, max_iter=5, learning_method='online', learning_offset=50., random_state=0)lda_pipeline = Pipeline([('vectorizer', vectorizer), ('lda', lda)])lda_pipeline.fit(fake_news['text'])pyLDAvis.enable_notebook()data_vectorized = vectorizer.fit_transform(data_processed['text'])dash = pyLDAvis.sklearn.prepare(lda_pipeline.steps[1][1], data_vectorized, vectorizer, mds='tsne')pyLDAvis.save_html(dash, 'fake_news_lda.html') You can check out the full interactive visualization here. Based on the topic model visualizations for real and fake news, it is clear that fake news usually involves different topics when compared to real news. Based on the visualizations and some of the topic keywords such as treason, violation, pathetic, rush, and violence it seems that fake news generally covers more controversial topics such as alleged political scandals and conspiracy theories. The deep learning model I designed for this task is a recurrent convolutional neural network model that consists of several different types of sequential operations and layers: A tokenizer is used to transform each article into a vector of indexed words (tokens).A word embedding layer that learns an embedding vector with m dimensions for each unique word and applies this embedding for the first n words in each news article, generating a m x n matrix.1D convolutional and max-pooling layers.LSTM layers followed by dropout layers.A final fully-connected layer. A tokenizer is used to transform each article into a vector of indexed words (tokens). A word embedding layer that learns an embedding vector with m dimensions for each unique word and applies this embedding for the first n words in each news article, generating a m x n matrix. 1D convolutional and max-pooling layers. LSTM layers followed by dropout layers. A final fully-connected layer. These components are explained in greater detail below. A tokenizer is used to split each news article into a vector of sequential words, which is later converted to a vector of integers by assigning a unique integer index to each word. The figure below demonstrates this process with a simple sentence. Word embeddings are learnable vector representations of words that represent the meaning of the words in relation to other words. Deep learning approaches can learn word embeddings from collections of text such that words with similar embedding vectors tend to have similar meanings or represent similar concepts. These components are the convolutional part of the recurrent convolutional neural network. If you have studied computer vision, you may be familiar with 2D convolutional and pooling layers that operate on image data. For text data, however, we need to use 1D convolutional and pooling layers. A 1D convolutional layer has a series of kernels, which are low-dimensional vectors that incrementally slide across the input vector as dot products are computed to produce the output vector. In the example below, a 1D convolutional operation with a kernel of size 2 is applied to an input vector with 5 elements. Like 1D convolutional layers, 1D max-pooling layers also operate on vectors but reduce the size of the input by selecting the maximum value from local regions in the input. In the example below, a max-pooling operation with a pool size of 2 is applied to a vector with 6 elements. The LSTM (long short-term memory) units form the recurrent part of the recurrent convolutional neural network. LSTMs are often used for tasks involving sequence data such as time series forecasting and text classification. I won’t dive deeply into the mathematical background behind LSTMs because that topic is out of the scope of this article, but essentially an LSTM is a unit in a neural network capable of remembering essential information for long periods of time and forgetting information when it is no longer relevant (hence the name, long short-term memory). An LSTM unit consists of three gates: An input gate which receives the input values. A forget gate which decides how much of the past information acquired during training should be remembered. An output gate which produces the output values. The ability of LSTMs to selectively remember information is useful in text classification problems such as fake news classification, since the information at the beginning of a news article may still be relevant to the content in the middle or towards the end of the article. The final part of this model is simply a fully-connected layer that you would find in a β€œvanilla” neural network. This layer receives the output from the last LSTM layer and computes a weighted sum of the vector values, applying a sigmoid activation to this sum to produce the final output β€” a value between 0 and 1 corresponding to the probability of an article being real news. The class that I created below is designed for customizing and encapsulating a model with all of the components described above. This class represents a pipeline that can be fitted directly to preprocessed text data without having to perform steps such as tokenization and word indexing beforehand. The LSTM_Text_Classifier class extends the BaseEstimator and ClassifierMixin classes from Scikit-learn, allowing it to behave like a Scikit-learn estimator. Using this class, I created a model with the following components in the code below: A word embedding layer that learns a 64-dimensional embedding vector for each word and aggregates the vectors from the first 512 words of a news article to generate a 512 x 64 embedding matrix for each input article. Three convolutional layers with 128 convolutional filters and a kernel size of 5, each followed by a max-pooling layer. Two LSTM layers with 128 neurons, each followed by a dropout layer with a 10 percent dropout rate. A fully-connected layer at the end of the network with a sigmoid activation, outputting a single value ranging from 0 to 1 and indicating the probability of an article being real news. lstm_classifier = LSTM_Text_Classifier(embedding_vector_length=64, max_seq_length=512, dropout=0.1, lstm_layers=[128, 128], batch_size=256, num_epochs=5, use_hash=False,conv_params={'filters': 128, 'kernel_size': 5, 'pool_size': 2, 'n_layers': 3}) The visualization below gives us a good idea of what the model architecture for this recurrent convolutional network looks like. In order to evaluate the performance of this model effectively, it is necessary to split the data into separate training, validation, and testing sets. Based on the code below, 30 percent of the data is used for testing, and of the remaining 70 percent, 14 percent (20 percent of 70) is used for validation, and the remaining 56 percent is used for training. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=0.2, random_state=42) After defining this complex model, I was able to train it on the training set while monitoring its performance on the validation set. The model was trained for three epochs and achieved its peak validation performance at the end second training epoch based on the code and output below. lstm_classifier.fit(X_train, y_train, validation_data=(X_valid, y_valid))Fitting Tokenizer...Model: "sequential_4"_________________________________________________________________Layer (type) Output Shape Param # =================================================================embedding_4 (Embedding) (None, 512, 64) 13169920 _________________________________________________________________conv1d_10 (Conv1D) (None, 512, 256) 82176 _________________________________________________________________max_pooling1d_10 (MaxPooling (None, 256, 256) 0 _________________________________________________________________conv1d_11 (Conv1D) (None, 256, 512) 655872 _________________________________________________________________max_pooling1d_11 (MaxPooling (None, 128, 512) 0 _________________________________________________________________conv1d_12 (Conv1D) (None, 128, 768) 1966848 _________________________________________________________________max_pooling1d_12 (MaxPooling (None, 64, 768) 0 _________________________________________________________________lstm_7 (LSTM) (None, 64, 128) 459264 _________________________________________________________________dropout_7 (Dropout) (None, 64, 128) 0 _________________________________________________________________lstm_8 (LSTM) (None, 128) 131584 _________________________________________________________________dropout_8 (Dropout) (None, 128) 0 _________________________________________________________________dense_4 (Dense) (None, 1) 129 =================================================================Total params: 16,465,793Trainable params: 16,465,793Non-trainable params: 0_________________________________________________________________NoneFitting model...Train on 41446 samples, validate on 10362 samplesEpoch 1/541446/41446 [==============================] - 43s 1ms/step - loss: 0.2858 - accuracy: 0.8648 - val_loss: 0.1433 - val_accuracy: 0.9505Epoch 2/541446/41446 [==============================] - 42s 1ms/step - loss: 0.0806 - accuracy: 0.9715 - val_loss: 0.1192 - val_accuracy: 0.9543Epoch 3/541446/41446 [==============================] - 43s 1ms/step - loss: 0.0381 - accuracy: 0.9881 - val_loss: 0.1470 - val_accuracy: 0.9527Epoch 00003: early stopping While accuracy is a useful metric for classification, it fails to tell us how the model is performing with respect to detecting each class. The code provided below computes the confusion matrix and classification report for the model’s predictions on the validation dataset to provide a better picture of the model’s performance. The confusion matrix provides classification statistics in the following format: The classification report for each class provides the following additional metrics: Precision β€” the number of times a class was correctly predicted divided by the total number of times the model predicted this class.Recall β€” the number of times a class was correctly predicted divided by the total number of samples with that class label in the testing data.F1-Score β€” the harmonic mean of precision and recall. Precision β€” the number of times a class was correctly predicted divided by the total number of times the model predicted this class. Recall β€” the number of times a class was correctly predicted divided by the total number of samples with that class label in the testing data. F1-Score β€” the harmonic mean of precision and recall. lstm_classifier.load_model('best_model')from sklearn.metrics import confusion_matrix, classification_reporty_pred = lstm_classifier.predict_classes(X_valid)print(confusion_matrix(y_valid, y_pred))print(classification_report(y_valid, y_pred, digits=4))[[4910 204] [ 271 4977]] precision recall f1-score support 0 0.9477 0.9601 0.9539 5114 1 0.9606 0.9484 0.9545 5248 accuracy 0.9542 10362 macro avg 0.9542 0.9542 0.9542 10362weighted avg 0.9542 0.9542 0.9542 10362 Based on the results above, we can clearly see that the model is nearly as good at detecting fake news correctly as it is at detecting real news correctly and achieved an overall accuracy of 95.42 percent on the validation data, which is pretty impressive. According to the confusion matrix, only 271 articles were misclassified as fake news and only 204 articles were misclassified as real news. While the validation results can give us some indication of the model’s performance on unseen data, it is the testing set, which has not been touched at all during the model training process which provides the best objective and statistically correct measure of the model’s performance. The code below produces a classification report for the testing set. from sklearn.metrics import accuracy_scorey_pred_test = lstm_classifier.predict_classes(X_test)print(classification_report(y_test, y_pred_test)) precision recall f1-score support 0 0.94 0.95 0.95 11143 1 0.95 0.94 0.95 11061 accuracy 0.95 22204 macro avg 0.95 0.95 0.95 22204weighted avg 0.95 0.95 0.95 22204 Based on the output above, the model achieved a similar level of performance on the testing set compared to its performance on the validation set. The model classified news articles in the testing set with an accuracy of 95 percent. Compared to the study in which humans were able to detect fake news only 70 percent of the time, these results are promising and demonstrate that a trained neural network could potentially do a better job at filtering out fake news than a human reader. Based on the LDA visualizations, we can see that there is a different distribution of topics and associated keywords for real and fake news. The recurrent convolutional neural network used in this project was able to distinguish between real and fake news articles with 95 percent accuracy on the testing data, which suggest that neural networks can potentially detect fake news better than human readers. Feel free to check out the Jupyter notebook with the code for this article on GitHub. V. Pérez-Rosas, B. Kleinberg, A. Lefevre, R. Mihalcea, Automatic Detection of Fake News, (2018), arXiv.orgA. Bharadwaj, B. Ashar, P. Barbhaya, R. Bhatia, Z. Shaikh, Source-Based Fake News Classification using Machine Learning, (2020), International Journal of Innovative Research in Science, Engineering and Technology V. Pérez-Rosas, B. Kleinberg, A. Lefevre, R. Mihalcea, Automatic Detection of Fake News, (2018), arXiv.org A. Bharadwaj, B. Ashar, P. Barbhaya, R. Bhatia, Z. Shaikh, Source-Based Fake News Classification using Machine Learning, (2020), International Journal of Innovative Research in Science, Engineering and Technology
[ { "code": null, "e": 672, "s": 171, "text": "Fake news is a topic that has gained a lot of attention in the past few years, and for good reasons. As social media becomes widely accessible, it becomes easier to influence millions of people by spreading misinformation. As humans, we often fail to recognize if the news we read is real or fake. A study from the University of Michigan found that human participants were able to detect fake news stories only 70 percent of the time. But can a neural network do any better? Keep reading to find out." }, { "code": null, "e": 735, "s": 672, "text": "The goal of this article is to answer the following questions:" }, { "code": null, "e": 817, "s": 735, "text": "What kinds of topics or keywords appear frequently in real news versus fake news?" }, { "code": null, "e": 885, "s": 817, "text": "How can we use a deep neural network to identify fake news stories?" }, { "code": null, "e": 1035, "s": 885, "text": "While most of the libraries I imported below are commonly used (NumPy, Pandas, Matplotlib, etc.), I also made use of the following helpful libraries:" }, { "code": null, "e": 1182, "s": 1035, "text": "Pandarallel is a helpful library for running operations on Pandas data frames in parallel and monitoring the progress of each worker in real-time." }, { "code": null, "e": 1411, "s": 1182, "text": "Spacy is a library for advanced natural language processing. It comes with language models for languages such as English, Spanish, and German. In this project, I installed and imported the English language model, en_core_web_md." }, { "code": null, "e": 1651, "s": 1411, "text": "import numpy as npimport pandas as pdfrom pandarallel import pandarallelpandarallel.initialize(progress_bar=True, use_memory_fs=False, )import spacyimport en_core_web_mdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline" }, { "code": null, "e": 1779, "s": 1651, "text": "The dataset that I used for this project contains data selected and aggregated from multiple Kaggle news datasets listed below:" }, { "code": null, "e": 1808, "s": 1779, "text": "Getting Real About Fake News" }, { "code": null, "e": 1835, "s": 1808, "text": "Fake and Real News Dataset" }, { "code": null, "e": 1873, "s": 1835, "text": "Source-Based Fake News Classification" }, { "code": null, "e": 1934, "s": 1873, "text": "All The News: 143,000 articles from 15 American publications" }, { "code": null, "e": 2163, "s": 1934, "text": "As shown in the output of the Pandas code below, the dataset has around 74,000 rows with three columns: the title of the news article, the text of the news article, and a binary label indicating whether the news is real or fake." }, { "code": null, "e": 2579, "s": 2163, "text": "data = pd.read_csv('./data/combined_news_data.csv')data.dropna(inplace=True)data.info()<class 'pandas.core.frame.DataFrame'>Int64Index: 74012 entries, 0 to 74783Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 title 74012 non-null object 1 text 74012 non-null object 2 label 74012 non-null int64 dtypes: int64(1), object(2)memory usage: 2.3+ MB" }, { "code": null, "e": 2768, "s": 2579, "text": "As demonstrated in the plot generated using Seaborn below, the dataset has a roughly even distribution of fake and real news articles, which is optimal for this binary classification task." }, { "code": null, "e": 2839, "s": 2768, "text": "sns.set(rc={'figure.figsize':(11.7,8.27)})sns.countplot(data['label'])" }, { "code": null, "e": 3089, "s": 2839, "text": "We can also examine the distribution of article lengths for the news articles using the code below, which creates a column that counts the word count of each article and displays the distribution of article lengths using Seaborn’s distplot function." }, { "code": null, "e": 3182, "s": 3089, "text": "data['length'] = data['text'].apply(lambda x: len(x.split(' ')))sns.distplot(data['length'])" }, { "code": null, "e": 3295, "s": 3182, "text": "Taking a closer look at this distribution using the describe function from Pandas produces the following output." }, { "code": null, "e": 3517, "s": 3295, "text": "data['length'].describe()count 74012.000000mean 549.869251std 629.223073min 1.00000025% 235.00000050% 404.00000075% 672.000000max 24234.000000Name: length, dtype: float64" }, { "code": null, "e": 3951, "s": 3517, "text": "The average article length is about 550 words and the median article length is 404 words. The distribution is right-skewed with 75 percent of the articles having a word count under 672 words while the longest article is clearly an outlier with over 24,000 words. For the purpose of building a model, we could likely achieve satisfactory results by only using the first 500 or so words in each article to determine if it is fake news." }, { "code": null, "e": 4164, "s": 3951, "text": "The first step in preparing data for most natural language processing tasks is preprocessing the text data. For this task, I performed the following preprocessing steps in the preprocessor function defined below:" }, { "code": null, "e": 4266, "s": 4164, "text": "Removing unwanted characters such as punctuation, HTML tags, and emoticons using regular expressions." }, { "code": null, "e": 4410, "s": 4266, "text": "Removing stop words (words that are extremely common in the English language and are generally not necessary for text classification purposes)." }, { "code": null, "e": 4575, "s": 4410, "text": "Lemmatization, which is the process of reducing a word to its lemma or dictionary form. For example, the word run is the lemma for the words runs, ran, and running." }, { "code": null, "e": 4976, "s": 4575, "text": "I used Python’s regex library to remove unwanted characters from the text data and Spacy’s medium-sized English language model (en_core_web_md) to perform stopword removal and lemmatization. In order to speed up the computation process for this expensive text-processing function, I made use of the parallel_apply function from Pandarallel, which parallelized the execution process across four cores." }, { "code": null, "e": 5527, "s": 4976, "text": "import re from spacy.lang.en.stop_words import STOP_WORDSnlp = en_core_web_md.load()def preprocessor(text): text = re.sub('<[^>]*>', '', text) emoticons = re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', text) text = re.sub('[\\W]+', ' ', text.lower()) + ''.join(emoticons).replace('-', '') doc = nlp(text) text = ' '.join([token.lemma_ for token in doc if token.text not in STOP_WORDS]) return textX = data['text'].parallel_apply(preprocessor)y = data['label']data_processed = pd.DataFrame({'title': data['title'], 'text': X, 'label': y})" }, { "code": null, "e": 5779, "s": 5527, "text": "After preprocessing the text data, I was able to use latent Dirichlet allocation (LDA) to compare the topics and most significant terms in real and fake news articles. LDA is an unsupervised topic modeling technique based on the following assumptions:" }, { "code": null, "e": 5938, "s": 5779, "text": "Each document (in this case each news article) is a bag of words, meaning the order of words in the document is not taken into account when extracting topics." }, { "code": null, "e": 6035, "s": 5938, "text": "Each document has a distribution of topics and each topic is defined by a distribution of words." }, { "code": null, "e": 6135, "s": 6035, "text": "There are k topics across all documents. The parameter k is specified beforehand for the algorithm." }, { "code": null, "e": 6256, "s": 6135, "text": "The probability of a document containing words belonging to a specific topic can be modeled as a Dirichlet distribution." }, { "code": null, "e": 6369, "s": 6256, "text": "In its simplest form, the LDA algorithm follows these steps for every document D in the collection of documents:" }, { "code": null, "e": 6799, "s": 6369, "text": "Distribute each of the k topics across the document D by assigning each word a topic according to the Dirichlet distribution.For each word in D assume its topic is wrong but every other word is assigned the correct topic.Assign this word a probability of belonging to each topic based on:- the topics in document D- how many times this word has been assigned to each topic across all documents.Repeat steps 1–4 for all documents." }, { "code": null, "e": 6925, "s": 6799, "text": "Distribute each of the k topics across the document D by assigning each word a topic according to the Dirichlet distribution." }, { "code": null, "e": 7022, "s": 6925, "text": "For each word in D assume its topic is wrong but every other word is assigned the correct topic." }, { "code": null, "e": 7196, "s": 7022, "text": "Assign this word a probability of belonging to each topic based on:- the topics in document D- how many times this word has been assigned to each topic across all documents." }, { "code": null, "e": 7232, "s": 7196, "text": "Repeat steps 1–4 for all documents." }, { "code": null, "e": 7337, "s": 7232, "text": "For a more detailed yet easily understandable overview of LDA, check out this page on Edwin Chen’s blog." }, { "code": null, "e": 7586, "s": 7337, "text": "I used the LDA module from Scikit-learn to perform topic modeling and a useful Python library called pyLDAvis to create interactive visualizations of the topic models for both real and fake news. The necessary imports for this task are given below." }, { "code": null, "e": 7798, "s": 7586, "text": "from sklearn.decomposition import LatentDirichletAllocationfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.manifold import TSNEfrom sklearn.pipeline import Pipelineimport pyLDAvis.sklearn" }, { "code": null, "e": 8020, "s": 7798, "text": "The code given below performs topic modeling on the preprocessed real news articles with ten different topics and then creates an interactive visualization that displays each topic in two-dimensional space using pyLDAvis." }, { "code": null, "e": 8804, "s": 8020, "text": "real_news = data_processed[data_processed['label'] == 1]num_topics = 10num_features=5000vectorizer = CountVectorizer(max_df=0.95, min_df=2, max_features=num_features, stop_words='english')lda = LatentDirichletAllocation(n_components=num_topics, max_iter=5, learning_method='online', learning_offset=50., random_state=0)lda_pipeline = Pipeline([('vectorizer', vectorizer), ('lda', lda)])lda_pipeline.fit(real_news['text'])pyLDAvis.enable_notebook()data_vectorized = vectorizer.fit_transform(data_processed['text'])dash = pyLDAvis.sklearn.prepare(lda_pipeline.steps[1][1], data_vectorized, vectorizer, mds='tsne')pyLDAvis.save_html(dash, 'real_news_lda.html')" }, { "code": null, "e": 9022, "s": 8804, "text": "The visualization above allows the user to view the relative size of each of the ten extracted topics while displaying the most relevant terms for each topic. You can check out the full interactive visualization here." }, { "code": null, "e": 9148, "s": 9022, "text": "The code given below replicates the previous steps for the fake news articles to produce a similar interactive visualization." }, { "code": null, "e": 9932, "s": 9148, "text": "fake_news = data_processed[data_processed['label'] == 0]num_topics = 10num_features=5000vectorizer = CountVectorizer(max_df=0.95, min_df=2, max_features=num_features, stop_words='english')lda = LatentDirichletAllocation(n_components=num_topics, max_iter=5, learning_method='online', learning_offset=50., random_state=0)lda_pipeline = Pipeline([('vectorizer', vectorizer), ('lda', lda)])lda_pipeline.fit(fake_news['text'])pyLDAvis.enable_notebook()data_vectorized = vectorizer.fit_transform(data_processed['text'])dash = pyLDAvis.sklearn.prepare(lda_pipeline.steps[1][1], data_vectorized, vectorizer, mds='tsne')pyLDAvis.save_html(dash, 'fake_news_lda.html')" }, { "code": null, "e": 10387, "s": 9932, "text": "You can check out the full interactive visualization here. Based on the topic model visualizations for real and fake news, it is clear that fake news usually involves different topics when compared to real news. Based on the visualizations and some of the topic keywords such as treason, violation, pathetic, rush, and violence it seems that fake news generally covers more controversial topics such as alleged political scandals and conspiracy theories." }, { "code": null, "e": 10564, "s": 10387, "text": "The deep learning model I designed for this task is a recurrent convolutional neural network model that consists of several different types of sequential operations and layers:" }, { "code": null, "e": 10951, "s": 10564, "text": "A tokenizer is used to transform each article into a vector of indexed words (tokens).A word embedding layer that learns an embedding vector with m dimensions for each unique word and applies this embedding for the first n words in each news article, generating a m x n matrix.1D convolutional and max-pooling layers.LSTM layers followed by dropout layers.A final fully-connected layer." }, { "code": null, "e": 11038, "s": 10951, "text": "A tokenizer is used to transform each article into a vector of indexed words (tokens)." }, { "code": null, "e": 11230, "s": 11038, "text": "A word embedding layer that learns an embedding vector with m dimensions for each unique word and applies this embedding for the first n words in each news article, generating a m x n matrix." }, { "code": null, "e": 11271, "s": 11230, "text": "1D convolutional and max-pooling layers." }, { "code": null, "e": 11311, "s": 11271, "text": "LSTM layers followed by dropout layers." }, { "code": null, "e": 11342, "s": 11311, "text": "A final fully-connected layer." }, { "code": null, "e": 11398, "s": 11342, "text": "These components are explained in greater detail below." }, { "code": null, "e": 11646, "s": 11398, "text": "A tokenizer is used to split each news article into a vector of sequential words, which is later converted to a vector of integers by assigning a unique integer index to each word. The figure below demonstrates this process with a simple sentence." }, { "code": null, "e": 11960, "s": 11646, "text": "Word embeddings are learnable vector representations of words that represent the meaning of the words in relation to other words. Deep learning approaches can learn word embeddings from collections of text such that words with similar embedding vectors tend to have similar meanings or represent similar concepts." }, { "code": null, "e": 12567, "s": 11960, "text": "These components are the convolutional part of the recurrent convolutional neural network. If you have studied computer vision, you may be familiar with 2D convolutional and pooling layers that operate on image data. For text data, however, we need to use 1D convolutional and pooling layers. A 1D convolutional layer has a series of kernels, which are low-dimensional vectors that incrementally slide across the input vector as dot products are computed to produce the output vector. In the example below, a 1D convolutional operation with a kernel of size 2 is applied to an input vector with 5 elements." }, { "code": null, "e": 12848, "s": 12567, "text": "Like 1D convolutional layers, 1D max-pooling layers also operate on vectors but reduce the size of the input by selecting the maximum value from local regions in the input. In the example below, a max-pooling operation with a pool size of 2 is applied to a vector with 6 elements." }, { "code": null, "e": 13454, "s": 12848, "text": "The LSTM (long short-term memory) units form the recurrent part of the recurrent convolutional neural network. LSTMs are often used for tasks involving sequence data such as time series forecasting and text classification. I won’t dive deeply into the mathematical background behind LSTMs because that topic is out of the scope of this article, but essentially an LSTM is a unit in a neural network capable of remembering essential information for long periods of time and forgetting information when it is no longer relevant (hence the name, long short-term memory). An LSTM unit consists of three gates:" }, { "code": null, "e": 13501, "s": 13454, "text": "An input gate which receives the input values." }, { "code": null, "e": 13609, "s": 13501, "text": "A forget gate which decides how much of the past information acquired during training should be remembered." }, { "code": null, "e": 13658, "s": 13609, "text": "An output gate which produces the output values." }, { "code": null, "e": 13934, "s": 13658, "text": "The ability of LSTMs to selectively remember information is useful in text classification problems such as fake news classification, since the information at the beginning of a news article may still be relevant to the content in the middle or towards the end of the article." }, { "code": null, "e": 14314, "s": 13934, "text": "The final part of this model is simply a fully-connected layer that you would find in a β€œvanilla” neural network. This layer receives the output from the last LSTM layer and computes a weighted sum of the vector values, applying a sigmoid activation to this sum to produce the final output β€” a value between 0 and 1 corresponding to the probability of an article being real news." }, { "code": null, "e": 14770, "s": 14314, "text": "The class that I created below is designed for customizing and encapsulating a model with all of the components described above. This class represents a pipeline that can be fitted directly to preprocessed text data without having to perform steps such as tokenization and word indexing beforehand. The LSTM_Text_Classifier class extends the BaseEstimator and ClassifierMixin classes from Scikit-learn, allowing it to behave like a Scikit-learn estimator." }, { "code": null, "e": 14855, "s": 14770, "text": "Using this class, I created a model with the following components in the code below:" }, { "code": null, "e": 15072, "s": 14855, "text": "A word embedding layer that learns a 64-dimensional embedding vector for each word and aggregates the vectors from the first 512 words of a news article to generate a 512 x 64 embedding matrix for each input article." }, { "code": null, "e": 15192, "s": 15072, "text": "Three convolutional layers with 128 convolutional filters and a kernel size of 5, each followed by a max-pooling layer." }, { "code": null, "e": 15291, "s": 15192, "text": "Two LSTM layers with 128 neurons, each followed by a dropout layer with a 10 percent dropout rate." }, { "code": null, "e": 15476, "s": 15291, "text": "A fully-connected layer at the end of the network with a sigmoid activation, outputting a single value ranging from 0 to 1 and indicating the probability of an article being real news." }, { "code": null, "e": 15762, "s": 15476, "text": "lstm_classifier = LSTM_Text_Classifier(embedding_vector_length=64, max_seq_length=512, dropout=0.1, lstm_layers=[128, 128], batch_size=256, num_epochs=5, use_hash=False,conv_params={'filters': 128, 'kernel_size': 5, 'pool_size': 2, 'n_layers': 3})" }, { "code": null, "e": 15891, "s": 15762, "text": "The visualization below gives us a good idea of what the model architecture for this recurrent convolutional network looks like." }, { "code": null, "e": 16250, "s": 15891, "text": "In order to evaluate the performance of this model effectively, it is necessary to split the data into separate training, validation, and testing sets. Based on the code below, 30 percent of the data is used for testing, and of the remaining 70 percent, 14 percent (20 percent of 70) is used for validation, and the remaining 56 percent is used for training." }, { "code": null, "e": 16495, "s": 16250, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=0.2, random_state=42)" }, { "code": null, "e": 16782, "s": 16495, "text": "After defining this complex model, I was able to train it on the training set while monitoring its performance on the validation set. The model was trained for three epochs and achieved its peak validation performance at the end second training epoch based on the code and output below." }, { "code": null, "e": 19320, "s": 16782, "text": "lstm_classifier.fit(X_train, y_train, validation_data=(X_valid, y_valid))Fitting Tokenizer...Model: \"sequential_4\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================embedding_4 (Embedding) (None, 512, 64) 13169920 _________________________________________________________________conv1d_10 (Conv1D) (None, 512, 256) 82176 _________________________________________________________________max_pooling1d_10 (MaxPooling (None, 256, 256) 0 _________________________________________________________________conv1d_11 (Conv1D) (None, 256, 512) 655872 _________________________________________________________________max_pooling1d_11 (MaxPooling (None, 128, 512) 0 _________________________________________________________________conv1d_12 (Conv1D) (None, 128, 768) 1966848 _________________________________________________________________max_pooling1d_12 (MaxPooling (None, 64, 768) 0 _________________________________________________________________lstm_7 (LSTM) (None, 64, 128) 459264 _________________________________________________________________dropout_7 (Dropout) (None, 64, 128) 0 _________________________________________________________________lstm_8 (LSTM) (None, 128) 131584 _________________________________________________________________dropout_8 (Dropout) (None, 128) 0 _________________________________________________________________dense_4 (Dense) (None, 1) 129 =================================================================Total params: 16,465,793Trainable params: 16,465,793Non-trainable params: 0_________________________________________________________________NoneFitting model...Train on 41446 samples, validate on 10362 samplesEpoch 1/541446/41446 [==============================] - 43s 1ms/step - loss: 0.2858 - accuracy: 0.8648 - val_loss: 0.1433 - val_accuracy: 0.9505Epoch 2/541446/41446 [==============================] - 42s 1ms/step - loss: 0.0806 - accuracy: 0.9715 - val_loss: 0.1192 - val_accuracy: 0.9543Epoch 3/541446/41446 [==============================] - 43s 1ms/step - loss: 0.0381 - accuracy: 0.9881 - val_loss: 0.1470 - val_accuracy: 0.9527Epoch 00003: early stopping" }, { "code": null, "e": 19731, "s": 19320, "text": "While accuracy is a useful metric for classification, it fails to tell us how the model is performing with respect to detecting each class. The code provided below computes the confusion matrix and classification report for the model’s predictions on the validation dataset to provide a better picture of the model’s performance. The confusion matrix provides classification statistics in the following format:" }, { "code": null, "e": 19815, "s": 19731, "text": "The classification report for each class provides the following additional metrics:" }, { "code": null, "e": 20143, "s": 19815, "text": "Precision β€” the number of times a class was correctly predicted divided by the total number of times the model predicted this class.Recall β€” the number of times a class was correctly predicted divided by the total number of samples with that class label in the testing data.F1-Score β€” the harmonic mean of precision and recall." }, { "code": null, "e": 20276, "s": 20143, "text": "Precision β€” the number of times a class was correctly predicted divided by the total number of times the model predicted this class." }, { "code": null, "e": 20419, "s": 20276, "text": "Recall β€” the number of times a class was correctly predicted divided by the total number of samples with that class label in the testing data." }, { "code": null, "e": 20473, "s": 20419, "text": "F1-Score β€” the harmonic mean of precision and recall." }, { "code": null, "e": 21068, "s": 20473, "text": "lstm_classifier.load_model('best_model')from sklearn.metrics import confusion_matrix, classification_reporty_pred = lstm_classifier.predict_classes(X_valid)print(confusion_matrix(y_valid, y_pred))print(classification_report(y_valid, y_pred, digits=4))[[4910 204] [ 271 4977]] precision recall f1-score support 0 0.9477 0.9601 0.9539 5114 1 0.9606 0.9484 0.9545 5248 accuracy 0.9542 10362 macro avg 0.9542 0.9542 0.9542 10362weighted avg 0.9542 0.9542 0.9542 10362" }, { "code": null, "e": 21465, "s": 21068, "text": "Based on the results above, we can clearly see that the model is nearly as good at detecting fake news correctly as it is at detecting real news correctly and achieved an overall accuracy of 95.42 percent on the validation data, which is pretty impressive. According to the confusion matrix, only 271 articles were misclassified as fake news and only 204 articles were misclassified as real news." }, { "code": null, "e": 21821, "s": 21465, "text": "While the validation results can give us some indication of the model’s performance on unseen data, it is the testing set, which has not been touched at all during the model training process which provides the best objective and statistically correct measure of the model’s performance. The code below produces a classification report for the testing set." }, { "code": null, "e": 22285, "s": 21821, "text": "from sklearn.metrics import accuracy_scorey_pred_test = lstm_classifier.predict_classes(X_test)print(classification_report(y_test, y_pred_test)) precision recall f1-score support 0 0.94 0.95 0.95 11143 1 0.95 0.94 0.95 11061 accuracy 0.95 22204 macro avg 0.95 0.95 0.95 22204weighted avg 0.95 0.95 0.95 22204" }, { "code": null, "e": 22771, "s": 22285, "text": "Based on the output above, the model achieved a similar level of performance on the testing set compared to its performance on the validation set. The model classified news articles in the testing set with an accuracy of 95 percent. Compared to the study in which humans were able to detect fake news only 70 percent of the time, these results are promising and demonstrate that a trained neural network could potentially do a better job at filtering out fake news than a human reader." }, { "code": null, "e": 22912, "s": 22771, "text": "Based on the LDA visualizations, we can see that there is a different distribution of topics and associated keywords for real and fake news." }, { "code": null, "e": 23177, "s": 22912, "text": "The recurrent convolutional neural network used in this project was able to distinguish between real and fake news articles with 95 percent accuracy on the testing data, which suggest that neural networks can potentially detect fake news better than human readers." }, { "code": null, "e": 23263, "s": 23177, "text": "Feel free to check out the Jupyter notebook with the code for this article on GitHub." }, { "code": null, "e": 23583, "s": 23263, "text": "V. Pérez-Rosas, B. Kleinberg, A. Lefevre, R. Mihalcea, Automatic Detection of Fake News, (2018), arXiv.orgA. Bharadwaj, B. Ashar, P. Barbhaya, R. Bhatia, Z. Shaikh, Source-Based Fake News Classification using Machine Learning, (2020), International Journal of Innovative Research in Science, Engineering and Technology" }, { "code": null, "e": 23691, "s": 23583, "text": "V. Pérez-Rosas, B. Kleinberg, A. Lefevre, R. Mihalcea, Automatic Detection of Fake News, (2018), arXiv.org" } ]
Beginner’s Guide to Creating the SVD Recommender System | by Mayukh Bhattacharyya | Towards Data Science
Ever logged into Netflix and see they are suggesting you watch Gravity if you had spent the last night watching Interstellar? Or perhaps bought something on Amazon and saw they are recommending us products that we may be interested in? Or ever wondered how the online ad agencies show us ads based on our browsing habits? It all boils down something called a recommendation system which predicts what we may be interested in based on our and others’ history of interacting with products. As I promised, we’ll make a recommender system. And just so you don’t feel bad about yourself, we’ll make a pretty cool one too. We’ll make a collaborative filtering one using the SVD ( Singular Vector Decomposition ) technique; that’s quite a notch above the basic content-based recommender system. Collaborative filtering captures the underlying pattern of interests of like-minded users and uses the choices and preferences of similar users to suggest new items. So let’s get started. So what we’ll need is listed below. You most probably know and already have these if you are reading this. 1. python >= 2.72. pandas >= 0.173. numpy4. scipy For the unaware, pandas, numpy & scipy are python packages. These will make our life easy. You can install them using pip from terminal or command prompt. Google it if you don’t know how to. For example, the command below installs pandas package. $ pip install pandas We’ll definitely need a dataset to work on. We’ll use the famous Movielens dataset for making our recommendation system. Head over to http://grouplens.org/datasets/movielens/ and download the movielens100k dataset. The dataset contains about 100,000 ratings of different movies by different users. Let’s explore the dataset. Create a new script exploration.py and add the following code blocks. Note: Here we’ll be using separate scripts but you can very well use a single iPython notebook, that’s a lot more convenient. import pandas as pdimport numpy as npdata = pd.read_csv('movielens100k.csv')data['userId'] = data['userId'].astype('str')data['movieId'] = data['movieId'].astype('str')users = data['userId'].unique() #list of all usersmovies = data['movieId'].unique() #list of all moviesprint("Number of users", len(users))print("Number of movies", len(movies))print(data.head()) There you go! You will see there are 718 users and 8915 movies in the dataset. Number of users 718Number of movies 8915+----+----------+-----------+----------+-------------+| | userId | movieId | rating | timestamp ||----+----------+-----------+----------+-------------|| 0 | 1 | 1 | 5 | 847117005 || 1 | 1 | 2 | 3 | 847642142 || 2 | 1 | 10 | 3 | 847641896 || 3 | 1 | 32 | 4 | 847642008 || 4 | 1 | 34 | 4 | 847641956 |+----+----------+-----------+----------+-------------+ We could have used the normal random train-test split on the dataset. But since we have the timestamps available, let’s do something fancy and better. Let’s make a new script workspace.py where we’ll do all our work. Add the following code at the start. import pandas as pdimport numpy as npimport scipydata = pd.read_csv('movielens100k.csv')data['userId'] = data['userId'].astype('str')data['movieId'] = data['movieId'].astype('str')users = data['userId'].unique() #list of all usersmovies = data['movieId'].unique() #list of all moviestest = pd.DataFrame(columns=data.columns)train = pd.DataFrame(columns=data.columns)test_ratio = 0.2 #fraction of data to be used as test set.for u in users: temp = data[data['userId'] == u] n = len(temp) test_size = int(test_ratio*n)temp = temp.sort_values('timestamp').reset_index()temp.drop('index', axis=1, inplace=True) dummy_test = temp.ix[n-1-test_size :]dummy_train = temp.ix[: n-2-test_size] test = pd.concat([test, dummy_test])train = pd.concat([train, dummy_train]) What this does is that based on the timestamps when these ratings were given, we sort the data to keep the more recent ratings towards the bottom and take 20% of ratings from every user starting from the bottom as the test set. So, instead of random selection, we take the recent ratings as the test set. This is more logical in the sense that the goal of recommenders is to rate un-encountered products in the future based on historical ratings of similar products. The dataset in the current form is of no use to us. In order to use the data for the recommender engine, we need to transform the dataset into a form called a utility matrix. We make a function create_utility_matrix in a new script. Name it recsys.py . We shall use the functions in this script to work on our train and test set. As a parameter, we pass a dictionary that stores the key-value pairs for each column of the dataset `data` that we are also passing. From the dataset, we’ll see the column number or column names for each of the corresponding fields, the column userId or column 0 for the key β€˜user’, column movieId or column 1 for key β€˜item’ and column ratings or column 2 for key β€˜value’. Utility Matrix is nothing but a 2D matrix where one axis belongs to the users and the other axis belongs to the items (movies in this case). So the value at (i,j) location of the matrix will be the rating that user i gave for movie j. Let’s give an example to clear up a bit more. Suppose we have this dataset of 5 ratings. +----+----------+-----------+----------+| | userId | movieId | rating ||----+----------+-----------+----------+| 0 | mark| movie1| 5 || 1 | lucy| movie2| 2 || 2 | mark| movie3| 3 || 3 | shane| movie2| 1 || 4 | lisa| movie3| 4 |+----+----------+-----------+----------+ If we pass this dataset through the create_utility_matrix function described below, it will return an utility matrix like this and auxiliary dictionaries of user_index and item_index as shown below. +----+----+----+| 5 | nan| 3 | # user_index = {mark: 0, lucy:1, shane:2, lisa:3}+----+----+----+ # item_index = {movie1:0, movie2: 1, movie3:2}| nan| 2 | nan|+----+----+----+| nan| 1 | nan| # The nan values are for user-item combinations+----+----+----+ # where the ratings are unavailable.| nan| nan| 4 |+----+----+----+ Let’s see the function now. import numpy as npimport pandas as pdfrom scipy.linalg import sqrtmdef create_utility_matrix(data, formatizer = {'user':0, 'item': 1, 'value': 2}): """ :param data: Array-like, 2D, nx3 :param formatizer:pass the formatizer :return: utility matrix (n x m), n=users, m=items """ itemField = formatizer['item'] userField = formatizer['user'] valueField = formatizer['value'] userList = data.ix[:,userField].tolist() itemList = data.ix[:,itemField].tolist() valueList = data.ix[:,valueField].tolist() users = list(set(data.ix[:,userField])) items = list(set(data.ix[:,itemField])) users_index = {users[i]: i for i in range(len(users))} pd_dict = {item: [np.nan for i in range(len(users))] for item in items} for i in range(0,len(data)): item = itemList[i] user = userList[i] value = valueList[i] pd_dict[item][users_index[user]] = value X = pd.DataFrame(pd_dict) X.index = users itemcols = list(X.columns) items_index = {itemcols[i]: i for i in range(len(itemcols))} # users_index gives us a mapping of user_id to index of user # items_index provides the same for items return X, users_index, items_index SVD is Singular Vector Decomposition. What it does is that it decomposes a matrix into constituent arrays of feature vectors corresponding to each row and each column. Let’s add another function to recsys.py. It will take the output from the `create_utility_matrix` and the parameter `k` which is the number of features into which each user and movie will be resolved into. The SVD technique was introduced into the recommendation system domain by Brandyn Webb, much more famously known as Simon Funk during the Netflix Prize challenge. Here we aren’t doing Funk’s iterative version of SVD or FunkSVD as it is called but instead using whatever numpy’s SVD implementation has to offer. def svd(train, k): utilMat = np.array(train) # the nan or unavailable entries are masked mask = np.isnan(utilMat) masked_arr = np.ma.masked_array(utilMat, mask) item_means = np.mean(masked_arr, axis=0) # nan entries will replaced by the average rating for each item utilMat = masked_arr.filled(item_means) x = np.tile(item_means, (utilMat.shape[0],1)) # we remove the per item average from all entries. # the above mentioned nan entries will be essentially zero now utilMat = utilMat - x # The magic happens here. U and V are user and item features U, s, V=np.linalg.svd(utilMat, full_matrices=False) s=np.diag(s) # we take only the k most significant features s=s[0:k,0:k] U=U[:,0:k] V=V[0:k,:] s_root=sqrtm(s) Usk=np.dot(U,s_root) skV=np.dot(s_root,V) UsV = np.dot(Usk, skV) UsV = UsV + x print("svd done") return UsV Back to workspace.py where we’ll use the functions above. We’ll find out the root mean square error of the predicted ratings for the test set using the true ratings. Besides making a function, we’ll also create a list to hold the different number of features which will help us to make an analysis for the future. from recsys import svd, create_utility_matrixdef rmse(true, pred): # this will be used towards the end x = true - pred return sum([xi*xi for xi in x])/len(x)# to test the performance over a different number of featuresno_of_features = [8,10,12,14,17]utilMat, users_index, items_index = create_utility_matrix(train)for f in no_of_features: svdout = svd(utilMat, k=f) pred = [] #to store the predicted ratings for _,row in test.iterrows(): user = row['userId'] item = row['movieId'] u_index = users_index[user] if item in items_index: i_index = items_index[item] pred_rating = svdout[u_index, i_index] else: pred_rating = np.mean(svdout[u_index, :]) pred.append(pred_rating)print(rmse(test['rating'], pred)) For test_size = 0.2 , the RMSE scores will be something around 0.96 This is a modest score for Movielens100k. With little tweaks, you perhaps can beat 0.945. But that’s up to you. If you like the article let me know! And here are 3 links for your perusal: https://github.com/mayukh18/reco (Complete codes of SVD as well as implementations of other famous RecSys algorithms)https://paperswithcode.com/sota/collaborative-filtering-on-movielens-100k ( State of the Art results on Movielens100k. These are validated on the official test set)https://sifter.org/~simon/journal/20061211.html (Most famous blog of Simon Funk detailing his SVD approach) https://github.com/mayukh18/reco (Complete codes of SVD as well as implementations of other famous RecSys algorithms) https://paperswithcode.com/sota/collaborative-filtering-on-movielens-100k ( State of the Art results on Movielens100k. These are validated on the official test set) https://sifter.org/~simon/journal/20061211.html (Most famous blog of Simon Funk detailing his SVD approach)
[ { "code": null, "e": 660, "s": 172, "text": "Ever logged into Netflix and see they are suggesting you watch Gravity if you had spent the last night watching Interstellar? Or perhaps bought something on Amazon and saw they are recommending us products that we may be interested in? Or ever wondered how the online ad agencies show us ads based on our browsing habits? It all boils down something called a recommendation system which predicts what we may be interested in based on our and others’ history of interacting with products." }, { "code": null, "e": 960, "s": 660, "text": "As I promised, we’ll make a recommender system. And just so you don’t feel bad about yourself, we’ll make a pretty cool one too. We’ll make a collaborative filtering one using the SVD ( Singular Vector Decomposition ) technique; that’s quite a notch above the basic content-based recommender system." }, { "code": null, "e": 1126, "s": 960, "text": "Collaborative filtering captures the underlying pattern of interests of like-minded users and uses the choices and preferences of similar users to suggest new items." }, { "code": null, "e": 1255, "s": 1126, "text": "So let’s get started. So what we’ll need is listed below. You most probably know and already have these if you are reading this." }, { "code": null, "e": 1305, "s": 1255, "text": "1. python >= 2.72. pandas >= 0.173. numpy4. scipy" }, { "code": null, "e": 1552, "s": 1305, "text": "For the unaware, pandas, numpy & scipy are python packages. These will make our life easy. You can install them using pip from terminal or command prompt. Google it if you don’t know how to. For example, the command below installs pandas package." }, { "code": null, "e": 1573, "s": 1552, "text": "$ pip install pandas" }, { "code": null, "e": 1788, "s": 1573, "text": "We’ll definitely need a dataset to work on. We’ll use the famous Movielens dataset for making our recommendation system. Head over to http://grouplens.org/datasets/movielens/ and download the movielens100k dataset." }, { "code": null, "e": 2094, "s": 1788, "text": "The dataset contains about 100,000 ratings of different movies by different users. Let’s explore the dataset. Create a new script exploration.py and add the following code blocks. Note: Here we’ll be using separate scripts but you can very well use a single iPython notebook, that’s a lot more convenient." }, { "code": null, "e": 2458, "s": 2094, "text": "import pandas as pdimport numpy as npdata = pd.read_csv('movielens100k.csv')data['userId'] = data['userId'].astype('str')data['movieId'] = data['movieId'].astype('str')users = data['userId'].unique() #list of all usersmovies = data['movieId'].unique() #list of all moviesprint(\"Number of users\", len(users))print(\"Number of movies\", len(movies))print(data.head())" }, { "code": null, "e": 2537, "s": 2458, "text": "There you go! You will see there are 718 users and 8915 movies in the dataset." }, { "code": null, "e": 3064, "s": 2537, "text": "Number of users 718Number of movies 8915+----+----------+-----------+----------+-------------+| | userId | movieId | rating | timestamp ||----+----------+-----------+----------+-------------|| 0 | 1 | 1 | 5 | 847117005 || 1 | 1 | 2 | 3 | 847642142 || 2 | 1 | 10 | 3 | 847641896 || 3 | 1 | 32 | 4 | 847642008 || 4 | 1 | 34 | 4 | 847641956 |+----+----------+-----------+----------+-------------+" }, { "code": null, "e": 3318, "s": 3064, "text": "We could have used the normal random train-test split on the dataset. But since we have the timestamps available, let’s do something fancy and better. Let’s make a new script workspace.py where we’ll do all our work. Add the following code at the start." }, { "code": null, "e": 4092, "s": 3318, "text": "import pandas as pdimport numpy as npimport scipydata = pd.read_csv('movielens100k.csv')data['userId'] = data['userId'].astype('str')data['movieId'] = data['movieId'].astype('str')users = data['userId'].unique() #list of all usersmovies = data['movieId'].unique() #list of all moviestest = pd.DataFrame(columns=data.columns)train = pd.DataFrame(columns=data.columns)test_ratio = 0.2 #fraction of data to be used as test set.for u in users: temp = data[data['userId'] == u] n = len(temp) test_size = int(test_ratio*n)temp = temp.sort_values('timestamp').reset_index()temp.drop('index', axis=1, inplace=True) dummy_test = temp.ix[n-1-test_size :]dummy_train = temp.ix[: n-2-test_size] test = pd.concat([test, dummy_test])train = pd.concat([train, dummy_train])" }, { "code": null, "e": 4559, "s": 4092, "text": "What this does is that based on the timestamps when these ratings were given, we sort the data to keep the more recent ratings towards the bottom and take 20% of ratings from every user starting from the bottom as the test set. So, instead of random selection, we take the recent ratings as the test set. This is more logical in the sense that the goal of recommenders is to rate un-encountered products in the future based on historical ratings of similar products." }, { "code": null, "e": 4889, "s": 4559, "text": "The dataset in the current form is of no use to us. In order to use the data for the recommender engine, we need to transform the dataset into a form called a utility matrix. We make a function create_utility_matrix in a new script. Name it recsys.py . We shall use the functions in this script to work on our train and test set." }, { "code": null, "e": 5262, "s": 4889, "text": "As a parameter, we pass a dictionary that stores the key-value pairs for each column of the dataset `data` that we are also passing. From the dataset, we’ll see the column number or column names for each of the corresponding fields, the column userId or column 0 for the key β€˜user’, column movieId or column 1 for key β€˜item’ and column ratings or column 2 for key β€˜value’." }, { "code": null, "e": 5497, "s": 5262, "text": "Utility Matrix is nothing but a 2D matrix where one axis belongs to the users and the other axis belongs to the items (movies in this case). So the value at (i,j) location of the matrix will be the rating that user i gave for movie j." }, { "code": null, "e": 5586, "s": 5497, "text": "Let’s give an example to clear up a bit more. Suppose we have this dataset of 5 ratings." }, { "code": null, "e": 5947, "s": 5586, "text": "+----+----------+-----------+----------+| | userId | movieId | rating ||----+----------+-----------+----------+| 0 | mark| movie1| 5 || 1 | lucy| movie2| 2 || 2 | mark| movie3| 3 || 3 | shane| movie2| 1 || 4 | lisa| movie3| 4 |+----+----------+-----------+----------+" }, { "code": null, "e": 6146, "s": 5947, "text": "If we pass this dataset through the create_utility_matrix function described below, it will return an utility matrix like this and auxiliary dictionaries of user_index and item_index as shown below." }, { "code": null, "e": 6481, "s": 6146, "text": "+----+----+----+| 5 | nan| 3 | # user_index = {mark: 0, lucy:1, shane:2, lisa:3}+----+----+----+ # item_index = {movie1:0, movie2: 1, movie3:2}| nan| 2 | nan|+----+----+----+| nan| 1 | nan| # The nan values are for user-item combinations+----+----+----+ # where the ratings are unavailable.| nan| nan| 4 |+----+----+----+" }, { "code": null, "e": 6509, "s": 6481, "text": "Let’s see the function now." }, { "code": null, "e": 7745, "s": 6509, "text": "import numpy as npimport pandas as pdfrom scipy.linalg import sqrtmdef create_utility_matrix(data, formatizer = {'user':0, 'item': 1, 'value': 2}): \"\"\" :param data: Array-like, 2D, nx3 :param formatizer:pass the formatizer :return: utility matrix (n x m), n=users, m=items \"\"\" itemField = formatizer['item'] userField = formatizer['user'] valueField = formatizer['value'] userList = data.ix[:,userField].tolist() itemList = data.ix[:,itemField].tolist() valueList = data.ix[:,valueField].tolist() users = list(set(data.ix[:,userField])) items = list(set(data.ix[:,itemField])) users_index = {users[i]: i for i in range(len(users))} pd_dict = {item: [np.nan for i in range(len(users))] for item in items} for i in range(0,len(data)): item = itemList[i] user = userList[i] value = valueList[i] pd_dict[item][users_index[user]] = value X = pd.DataFrame(pd_dict) X.index = users itemcols = list(X.columns) items_index = {itemcols[i]: i for i in range(len(itemcols))} # users_index gives us a mapping of user_id to index of user # items_index provides the same for items return X, users_index, items_index" }, { "code": null, "e": 8119, "s": 7745, "text": "SVD is Singular Vector Decomposition. What it does is that it decomposes a matrix into constituent arrays of feature vectors corresponding to each row and each column. Let’s add another function to recsys.py. It will take the output from the `create_utility_matrix` and the parameter `k` which is the number of features into which each user and movie will be resolved into." }, { "code": null, "e": 8430, "s": 8119, "text": "The SVD technique was introduced into the recommendation system domain by Brandyn Webb, much more famously known as Simon Funk during the Netflix Prize challenge. Here we aren’t doing Funk’s iterative version of SVD or FunkSVD as it is called but instead using whatever numpy’s SVD implementation has to offer." }, { "code": null, "e": 9325, "s": 8430, "text": "def svd(train, k): utilMat = np.array(train) # the nan or unavailable entries are masked mask = np.isnan(utilMat) masked_arr = np.ma.masked_array(utilMat, mask) item_means = np.mean(masked_arr, axis=0) # nan entries will replaced by the average rating for each item utilMat = masked_arr.filled(item_means) x = np.tile(item_means, (utilMat.shape[0],1)) # we remove the per item average from all entries. # the above mentioned nan entries will be essentially zero now utilMat = utilMat - x # The magic happens here. U and V are user and item features U, s, V=np.linalg.svd(utilMat, full_matrices=False) s=np.diag(s) # we take only the k most significant features s=s[0:k,0:k] U=U[:,0:k] V=V[0:k,:] s_root=sqrtm(s) Usk=np.dot(U,s_root) skV=np.dot(s_root,V) UsV = np.dot(Usk, skV) UsV = UsV + x print(\"svd done\") return UsV" }, { "code": null, "e": 9639, "s": 9325, "text": "Back to workspace.py where we’ll use the functions above. We’ll find out the root mean square error of the predicted ratings for the test set using the true ratings. Besides making a function, we’ll also create a list to hold the different number of features which will help us to make an analysis for the future." }, { "code": null, "e": 10439, "s": 9639, "text": "from recsys import svd, create_utility_matrixdef rmse(true, pred): # this will be used towards the end x = true - pred return sum([xi*xi for xi in x])/len(x)# to test the performance over a different number of featuresno_of_features = [8,10,12,14,17]utilMat, users_index, items_index = create_utility_matrix(train)for f in no_of_features: svdout = svd(utilMat, k=f) pred = [] #to store the predicted ratings for _,row in test.iterrows(): user = row['userId'] item = row['movieId'] u_index = users_index[user] if item in items_index: i_index = items_index[item] pred_rating = svdout[u_index, i_index] else: pred_rating = np.mean(svdout[u_index, :]) pred.append(pred_rating)print(rmse(test['rating'], pred))" }, { "code": null, "e": 10507, "s": 10439, "text": "For test_size = 0.2 , the RMSE scores will be something around 0.96" }, { "code": null, "e": 10619, "s": 10507, "text": "This is a modest score for Movielens100k. With little tweaks, you perhaps can beat 0.945. But that’s up to you." }, { "code": null, "e": 10695, "s": 10619, "text": "If you like the article let me know! And here are 3 links for your perusal:" }, { "code": null, "e": 11084, "s": 10695, "text": "https://github.com/mayukh18/reco (Complete codes of SVD as well as implementations of other famous RecSys algorithms)https://paperswithcode.com/sota/collaborative-filtering-on-movielens-100k ( State of the Art results on Movielens100k. These are validated on the official test set)https://sifter.org/~simon/journal/20061211.html (Most famous blog of Simon Funk detailing his SVD approach)" }, { "code": null, "e": 11202, "s": 11084, "text": "https://github.com/mayukh18/reco (Complete codes of SVD as well as implementations of other famous RecSys algorithms)" }, { "code": null, "e": 11367, "s": 11202, "text": "https://paperswithcode.com/sota/collaborative-filtering-on-movielens-100k ( State of the Art results on Movielens100k. These are validated on the official test set)" } ]
How do I cast a type to a BigInt in MySQL?
You need to use the CAST operator along with CONV() function. The CONV() function can be used to convert one base number system to another base system. For Example, The 16 is one base system and 10 is another base system. The 16 base system is hexadecimal and 10 is a decimal. The syntax is as follows βˆ’ SELECT CAST(CONV('yourColumnName',16,10) AS UNSIGNED INTEGER) as anyAliasName FROM yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows βˆ’ mysql> create table castTypeToBigIntDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Value varchar(100), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.19 sec) Insert some records in the table using insert command. The query is as follows βˆ’ mysql> insert into castTypeToBigIntDemo(Value) values('AB5'); Query OK, 1 row affected (0.13 sec) mysql> insert into castTypeToBigIntDemo(Value) values('55244A5562C5566354'); Query OK, 1 row affected (0.15 sec) mysql> insert into castTypeToBigIntDemo(Value) values('4546575765ABD78'); Query OK, 1 row affected (0.15 sec) mysql> insert into castTypeToBigIntDemo(Value) values('5979787DEFAB'); Query OK, 1 row affected (0.19 sec) mysql> insert into castTypeToBigIntDemo(Value) values('86868686856ABD'); Query OK, 1 row affected (0.17 sec) Display all records from the table using a select statement. The query is as follows βˆ’ mysql> select *from castTypeToBigIntDemo; The following is the output βˆ’ +----+--------------------+ | Id | Value | +----+--------------------+ | 1 | AB5 | | 2 | 55244A5562C5566354 | | 3 | 4546575765ABD78 | | 4 | 5979787DEFAB | | 5 | 86868686856ABD | +----+--------------------+ 5 rows in set (0.00 sec) Here is the query to cast a type to a BigInt in MySQL βˆ’ mysql> SELECT CAST(CONV(Value,16,10) AS UNSIGNED INTEGER) as BigNumber from castTypeToBigIntDemo; The following is the output βˆ’ +----------------------+ | BigNumber | +----------------------+ | 2741 | | 18446744073709551615 | | 311985829366644088 | | 98378247434155 | | 37865559219858109 | +----------------------+ 5 rows in set, 1 warning (0.00 sec)
[ { "code": null, "e": 1214, "s": 1062, "text": "You need to use the CAST operator along with CONV() function. The CONV() function can be used to convert one base number system to another base system." }, { "code": null, "e": 1339, "s": 1214, "text": "For Example, The 16 is one base system and 10 is another base system. The 16 base system is hexadecimal and 10 is a decimal." }, { "code": null, "e": 1366, "s": 1339, "text": "The syntax is as follows βˆ’" }, { "code": null, "e": 1464, "s": 1366, "text": "SELECT CAST(CONV('yourColumnName',16,10) AS UNSIGNED INTEGER) as anyAliasName FROM yourTableName;" }, { "code": null, "e": 1563, "s": 1464, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows βˆ’" }, { "code": null, "e": 1746, "s": 1563, "text": "mysql> create table castTypeToBigIntDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT, \n -> Value varchar(100),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (1.19 sec)" }, { "code": null, "e": 1827, "s": 1746, "text": "Insert some records in the table using insert command. The query is as follows βˆ’" }, { "code": null, "e": 2364, "s": 1827, "text": "mysql> insert into castTypeToBigIntDemo(Value) values('AB5');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into castTypeToBigIntDemo(Value) values('55244A5562C5566354');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into castTypeToBigIntDemo(Value) values('4546575765ABD78');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into castTypeToBigIntDemo(Value) values('5979787DEFAB');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into castTypeToBigIntDemo(Value) values('86868686856ABD');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2451, "s": 2364, "text": "Display all records from the table using a select statement. The query is as follows βˆ’" }, { "code": null, "e": 2493, "s": 2451, "text": "mysql> select *from castTypeToBigIntDemo;" }, { "code": null, "e": 2523, "s": 2493, "text": "The following is the output βˆ’" }, { "code": null, "e": 2800, "s": 2523, "text": "+----+--------------------+\n| Id | Value |\n+----+--------------------+\n| 1 | AB5 |\n| 2 | 55244A5562C5566354 |\n| 3 | 4546575765ABD78 |\n| 4 | 5979787DEFAB |\n| 5 | 86868686856ABD |\n+----+--------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2856, "s": 2800, "text": "Here is the query to cast a type to a BigInt in MySQL βˆ’" }, { "code": null, "e": 2954, "s": 2856, "text": "mysql> SELECT CAST(CONV(Value,16,10) AS UNSIGNED INTEGER) as BigNumber from castTypeToBigIntDemo;" }, { "code": null, "e": 2984, "s": 2954, "text": "The following is the output βˆ’" }, { "code": null, "e": 3245, "s": 2984, "text": "+----------------------+\n| BigNumber |\n+----------------------+\n| 2741 |\n| 18446744073709551615 |\n| 311985829366644088 |\n| 98378247434155 |\n| 37865559219858109 |\n+----------------------+\n5 rows in set, 1 warning (0.00 sec)" } ]
Hot Standby Router Protocol (HSRP) - GeeksforGeeks
25 Oct, 2021 Hot Standby Router Protocol (HSRP) is a CISCO proprietary protocol, which provides redundancy for a local subnet. In HSRP, two or more routers gives an illusion of a virtual router. HSRP allows you to configure two or more routers as standby routers and only a single router as an active router at a time. All the routers in a single HSRP group shares a single MAC address and IP address, which acts as a default gateway to the local network. The Active router is responsible for forwarding the traffic. If it fails, the Standby router takes up all the responsibilities of the active router and forwards the traffic. Virtual IP : IP address from local subnet is assigned as default gateway to all local hosts in the network.Virtual MAC address : MAC address is generated automatically by HSRP. The first 24 bits will be default CISCO address (i.e. 0000.0c). The next 16 bits are HSRP ID (i.e. 07.ac). The next 8 bits will be the group number in hexadecimal. e.g- if the group number is 10 then the last 8 bits will be 0a. Example of virtual MAC address –0000.0c07.ac0aHello messages : Periodic messages exchanged by active and standby routers. These messages are exchanged after every 3 seconds telling the state of router.Hold down timer : Its default value is 10 seconds i.e roughly 3 times the value of hello message. This timer tells us about the router that how much time will the standby router waits for hello message if it is not received on time.Note : If the active router fails then the standby router will become the active router.Priority : By default, the priority value is 100. It is helpful when the active router comes back after falling down, we can change the priority of standby router (which has become the active router after the original active router is down) to less than 100 therefore it again becomes standby router.Note : The router having higher priority will become the active router.Preempt : It is a state in which the standby router automatically becomes the active router. Virtual IP : IP address from local subnet is assigned as default gateway to all local hosts in the network. Virtual MAC address : MAC address is generated automatically by HSRP. The first 24 bits will be default CISCO address (i.e. 0000.0c). The next 16 bits are HSRP ID (i.e. 07.ac). The next 8 bits will be the group number in hexadecimal. e.g- if the group number is 10 then the last 8 bits will be 0a. Example of virtual MAC address –0000.0c07.ac0a 0000.0c07.ac0a Hello messages : Periodic messages exchanged by active and standby routers. These messages are exchanged after every 3 seconds telling the state of router. Hold down timer : Its default value is 10 seconds i.e roughly 3 times the value of hello message. This timer tells us about the router that how much time will the standby router waits for hello message if it is not received on time.Note : If the active router fails then the standby router will become the active router. Note : If the active router fails then the standby router will become the active router. Priority : By default, the priority value is 100. It is helpful when the active router comes back after falling down, we can change the priority of standby router (which has become the active router after the original active router is down) to less than 100 therefore it again becomes standby router.Note : The router having higher priority will become the active router. Note : The router having higher priority will become the active router. Preempt : It is a state in which the standby router automatically becomes the active router. Members having same group ID are the members of same group. One of the member of the group will be elected as the active router while others remain as standby routers. The virtual IP is configured as default gateway of all the hosts in the local subnet and the active router is responsible for forwarding the traffic of local hosts. If the active router goes down then the hello messages are not exchanged between the active and the standby routers therefore the standby router waits until the hold-down timer time. As soon as the hold down time is finished, the standby router will become the active router and take up all the responsibilities of active router. This is known as preempt.If in case the original active router comes back then we can decrease the priority of the standby router so that it will become the standby router again. version 1 : The messages are multicast at 224.0.0.2 and uses the UDP port 1985. This version allows group number range from 0 to 255.version 2 : The messages are multicast at 224.0.0.102 and uses the UDP port 1985. This version allows group number range from 0 to 4095. Consider above given topology. There are 2 routers named R1 and R2. IP address of R1 (f 0/0) is 10.1.1.1/24 and R2 (f 0/0) is 10.1.1.2/24. Assigning IP address to router R1. r1#(config) int fa0/0 r1#(config-if)ip add 10.1.1.1 255.255.255.0 Assigning IP address to router R2. r2#(config) int fa0/0 r2#(config-if)ip address 10.1.1.2 255.255.255.0 Now, Let’s provide virtual IP address (10.1.1.100), group name HSRP_TEST, group number 1and priority 110. Also, preempt has been enabled i.e. if the active router goes down then the standby router automatically becomes the active router. r1#(config-if) standby 1 ip 10.1.1.100 r1#(config-if) standby 1 name HSRP_TEST r1#(config-if) standby 1 priority 110 r1#(config-if) standby 1 preempt Now, we will provide virtual IP address (10.1.1.100), group name HSRP_TEST and priority 100. Also, group number 1 and preempt has been enabled. r2#(config) int fa0/0 r2#(config-if) standby 1 ip 10.1.1.100 r2#(config-if) standby 1 name HSRP_TEST r2#(config-if) standby 1 priority 100 r2#(config-if) standby 1 preempt Note : As we have provided priority 110 to r1, therefore it will become the active router. saurabhsharma56 vaibhavsinghtanwar Computer Networks-Network Layer Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Caesar Cipher in Cryptography Socket Programming in Python UDP Server-Client implementation in C Differences between IPv4 and IPv6 Socket Programming in Java Advanced Encryption Standard (AES) Intrusion Detection System (IDS) GSM in Wireless Communication Simple Chat Room using Python Cryptography and its Types
[ { "code": null, "e": 36568, "s": 36540, "text": "\n25 Oct, 2021" }, { "code": null, "e": 36750, "s": 36568, "text": "Hot Standby Router Protocol (HSRP) is a CISCO proprietary protocol, which provides redundancy for a local subnet. In HSRP, two or more routers gives an illusion of a virtual router." }, { "code": null, "e": 37185, "s": 36750, "text": "HSRP allows you to configure two or more routers as standby routers and only a single router as an active router at a time. All the routers in a single HSRP group shares a single MAC address and IP address, which acts as a default gateway to the local network. The Active router is responsible for forwarding the traffic. If it fails, the Standby router takes up all the responsibilities of the active router and forwards the traffic." }, { "code": null, "e": 38575, "s": 37185, "text": "Virtual IP : IP address from local subnet is assigned as default gateway to all local hosts in the network.Virtual MAC address : MAC address is generated automatically by HSRP. The first 24 bits will be default CISCO address (i.e. 0000.0c). The next 16 bits are HSRP ID (i.e. 07.ac). The next 8 bits will be the group number in hexadecimal. e.g- if the group number is 10 then the last 8 bits will be 0a. Example of virtual MAC address –0000.0c07.ac0aHello messages : Periodic messages exchanged by active and standby routers. These messages are exchanged after every 3 seconds telling the state of router.Hold down timer : Its default value is 10 seconds i.e roughly 3 times the value of hello message. This timer tells us about the router that how much time will the standby router waits for hello message if it is not received on time.Note : If the active router fails then the standby router will become the active router.Priority : By default, the priority value is 100. It is helpful when the active router comes back after falling down, we can change the priority of standby router (which has become the active router after the original active router is down) to less than 100 therefore it again becomes standby router.Note : The router having higher priority will become the active router.Preempt : It is a state in which the standby router automatically becomes the active router." }, { "code": null, "e": 38683, "s": 38575, "text": "Virtual IP : IP address from local subnet is assigned as default gateway to all local hosts in the network." }, { "code": null, "e": 39028, "s": 38683, "text": "Virtual MAC address : MAC address is generated automatically by HSRP. The first 24 bits will be default CISCO address (i.e. 0000.0c). The next 16 bits are HSRP ID (i.e. 07.ac). The next 8 bits will be the group number in hexadecimal. e.g- if the group number is 10 then the last 8 bits will be 0a. Example of virtual MAC address –0000.0c07.ac0a" }, { "code": null, "e": 39043, "s": 39028, "text": "0000.0c07.ac0a" }, { "code": null, "e": 39199, "s": 39043, "text": "Hello messages : Periodic messages exchanged by active and standby routers. These messages are exchanged after every 3 seconds telling the state of router." }, { "code": null, "e": 39520, "s": 39199, "text": "Hold down timer : Its default value is 10 seconds i.e roughly 3 times the value of hello message. This timer tells us about the router that how much time will the standby router waits for hello message if it is not received on time.Note : If the active router fails then the standby router will become the active router." }, { "code": null, "e": 39609, "s": 39520, "text": "Note : If the active router fails then the standby router will become the active router." }, { "code": null, "e": 39981, "s": 39609, "text": "Priority : By default, the priority value is 100. It is helpful when the active router comes back after falling down, we can change the priority of standby router (which has become the active router after the original active router is down) to less than 100 therefore it again becomes standby router.Note : The router having higher priority will become the active router." }, { "code": null, "e": 40053, "s": 39981, "text": "Note : The router having higher priority will become the active router." }, { "code": null, "e": 40146, "s": 40053, "text": "Preempt : It is a state in which the standby router automatically becomes the active router." }, { "code": null, "e": 40988, "s": 40146, "text": "Members having same group ID are the members of same group. One of the member of the group will be elected as the active router while others remain as standby routers. The virtual IP is configured as default gateway of all the hosts in the local subnet and the active router is responsible for forwarding the traffic of local hosts. If the active router goes down then the hello messages are not exchanged between the active and the standby routers therefore the standby router waits until the hold-down timer time. As soon as the hold down time is finished, the standby router will become the active router and take up all the responsibilities of active router. This is known as preempt.If in case the original active router comes back then we can decrease the priority of the standby router so that it will become the standby router again." }, { "code": null, "e": 41258, "s": 40988, "text": "version 1 : The messages are multicast at 224.0.0.2 and uses the UDP port 1985. This version allows group number range from 0 to 255.version 2 : The messages are multicast at 224.0.0.102 and uses the UDP port 1985. This version allows group number range from 0 to 4095." }, { "code": null, "e": 41397, "s": 41258, "text": "Consider above given topology. There are 2 routers named R1 and R2. IP address of R1 (f 0/0) is 10.1.1.1/24 and R2 (f 0/0) is 10.1.1.2/24." }, { "code": null, "e": 41432, "s": 41397, "text": "Assigning IP address to router R1." }, { "code": null, "e": 41498, "s": 41432, "text": "r1#(config) int fa0/0\nr1#(config-if)ip add 10.1.1.1 255.255.255.0" }, { "code": null, "e": 41533, "s": 41498, "text": "Assigning IP address to router R2." }, { "code": null, "e": 41603, "s": 41533, "text": "r2#(config) int fa0/0\nr2#(config-if)ip address 10.1.1.2 255.255.255.0" }, { "code": null, "e": 41841, "s": 41603, "text": "Now, Let’s provide virtual IP address (10.1.1.100), group name HSRP_TEST, group number 1and priority 110. Also, preempt has been enabled i.e. if the active router goes down then the standby router automatically becomes the active router." }, { "code": null, "e": 41991, "s": 41841, "text": "r1#(config-if) standby 1 ip 10.1.1.100\nr1#(config-if) standby 1 name HSRP_TEST\nr1#(config-if) standby 1 priority 110\nr1#(config-if) standby 1 preempt" }, { "code": null, "e": 42135, "s": 41991, "text": "Now, we will provide virtual IP address (10.1.1.100), group name HSRP_TEST and priority 100. Also, group number 1 and preempt has been enabled." }, { "code": null, "e": 42307, "s": 42135, "text": "r2#(config) int fa0/0\nr2#(config-if) standby 1 ip 10.1.1.100\nr2#(config-if) standby 1 name HSRP_TEST\nr2#(config-if) standby 1 priority 100\nr2#(config-if) standby 1 preempt" }, { "code": null, "e": 42398, "s": 42307, "text": "Note : As we have provided priority 110 to r1, therefore it will become the active router." }, { "code": null, "e": 42414, "s": 42398, "text": "saurabhsharma56" }, { "code": null, "e": 42433, "s": 42414, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 42465, "s": 42433, "text": "Computer Networks-Network Layer" }, { "code": null, "e": 42483, "s": 42465, "text": "Computer Networks" }, { "code": null, "e": 42501, "s": 42483, "text": "Computer Networks" }, { "code": null, "e": 42599, "s": 42501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42629, "s": 42599, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 42658, "s": 42629, "text": "Socket Programming in Python" }, { "code": null, "e": 42696, "s": 42658, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 42730, "s": 42696, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 42757, "s": 42730, "text": "Socket Programming in Java" }, { "code": null, "e": 42792, "s": 42757, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 42825, "s": 42792, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 42855, "s": 42825, "text": "GSM in Wireless Communication" }, { "code": null, "e": 42885, "s": 42855, "text": "Simple Chat Room using Python" } ]
EmberJS - Template Condition Unless
It executes only false block of statements. {{#unless falsy_condition}} //block of statement {{/unless}} The example given below shows the use of the unless conditional helper in the Ember.js. Create a template called application.hbs under app/templates/ with the following code βˆ’ {{#unless check}} <h3> boolean value is {{check}}</h3> {{/unless}} Now create the controller called application.js file, which will be defined under app/controller/ with the following code βˆ’ import Ember from 'ember'; export default Ember.Controller.extend ({ bool: false, check: function () { return this.bool; }.property('content.check') }); Run the ember server and you will receive the following output βˆ’ Print Add Notes Bookmark this page
[ { "code": null, "e": 1942, "s": 1898, "text": "It executes only false block of statements." }, { "code": null, "e": 2007, "s": 1942, "text": "{{#unless falsy_condition}}\n //block of statement\n{{/unless}}\n" }, { "code": null, "e": 2183, "s": 2007, "text": "The example given below shows the use of the unless conditional helper in the Ember.js. Create a template called application.hbs under app/templates/ with the following code βˆ’" }, { "code": null, "e": 2253, "s": 2183, "text": "{{#unless check}}\n <h3> boolean value is {{check}}</h3>\n{{/unless}}" }, { "code": null, "e": 2377, "s": 2253, "text": "Now create the controller called application.js file, which will be defined under app/controller/ with the following code βˆ’" }, { "code": null, "e": 2546, "s": 2377, "text": "import Ember from 'ember';\n\nexport default Ember.Controller.extend ({\n bool: false,\n check: function () {\n return this.bool;\n }.property('content.check')\n});" }, { "code": null, "e": 2611, "s": 2546, "text": "Run the ember server and you will receive the following output βˆ’" }, { "code": null, "e": 2618, "s": 2611, "text": " Print" }, { "code": null, "e": 2629, "s": 2618, "text": " Add Notes" } ]
D3.js - Drawing Charts
D3.js is used to create a static SVG chart. It helps to draw the following charts βˆ’ Bar Chart Circle Chart Pie Chart Donut Chart Line Chart Bubble Chart, etc. This chapter explains about drawing charts in D3. Let us understand each of these in detail. Bar charts are one of the most commonly used types of graph and are used to display and compare the number, frequency or other measure (e.g. mean) for different discrete categories or groups. This graph is constructed in such a way that the heights or lengths of the different bars are proportional to the size of the category they represent. The x-axis (the horizontal axis) represents the different categories it has no scale. The y axis (the vertical axis) does have a scale and this indicates the units of measurement. The bars can be drawn either vertically or horizontally depending upon the number of categories and length or complexity of the category. Let us create a bar chart in SVG using D3. For this example, we can use the rect elements for the bars and text elements to display our data values corresponding to the bars. To create a bar chart in SVG using D3, let us follow the steps given below. Step 1 βˆ’ Adding style in the rect element βˆ’ Let us add the following style to the rect element. svg rect { fill: gray; } Step 2 βˆ’ Add styles in text element βˆ’ Add the following CSS class to apply styles to text values. Add this style to SVG text element. It is defined below βˆ’ svg text { fill: yellow; font: 12px sans-serif; text-anchor: end; } Here, Fill is used to apply colors. Text-anchor is used to position the text towards the right end of the bars. Step 3 βˆ’ Define variables βˆ’ Let us add the variables in the script. It is explained below. <script> var data = [10, 5, 12, 15]; var width = 300, scaleFactor = 20, barHeight = 30; </script> Here, Width βˆ’ Width of the SVG. Width βˆ’ Width of the SVG. Scalefactor βˆ’ Scaled to a pixel value that is visible on the screen. Scalefactor βˆ’ Scaled to a pixel value that is visible on the screen. Barheight βˆ’ This is the static height of the horizontal bars. Barheight βˆ’ This is the static height of the horizontal bars. Step 4 βˆ’ Append SVG elements βˆ’ Let us append SVG elements in D3 using the following code. var graph = d3.select("body") .append("svg") .attr("width", width) .attr("height", barHeight * data.length); Here, we will first select the document body, create a new SVG element and then append it. We will build our bar graph inside this SVG element. Then, set the width and height of SVG. Height is calculated as bar height * number of data values. We have taken the bar height as 30 and data array length is 4. Then SVG height is calculated as barheight* datalength which is 120 px. Step 5 βˆ’ Apply transformation βˆ’ Let us apply the transformation in bar using the following code. var bar = graph.selectAll("g") .data(data) .enter() .append("g") .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; }); Here, each bar inside corresponds with an element. Therefore, we create group elements. Each of our group elements needs to be positioned one below the other to build a horizontal bar chart. Let us take a transformation formula index * bar height. Step 6 βˆ’ Append rect elements to the bar βˆ’ In the previous step, we appended group elements. Now add the rect elements to the bar using the following code. bar.append("rect") .attr("width", function(d) { return d * scaleFactor; }) .attr("height", barHeight - 1); Here, the width is (data value * scale factor) and height is (bar height - margin). Step 7 βˆ’ Display data βˆ’ This is the last step. Let us display the data on each bar using the following code. bar.append("text") .attr("x", function(d) { return (d*scaleFactor); }) .attr("y", barHeight / 2) .attr("dy", ".35em") .text(function(d) { return d; }); Here, width is defined as (data value * scalefactor). Text elements do not support padding or margin. For this reason, we need to give it a β€œdy” offset. This is used to align the text vertically. Step 8 βˆ’ Working example βˆ’ The complete code listing is shown in the following code block. Create a webpage barcharts.html and add the following changes. barcharts.html <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> <style> svg rect { fill: gray; } svg text { fill: yellow; font: 12px sans-serif; text-anchor: end; } </style> </head> <body> <script> var data = [10, 5, 12, 15]; var width = 300 scaleFactor = 20, barHeight = 30; var graph = d3.select("body") .append("svg") .attr("width", width) .attr("height", barHeight * data.length); var bar = graph.selectAll("g") .data(data) .enter() .append("g") .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; }); bar.append("rect").attr("width", function(d) { return d * scaleFactor; }) .attr("height", barHeight - 1); bar.append("text") .attr("x", function(d) { return (d*scaleFactor); }) .attr("y", barHeight / 2) .attr("dy", ".35em") .text(function(d) { return d; }); </script> </body> </html> Now request your browser, you will see the following response. A Circle chart is a circular statistical graphic, which is divided into slices to illustrate a numerical proportion. Let us create a circle chart in SVG using D3. To do this, we must adhere to the following steps βˆ’ Step 1 βˆ’ Define variables βˆ’ Let us add the variables in the script. It is shown in the code block below. <script> var width = 400; var height = 400; var data = [10, 20, 30]; var colors = ['green', 'purple', 'yellow']; </script> Here, Width βˆ’ width of the SVG. Width βˆ’ width of the SVG. Height βˆ’ height of the SVG. Height βˆ’ height of the SVG. Data βˆ’ array of data elements. Data βˆ’ array of data elements. Colors βˆ’ apply colors to the circle elements. Colors βˆ’ apply colors to the circle elements. Step 2 βˆ’ Append SVG elements βˆ’ Let us append SVG elements in D3 using the following code. var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); Step 3 βˆ’ Apply transformation βˆ’ Let us apply the transformation in SVG using the following code. var g = svg.selectAll("g") .data(data) .enter() .append("g") .attr("transform", function(d, i) { return "translate(0,0)"; }) Here, var g = svg.selectAll(β€œg”) βˆ’ Creates group element to hold the circles. .data(data) βˆ’ Binds our data array to the group elements. .enter() βˆ’ Creates placeholders for our group elements. .append(β€œg”) βˆ’ Appends group elements to our page. .attr("transform", function(d, i) { return "translate(0,0)"; }) Here, translate is used to position your elements with respect to the origin. Step 4 βˆ’ Append circle elements βˆ’ Now, append circle elements to the group using the following code. g.append("circle") Now, add the attributes to the group using the following code. .attr("cx", function(d, i) { return i*75 + 50; }) Here, we use the x-coordinate of the center of each circle. We are multiplying the index of the circle with 75 and adding a padding of 50 between the circles. Next, we set the y-coordinate of the center of each circle. This is used to uniform all the circles and it is defined below. .attr("cy", function(d, i) { return 75; }) Next, set the radius of each circle. It is defined below, .attr("r", function(d) { return d*1.5; }) Here, the radius is multiplied with data value along with a constant β€œ1.5” to increase the circle's size. Finally, fill colors for each circle using the following code. .attr("fill", function(d, i){ return colors[i]; }) Step 5 βˆ’ Display data βˆ’ This is the last step. Let us display the data on each circle using the following code. g.append("text") .attr("x", function(d, i) { return i * 75 + 25; }) .attr("y", 80) .attr("stroke", "teal") .attr("font-size", "10px") .attr("font-family", "sans-serif") .text(function(d) { return d; }); Step 6 βˆ’ Working Example βˆ’ The complete code listing is shown in the following code block. Create a webpage circlecharts.html and add the following changes in it. circlecharts.html <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <script> var width = 400; var height = 400; var data = [10, 20, 30]; var colors = ['green', 'purple', 'yellow']; var svg = d3 .select("body") .append("svg") .attr("width", width) .attr("height", height); var g = svg.selectAll("g") .data(data) .enter() .append("g") .attr("transform", function(d, i) { return "translate(0,0)"; }) g.append("circle").attr("cx", function(d, i) { return i*75 + 50; }) .attr("cy", function(d, i) { return 75; }) .attr("r", function(d) { return d*1.5; }) .attr("fill", function(d, i){ return colors[i]; }) g.append("text").attr("x", function(d, i) { return i * 75 + 25; }) .attr("y", 80) .attr("stroke", "teal") .attr("font-size", "10px") .attr("font-family", "sans-serif").text(function(d) { return d; }); </script> </body> </html> Now, request your browser and following will be the response. A pie chart is a circular statistical graph. It is divided into slices to show numerical proportion. Let us understand how to create a pie chart in D3. Before starting to draw a pie chart, we need to understand the following two methods βˆ’ The d3.arc() method and The d3.pie() method. Let us understand both of these methods in detail. The d3.arc() Method βˆ’ The d3.arc() method generates an arc. You need to set an inner radius and an outer radius for the arc. If the inner radius is 0, the result will be a pie chart, otherwise the result will be a donut chart, which is discussed in the next section. The d3.pie()Method βˆ’ The d3.pie() method is used to generate a pie chart. It takes a data from dataset and calculates the start angle and end angle for each wedge of the pie chart. Let us draw a pie chart using the following steps. Step 1 βˆ’ Applying styles βˆ’ Let us apply the following style to an arc element. .arc text { font: 12px arial; text-anchor: middle; } .arc path { stroke: #fff; } .title { fill: green; font-weight: italic; } Here, fill is used to apply colors. A text-anchor is used to position the text towards the center of an arc. Step 2 βˆ’ Define variables βˆ’ Define the variables in the script as shown below. <script> var svg = d3.select("svg"), width = svg.attr("width"), height = svg.attr("height"), radius = Math.min(width, height) / 2; </script> Here, Width βˆ’ Width of the SVG. Width βˆ’ Width of the SVG. Height βˆ’ Height of the SVG. Height βˆ’ Height of the SVG. Radius βˆ’ It can be calculated using the function of Math.min(width, height) / 2; Radius βˆ’ It can be calculated using the function of Math.min(width, height) / 2; Step 3 βˆ’ Apply Transformation βˆ’ Apply the following transformation in SVG using the following code. var g = svg.append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); Now add colors using the d3.scaleOrdinal function as given below. var color = d3.scaleOrdinal(['gray', 'green', 'brown', 'orange']); Step 4 βˆ’ Generate a pie chart βˆ’ Now, generate a pie chart using the function given below. var pie = d3.pie() .value(function(d) { return d.percent; }); Here, you can plot the percentage values. An anonymous function is required to return d.percent and set it as the pie value. Step 5 βˆ’ Define arcs for pie wedges βˆ’ After generating the pie chart, now define arc for each pie wedges using the function given below. var arc = d3.arc() .outerRadius(radius) .innerRadius(0); Here, this arc will be set to the path elements. The calculated radius is set to outerradius, while the innerradius is set to 0. Step 6 βˆ’ Add labels in wedges βˆ’ Add the labels in pie wedges by providing the radius. It is defined as follows. var label = d3 .arc() .outerRadius(radius) .innerRadius(radius - 80); Step 7 βˆ’ Read data βˆ’ This is an important step. We can read data using the function given below. d3.csv("populations.csv", function(error, data) { if (error) { throw error; } }); Here, populations.csv contains the data file. The d3.csv function reads data from the dataset. If data is not present, it throws an error. We can include this file in your D3 path. Step 8 βˆ’ Load data βˆ’ The next step is to load data using the following code. var arc = g.selectAll(".arc") .data(pie(data)) .enter() .append("g") .attr("class", "arc"); Here, we can assign data to group elements for each of the data values from the dataset. Step 9 βˆ’ Append path βˆ’ Now, append path and assign a class β€˜arc’ to groups as shown below. arcs.append("path") .attr("d", arc) .attr("fill", function(d) { return color(d.data.states); }); Here, fill is used to apply the data color. It is taken from the d3.scaleOrdinal function. Step 10 βˆ’ Append text βˆ’ To display the text in labels using the following code. arc.append("text") .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; }) .text(function(d) { return d.data.states; }); Here, SVG text element is used to display text in labels. The label arcs that we created earlier using d3.arc() returns a centroid point, which is a position for labels. Finally, we provide data using the d.data.browser. Step 11 βˆ’ Append group elements βˆ’ Append group elements attributes and add class title to color the text and make it italic, which is specified in Step 1 and is defined below. svg.append("g") .attr("transform", "translate(" + (width / 2 - 120) + "," + 20 + ")") .append("text") .text("Top population states in india") .attr("class", "title") Step 12 βˆ’ Working Example βˆ’ To draw a pie chart, we can take a dataset of Indian population. This dataset shows the population in a dummy website, which is defined as follows. population.csv states,percent UP,80.00 Maharastra,70.00 Bihar,65.0 MP,60.00 Gujarat,50.0 WB,49.0 TN,35.0 Let us create a pie chart visualization for the above dataset. Create a webpage β€œpiechart.html” and add the following code in it. <!DOCTYPE html> <html> <head> <style> .arc text { font: 12px arial; text-anchor: middle; } .arc path { stroke: #fff; } .title { fill: green; font-weight: italic; } </style> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <svg width = "400" height = "400"></svg> <script> var svg = d3.select("svg"), width = svg.attr("width"), height = svg.attr("height"), radius = Math.min(width, height) / 2; var g = svg.append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); var color = d3.scaleOrdinal([ 'gray', 'green', 'brown', 'orange', 'yellow', 'red', 'purple' ]); var pie = d3.pie().value(function(d) { return d.percent; }); var path = d3.arc() .outerRadius(radius - 10).innerRadius(0); var label = d3.arc() .outerRadius(radius).innerRadius(radius - 80); d3.csv("populations.csv", function(error, data) { if (error) { throw error; } var arc = g.selectAll(".arc") .data(pie(data)) .enter() .append("g") .attr("class", "arc"); arc.append("path") .attr("d", path) .attr("fill", function(d) { return color(d.data.states); }); console.log(arc) arc.append("text").attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; }) .text(function(d) { return d.data.states; }); }); svg.append("g") .attr("transform", "translate(" + (width / 2 - 120) + "," + 20 + ")") .append("text").text("Top population states in india") .attr("class", "title") </script> </body> </html> Print Add Notes Bookmark this page
[ { "code": null, "e": 2214, "s": 2130, "text": "D3.js is used to create a static SVG chart. It helps to draw the following charts βˆ’" }, { "code": null, "e": 2224, "s": 2214, "text": "Bar Chart" }, { "code": null, "e": 2237, "s": 2224, "text": "Circle Chart" }, { "code": null, "e": 2247, "s": 2237, "text": "Pie Chart" }, { "code": null, "e": 2259, "s": 2247, "text": "Donut Chart" }, { "code": null, "e": 2270, "s": 2259, "text": "Line Chart" }, { "code": null, "e": 2289, "s": 2270, "text": "Bubble Chart, etc." }, { "code": null, "e": 2382, "s": 2289, "text": "This chapter explains about drawing charts in D3. Let us understand each of these in detail." }, { "code": null, "e": 2725, "s": 2382, "text": "Bar charts are one of the most commonly used types of graph and are used to display and compare the number, frequency or other measure (e.g. mean) for different discrete categories or groups. This graph is constructed in such a way that the heights or lengths of the different bars are proportional to the size of the category they represent." }, { "code": null, "e": 3043, "s": 2725, "text": "The x-axis (the horizontal axis) represents the different categories it has no scale. The y axis (the vertical axis) does have a scale and this indicates the units of measurement. The bars can be drawn either vertically or horizontally depending upon the number of categories and length or complexity of the category." }, { "code": null, "e": 3219, "s": 3043, "text": "Let us create a bar chart in SVG using D3. For this example, we can use the rect elements for the bars and text elements to display our data values corresponding to the bars. " }, { "code": null, "e": 3295, "s": 3219, "text": "To create a bar chart in SVG using D3, let us follow the steps given below." }, { "code": null, "e": 3391, "s": 3295, "text": "Step 1 βˆ’ Adding style in the rect element βˆ’ Let us add the following style to the rect element." }, { "code": null, "e": 3419, "s": 3391, "text": "svg rect {\n fill: gray;\n}" }, { "code": null, "e": 3575, "s": 3419, "text": "Step 2 βˆ’ Add styles in text element βˆ’ Add the following CSS class to apply styles to text values. Add this style to SVG text element. It is defined below βˆ’" }, { "code": null, "e": 3652, "s": 3575, "text": "svg text {\n fill: yellow;\n font: 12px sans-serif;\n text-anchor: end;\n}" }, { "code": null, "e": 3764, "s": 3652, "text": "Here, Fill is used to apply colors. Text-anchor is used to position the text towards the right end of the bars." }, { "code": null, "e": 3855, "s": 3764, "text": "Step 3 βˆ’ Define variables βˆ’ Let us add the variables in the script. It is explained below." }, { "code": null, "e": 3971, "s": 3855, "text": "<script>\n var data = [10, 5, 12, 15];\n var width = 300,\n scaleFactor = 20,\n barHeight = 30;\n</script>" }, { "code": null, "e": 3977, "s": 3971, "text": "Here," }, { "code": null, "e": 4003, "s": 3977, "text": "Width βˆ’ Width of the SVG." }, { "code": null, "e": 4029, "s": 4003, "text": "Width βˆ’ Width of the SVG." }, { "code": null, "e": 4098, "s": 4029, "text": "Scalefactor βˆ’ Scaled to a pixel value that is visible on the screen." }, { "code": null, "e": 4167, "s": 4098, "text": "Scalefactor βˆ’ Scaled to a pixel value that is visible on the screen." }, { "code": null, "e": 4229, "s": 4167, "text": "Barheight βˆ’ This is the static height of the horizontal bars." }, { "code": null, "e": 4291, "s": 4229, "text": "Barheight βˆ’ This is the static height of the horizontal bars." }, { "code": null, "e": 4381, "s": 4291, "text": "Step 4 βˆ’ Append SVG elements βˆ’ Let us append SVG elements in D3 using the following code." }, { "code": null, "e": 4499, "s": 4381, "text": "var graph = d3.select(\"body\")\n .append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", barHeight * data.length);" }, { "code": null, "e": 4742, "s": 4499, "text": "Here, we will first select the document body, create a new SVG element and then append it. We will build our bar graph inside this SVG element. Then, set the width and height of SVG. Height is calculated as bar height * number of data values." }, { "code": null, "e": 4877, "s": 4742, "text": "We have taken the bar height as 30 and data array length is 4. Then SVG height is calculated as barheight* datalength which is 120 px." }, { "code": null, "e": 4974, "s": 4877, "text": "Step 5 βˆ’ Apply transformation βˆ’ Let us apply the transformation in bar using the following code." }, { "code": null, "e": 5146, "s": 4974, "text": "var bar = graph.selectAll(\"g\") \n .data(data)\n .enter()\n .append(\"g\")\n .attr(\"transform\", function(d, i) {\n return \"translate(0,\" + i * barHeight + \")\";\n });" }, { "code": null, "e": 5394, "s": 5146, "text": "Here, each bar inside corresponds with an element. Therefore, we create group elements. Each of our group elements needs to be positioned one below the other to build a horizontal bar chart. Let us take a transformation formula index * bar height." }, { "code": null, "e": 5550, "s": 5394, "text": "Step 6 βˆ’ Append rect elements to the bar βˆ’ In the previous step, we appended group elements. Now add the rect elements to the bar using the following code." }, { "code": null, "e": 5672, "s": 5550, "text": "bar.append(\"rect\")\n .attr(\"width\", function(d) {\n return d * scaleFactor;\n })\n .attr(\"height\", barHeight - 1);" }, { "code": null, "e": 5756, "s": 5672, "text": "Here, the width is (data value * scale factor) and height is (bar height - margin)." }, { "code": null, "e": 5865, "s": 5756, "text": "Step 7 βˆ’ Display data βˆ’ This is the last step. Let us display the data on each bar using the following code." }, { "code": null, "e": 6029, "s": 5865, "text": "bar.append(\"text\")\n .attr(\"x\", function(d) { return (d*scaleFactor); })\n .attr(\"y\", barHeight / 2)\n .attr(\"dy\", \".35em\")\n .text(function(d) { return d; });" }, { "code": null, "e": 6225, "s": 6029, "text": "Here, width is defined as (data value * scalefactor). Text elements do not support padding or margin. For this reason, we need to give it a β€œdy” offset. This is used to align the text vertically." }, { "code": null, "e": 6379, "s": 6225, "text": "Step 8 βˆ’ Working example βˆ’ The complete code listing is shown in the following code block. Create a webpage barcharts.html and add the following changes." }, { "code": null, "e": 6394, "s": 6379, "text": "barcharts.html" }, { "code": null, "e": 7700, "s": 6394, "text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n <style>\n svg rect {\n fill: gray;\n }\n \n svg text {\n fill: yellow;\n font: 12px sans-serif;\n text-anchor: end;\n }\n </style>\n </head>\n\n <body>\n <script>\n var data = [10, 5, 12, 15];\n \n var width = 300 \n scaleFactor = 20, \n barHeight = 30;\n \n var graph = d3.select(\"body\")\n .append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", barHeight * data.length);\n \n var bar = graph.selectAll(\"g\")\n .data(data)\n .enter()\n .append(\"g\")\n .attr(\"transform\", function(d, i) {\n return \"translate(0,\" + i * barHeight + \")\";\n });\n bar.append(\"rect\").attr(\"width\", function(d) {\n return d * scaleFactor;\n })\n \n .attr(\"height\", barHeight - 1);\n \n bar.append(\"text\")\n .attr(\"x\", function(d) { return (d*scaleFactor); })\n .attr(\"y\", barHeight / 2)\n .attr(\"dy\", \".35em\")\n .text(function(d) { return d; });\n </script>\n </body>\n</html>" }, { "code": null, "e": 7763, "s": 7700, "text": "Now request your browser, you will see the following response." }, { "code": null, "e": 7880, "s": 7763, "text": "A Circle chart is a circular statistical graphic, which is divided into slices to illustrate a numerical proportion." }, { "code": null, "e": 7978, "s": 7880, "text": "Let us create a circle chart in SVG using D3. To do this, we must adhere to the following steps βˆ’" }, { "code": null, "e": 8083, "s": 7978, "text": "Step 1 βˆ’ Define variables βˆ’ Let us add the variables in the script. It is shown in the code block below." }, { "code": null, "e": 8218, "s": 8083, "text": "<script>\n var width = 400;\n var height = 400;\n var data = [10, 20, 30];\n var colors = ['green', 'purple', 'yellow'];\n</script>" }, { "code": null, "e": 8224, "s": 8218, "text": "Here," }, { "code": null, "e": 8250, "s": 8224, "text": "Width βˆ’ width of the SVG." }, { "code": null, "e": 8276, "s": 8250, "text": "Width βˆ’ width of the SVG." }, { "code": null, "e": 8304, "s": 8276, "text": "Height βˆ’ height of the SVG." }, { "code": null, "e": 8332, "s": 8304, "text": "Height βˆ’ height of the SVG." }, { "code": null, "e": 8363, "s": 8332, "text": "Data βˆ’ array of data elements." }, { "code": null, "e": 8394, "s": 8363, "text": "Data βˆ’ array of data elements." }, { "code": null, "e": 8440, "s": 8394, "text": "Colors βˆ’ apply colors to the circle elements." }, { "code": null, "e": 8486, "s": 8440, "text": "Colors βˆ’ apply colors to the circle elements." }, { "code": null, "e": 8576, "s": 8486, "text": "Step 2 βˆ’ Append SVG elements βˆ’ Let us append SVG elements in D3 using the following code." }, { "code": null, "e": 8675, "s": 8576, "text": "var svg = d3.select(\"body\")\n .append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", height);" }, { "code": null, "e": 8772, "s": 8675, "text": "Step 3 βˆ’ Apply transformation βˆ’ Let us apply the transformation in SVG using the following code." }, { "code": null, "e": 8918, "s": 8772, "text": "var g = svg.selectAll(\"g\")\n .data(data)\n .enter()\n .append(\"g\")\n .attr(\"transform\", function(d, i) {\n return \"translate(0,0)\";\n })" }, { "code": null, "e": 8924, "s": 8918, "text": "Here," }, { "code": null, "e": 8996, "s": 8924, "text": "var g = svg.selectAll(β€œg”) βˆ’ Creates group element to hold the circles." }, { "code": null, "e": 9054, "s": 8996, "text": ".data(data) βˆ’ Binds our data array to the group elements." }, { "code": null, "e": 9110, "s": 9054, "text": ".enter() βˆ’ Creates placeholders for our group elements." }, { "code": null, "e": 9161, "s": 9110, "text": ".append(β€œg”) βˆ’ Appends group elements to our page." }, { "code": null, "e": 9228, "s": 9161, "text": ".attr(\"transform\", function(d, i) {\n return \"translate(0,0)\";\n})" }, { "code": null, "e": 9306, "s": 9228, "text": "Here, translate is used to position your elements with respect to the origin." }, { "code": null, "e": 9407, "s": 9306, "text": "Step 4 βˆ’ Append circle elements βˆ’ Now, append circle elements to the group using the following code." }, { "code": null, "e": 9426, "s": 9407, "text": "g.append(\"circle\")" }, { "code": null, "e": 9489, "s": 9426, "text": "Now, add the attributes to the group using the following code." }, { "code": null, "e": 9542, "s": 9489, "text": ".attr(\"cx\", function(d, i) {\n return i*75 + 50;\n})" }, { "code": null, "e": 9701, "s": 9542, "text": "Here, we use the x-coordinate of the center of each circle. We are multiplying the index of the circle with 75 and adding a padding of 50 between the circles." }, { "code": null, "e": 9826, "s": 9701, "text": "Next, we set the y-coordinate of the center of each circle. This is used to uniform all the circles and it is defined below." }, { "code": null, "e": 9872, "s": 9826, "text": ".attr(\"cy\", function(d, i) {\n return 75;\n})" }, { "code": null, "e": 9930, "s": 9872, "text": "Next, set the radius of each circle. It is defined below," }, { "code": null, "e": 9975, "s": 9930, "text": ".attr(\"r\", function(d) {\n return d*1.5;\n})" }, { "code": null, "e": 10144, "s": 9975, "text": "Here, the radius is multiplied with data value along with a constant β€œ1.5” to increase the circle's size. Finally, fill colors for each circle using the following code." }, { "code": null, "e": 10198, "s": 10144, "text": ".attr(\"fill\", function(d, i){\n return colors[i];\n})" }, { "code": null, "e": 10310, "s": 10198, "text": "Step 5 βˆ’ Display data βˆ’ This is the last step. Let us display the data on each circle using the following code." }, { "code": null, "e": 10549, "s": 10310, "text": "g.append(\"text\")\n .attr(\"x\", function(d, i) {\n return i * 75 + 25;\n })\n .attr(\"y\", 80)\n .attr(\"stroke\", \"teal\")\n .attr(\"font-size\", \"10px\")\n .attr(\"font-family\", \"sans-serif\")\n .text(function(d) {\n return d;\n });" }, { "code": null, "e": 10712, "s": 10549, "text": "Step 6 βˆ’ Working Example βˆ’ The complete code listing is shown in the following code block. Create a webpage circlecharts.html and add the following changes in it." }, { "code": null, "e": 10730, "s": 10712, "text": "circlecharts.html" }, { "code": null, "e": 12118, "s": 10730, "text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <script>\n var width = 400;\n \n var height = 400;\n \n var data = [10, 20, 30];\n \n var colors = ['green', 'purple', 'yellow'];\n \n var svg = d3\n .select(\"body\")\n .append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", height);\n \n var g = svg.selectAll(\"g\")\n .data(data)\n .enter()\n .append(\"g\")\n .attr(\"transform\", function(d, i) {\n return \"translate(0,0)\";\n })\n \n g.append(\"circle\").attr(\"cx\", function(d, i) {\n return i*75 + 50;\n })\n \n .attr(\"cy\", function(d, i) {\n return 75;\n })\n \n .attr(\"r\", function(d) {\n return d*1.5;\n })\n \n .attr(\"fill\", function(d, i){\n return colors[i];\n })\n \n g.append(\"text\").attr(\"x\", function(d, i) {\n return i * 75 + 25;\n })\n \n .attr(\"y\", 80)\n .attr(\"stroke\", \"teal\")\n .attr(\"font-size\", \"10px\")\n .attr(\"font-family\", \"sans-serif\").text(function(d) {\n return d;\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 12180, "s": 12118, "text": "Now, request your browser and following will be the response." }, { "code": null, "e": 12332, "s": 12180, "text": "A pie chart is a circular statistical graph. It is divided into slices to show numerical proportion. Let us understand how to create a pie chart in D3." }, { "code": null, "e": 12419, "s": 12332, "text": "Before starting to draw a pie chart, we need to understand the following two methods βˆ’" }, { "code": null, "e": 12444, "s": 12419, "text": "The d3.arc() method and " }, { "code": null, "e": 12465, "s": 12444, "text": "The d3.pie() method." }, { "code": null, "e": 12516, "s": 12465, "text": "Let us understand both of these methods in detail." }, { "code": null, "e": 12783, "s": 12516, "text": "The d3.arc() Method βˆ’ The d3.arc() method generates an arc. You need to set an inner radius and an outer radius for the arc. If the inner radius is 0, the result will be a pie chart, otherwise the result will be a donut chart, which is discussed in the next section." }, { "code": null, "e": 12964, "s": 12783, "text": "The d3.pie()Method βˆ’ The d3.pie() method is used to generate a pie chart. It takes a data from dataset and calculates the start angle and end angle for each wedge of the pie chart." }, { "code": null, "e": 13015, "s": 12964, "text": "Let us draw a pie chart using the following steps." }, { "code": null, "e": 13094, "s": 13015, "text": "Step 1 βˆ’ Applying styles βˆ’ Let us apply the following style to an arc element." }, { "code": null, "e": 13237, "s": 13094, "text": ".arc text {\n font: 12px arial;\n text-anchor: middle;\n}\n\n.arc path {\n stroke: #fff;\n}\n\n.title {\n fill: green;\n font-weight: italic;\n}" }, { "code": null, "e": 13346, "s": 13237, "text": "Here, fill is used to apply colors. A text-anchor is used to position the text towards the center of an arc." }, { "code": null, "e": 13425, "s": 13346, "text": "Step 2 βˆ’ Define variables βˆ’ Define the variables in the script as shown below." }, { "code": null, "e": 13587, "s": 13425, "text": "<script>\n var svg = d3.select(\"svg\"),\n width = svg.attr(\"width\"),\n height = svg.attr(\"height\"),\n radius = Math.min(width, height) / 2;\n</script>" }, { "code": null, "e": 13593, "s": 13587, "text": "Here," }, { "code": null, "e": 13619, "s": 13593, "text": "Width βˆ’ Width of the SVG." }, { "code": null, "e": 13645, "s": 13619, "text": "Width βˆ’ Width of the SVG." }, { "code": null, "e": 13673, "s": 13645, "text": "Height βˆ’ Height of the SVG." }, { "code": null, "e": 13701, "s": 13673, "text": "Height βˆ’ Height of the SVG." }, { "code": null, "e": 13782, "s": 13701, "text": "Radius βˆ’ It can be calculated using the function of Math.min(width, height) / 2;" }, { "code": null, "e": 13863, "s": 13782, "text": "Radius βˆ’ It can be calculated using the function of Math.min(width, height) / 2;" }, { "code": null, "e": 13963, "s": 13863, "text": "Step 3 βˆ’ Apply Transformation βˆ’ Apply the following transformation in SVG using the following code." }, { "code": null, "e": 14061, "s": 13963, "text": "var g = svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + width / 2 + \",\" + height / 2 + \")\");" }, { "code": null, "e": 14127, "s": 14061, "text": "Now add colors using the d3.scaleOrdinal function as given below." }, { "code": null, "e": 14194, "s": 14127, "text": "var color = d3.scaleOrdinal(['gray', 'green', 'brown', 'orange']);" }, { "code": null, "e": 14284, "s": 14194, "text": "Step 4 βˆ’ Generate a pie chart βˆ’ Now, generate a pie chart using the function given below." }, { "code": null, "e": 14349, "s": 14284, "text": "var pie = d3.pie()\n .value(function(d) { return d.percent; });" }, { "code": null, "e": 14474, "s": 14349, "text": "Here, you can plot the percentage values. An anonymous function is required to return d.percent and set it as the pie value." }, { "code": null, "e": 14611, "s": 14474, "text": "Step 5 βˆ’ Define arcs for pie wedges βˆ’ After generating the pie chart, now define arc for each pie wedges using the function given below." }, { "code": null, "e": 14674, "s": 14611, "text": "var arc = d3.arc()\n .outerRadius(radius)\n .innerRadius(0);" }, { "code": null, "e": 14803, "s": 14674, "text": "Here, this arc will be set to the path elements. The calculated radius is set to outerradius, while the innerradius is set to 0." }, { "code": null, "e": 14915, "s": 14803, "text": "Step 6 βˆ’ Add labels in wedges βˆ’ Add the labels in pie wedges by providing the radius. It is defined as follows." }, { "code": null, "e": 14994, "s": 14915, "text": "var label = d3\n .arc()\n .outerRadius(radius)\n .innerRadius(radius - 80);" }, { "code": null, "e": 15091, "s": 14994, "text": "Step 7 βˆ’ Read data βˆ’ This is an important step. We can read data using the function given below." }, { "code": null, "e": 15185, "s": 15091, "text": "d3.csv(\"populations.csv\", function(error, data) {\n if (error) {\n throw error;\n }\n});" }, { "code": null, "e": 15366, "s": 15185, "text": "Here, populations.csv contains the data file. The d3.csv function reads data from the dataset. If data is not present, it throws an error. We can include this file in your D3 path." }, { "code": null, "e": 15443, "s": 15366, "text": "Step 8 βˆ’ Load data βˆ’ The next step is to load data using the following code." }, { "code": null, "e": 15547, "s": 15443, "text": "var arc = g.selectAll(\".arc\")\n .data(pie(data))\n .enter()\n .append(\"g\")\n .attr(\"class\", \"arc\");" }, { "code": null, "e": 15636, "s": 15547, "text": "Here, we can assign data to group elements for each of the data values from the dataset." }, { "code": null, "e": 15727, "s": 15636, "text": "Step 9 βˆ’ Append path βˆ’ Now, append path and assign a class β€˜arc’ to groups as shown below." }, { "code": null, "e": 15830, "s": 15727, "text": "arcs.append(\"path\")\n .attr(\"d\", arc)\n .attr(\"fill\", function(d) { return color(d.data.states); });" }, { "code": null, "e": 15921, "s": 15830, "text": "Here, fill is used to apply the data color. It is taken from the d3.scaleOrdinal function." }, { "code": null, "e": 16001, "s": 15921, "text": "Step 10 βˆ’ Append text βˆ’ To display the text in labels using the following code." }, { "code": null, "e": 16163, "s": 16001, "text": "arc.append(\"text\")\n .attr(\"transform\", function(d) { \n return \"translate(\" + label.centroid(d) + \")\"; \n })\n.text(function(d) { return d.data.states; });" }, { "code": null, "e": 16384, "s": 16163, "text": "Here, SVG text element is used to display text in labels. The label arcs that we created earlier using d3.arc() returns a centroid point, which is a position for labels. Finally, we provide data using the d.data.browser." }, { "code": null, "e": 16560, "s": 16384, "text": "Step 11 βˆ’ Append group elements βˆ’ Append group elements attributes and add class title to color the text and make it italic, which is specified in Step 1 and is defined below." }, { "code": null, "e": 16738, "s": 16560, "text": "svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + (width / 2 - 120) + \",\" + 20 + \")\")\n .append(\"text\")\n .text(\"Top population states in india\")\n .attr(\"class\", \"title\")" }, { "code": null, "e": 16914, "s": 16738, "text": "Step 12 βˆ’ Working Example βˆ’ To draw a pie chart, we can take a dataset of Indian population. This dataset shows the population in a dummy website, which is defined as follows." }, { "code": null, "e": 16929, "s": 16914, "text": "population.csv" }, { "code": null, "e": 17020, "s": 16929, "text": "states,percent\nUP,80.00\nMaharastra,70.00\nBihar,65.0\nMP,60.00\nGujarat,50.0\nWB,49.0\nTN,35.0\n" }, { "code": null, "e": 17150, "s": 17020, "text": "Let us create a pie chart visualization for the above dataset. Create a webpage β€œpiechart.html” and add the following code in it." }, { "code": null, "e": 19354, "s": 17150, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .arc text {\n font: 12px arial;\n text-anchor: middle;\n }\n \n .arc path {\n stroke: #fff;\n }\n \n .title {\n fill: green;\n font-weight: italic;\n }\n </style>\n \n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <svg width = \"400\" height = \"400\"></svg>\n <script>\n var svg = d3.select(\"svg\"),\n width = svg.attr(\"width\"),\n height = svg.attr(\"height\"),\n radius = Math.min(width, height) / 2;\n \n var g = svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + width / 2 + \",\" + height / 2 + \")\");\n\n var color = d3.scaleOrdinal([\n 'gray', 'green', 'brown', 'orange', 'yellow', 'red', 'purple'\n ]);\n \n var pie = d3.pie().value(function(d) { \n return d.percent; \n });\n \n var path = d3.arc()\n .outerRadius(radius - 10).innerRadius(0);\n \n var label = d3.arc()\n .outerRadius(radius).innerRadius(radius - 80);\n \n d3.csv(\"populations.csv\", function(error, data) {\n if (error) {\n throw error;\n }\n \n var arc = g.selectAll(\".arc\")\n .data(pie(data))\n .enter()\n .append(\"g\")\n .attr(\"class\", \"arc\");\n \n arc.append(\"path\")\n .attr(\"d\", path)\n .attr(\"fill\", function(d) { return color(d.data.states); });\n \n console.log(arc)\n \n arc.append(\"text\").attr(\"transform\", function(d) { \n return \"translate(\" + label.centroid(d) + \")\"; \n })\n \n .text(function(d) { return d.data.states; });\n });\n \n svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + (width / 2 - 120) + \",\" + 20 + \")\")\n .append(\"text\").text(\"Top population states in india\")\n .attr(\"class\", \"title\")\n </script>\n </body>\n</html>" }, { "code": null, "e": 19361, "s": 19354, "text": " Print" }, { "code": null, "e": 19372, "s": 19361, "text": " Add Notes" } ]
How to adjust the width and height of iframe to fit with content in it ? - GeeksforGeeks
30 Jun, 2020 Using iframe tag the content inside the tag is displayed with a default size if the height and width are not specified. thou the height and width are specified then also the content of the iframe tag is not displayed in the same size of the main content. It is difficult to set the size of the content in the iframe tag as same as the main content. So its need to be dynamically set the content size when the content of iframe is loaded on the web page. Because its not possible to set the height and width all the time while the same code execute with a different content. There is a way to make it dynamically by using some attribute of JavaScript.The attributes used here are, contentWindow : This property returns the Window object used by an iframe element, basically its defines the iframe window. scrollHeight : This property defines the entire height of an element in pixels, the element is iframe. scrollWidth : This property defines the entire width of an element in pixels, the element is iframe. <!DOCTYPE html><html><head><h4 style="color:#006400; font-size:24px;">Adjust width and height of iframe to fit with content in it using JavaScript</h4></head><body> <iframe style="width: 100%;border:3px solid black; " src="iframe Pge.html" id="Iframe"></iframe> <!--iframe tag--> <script> // Selecting the iframe element var frame = document.getElementById("Iframe"); // Adjusting the iframe height onload event frame.onload = function() // function execute while load the iframe { // set the height of the iframe as // the height of the iframe content frame.style.height = frame.contentWindow.document.body.scrollHeight + 'px'; // set the width of the iframe as the // width of the iframe content frame.style.width = frame.contentWindow.document.body.scrollWidth+'px'; } </script></body></html> Before adjusting the height and width of iframe the site looks like- After adjusting the height and width of iframe the site looks like- The html code for the page what is used inside the iframe : <html ><head> </head><body style="margin:0px;"> <table style="width:100%; border-collapse:collapse; font:14px Arial,sans-serif;"> <tr> <td colspan="2" style="padding:10px; background-color:#16641a;"> <h1 style="font-size:24px; color:#fbfffb;"> Welcome to GeeksforGeeks</h1> </td> </tr> <tr style="height:300px;"> <td style="width:20%; padding:20px; background-color:#ffffff; "> <ul style="list-style:none; padding:0px; line-height:24px;"> <li><a href="#" style="color:rgb(70, 192, 59);"> Coding</a></li><br> <li><a href="#" style="color:rgb(70, 192, 59);;"> WebTechnology</a></li><br> <li><a href="#" style="color:rgb(70, 192, 59);"> DSA</a></li> </ul> </td> <td style="padding:20px; background-color:#5c9b37; vertical-align:top;"> <h2>Way to gain knowledge</h2> <ul style="list-style:none; padding:0px; line-height:24px;"> <li style="color:#ffffff;">Learn</a></li><br> <li style="color:#ffffff;">Practice</a></li><br> <li style="color:#ffffff;">Apply to real world</a></li> </ul> </td> </tr> <tr> <td colspan="2" style="padding:5px; background-color:#2b2a2a; text-align:center;"> <p style="color:#ffffff;">copyright Β© geeksforgeeks, Some rights reserved</p> </td> </tr> </table></body></html> Another way set the height and width of the iframe to fit with content is to set the Height and Width to 100%, <iframe width="100%" height="100%" src="URL" ></iframe> (This may not be applicable for all cases) <html> <head> <h4 style="color:#006400; font-size:24px;"> Adjust width and height manually to fit iframe content</h4> </head> <body> <div id="frame"> <iframe width="100%" height="100%" border:3px solid black;" src="iframe Pge.html" id="iFrame1" ></iframe> </div> </body> </html> Same as previous, Another way set the height and width of the iframe to fit with content is to use resize property of CSS, this method is not dynamic, but useful for some time. <html> <head> <style> #frame { width: 300px; height: 200px; resize: both; } </style> <h4 style="color:#006400; font-size:24px;"> Adjust width and height manually to fit iframe content using CSS</h4> </head> <body style="background-color:#ffffff"> <iframe height ="100%" width="100%" style="border:3px solid black;" src="iframe Pge.html" id="frame" ></iframe> </body> </html> JavaScript-Misc Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request JavaScript | console.log() with Examples Node.js | fs.writeFileSync() Method Set the value of an input field in JavaScript How to read a local text file using JavaScript?
[ { "code": null, "e": 24978, "s": 24950, "text": "\n30 Jun, 2020" }, { "code": null, "e": 25552, "s": 24978, "text": "Using iframe tag the content inside the tag is displayed with a default size if the height and width are not specified. thou the height and width are specified then also the content of the iframe tag is not displayed in the same size of the main content. It is difficult to set the size of the content in the iframe tag as same as the main content. So its need to be dynamically set the content size when the content of iframe is loaded on the web page. Because its not possible to set the height and width all the time while the same code execute with a different content." }, { "code": null, "e": 25658, "s": 25552, "text": "There is a way to make it dynamically by using some attribute of JavaScript.The attributes used here are," }, { "code": null, "e": 25782, "s": 25658, "text": "contentWindow : This property returns the Window object used by an iframe element, basically its defines the iframe window." }, { "code": null, "e": 25885, "s": 25782, "text": "scrollHeight : This property defines the entire height of an element in pixels, the element is iframe." }, { "code": null, "e": 25986, "s": 25885, "text": "scrollWidth : This property defines the entire width of an element in pixels, the element is iframe." }, { "code": "<!DOCTYPE html><html><head><h4 style=\"color:#006400; font-size:24px;\">Adjust width and height of iframe to fit with content in it using JavaScript</h4></head><body> <iframe style=\"width: 100%;border:3px solid black; \" src=\"iframe Pge.html\" id=\"Iframe\"></iframe> <!--iframe tag--> <script> // Selecting the iframe element var frame = document.getElementById(\"Iframe\"); // Adjusting the iframe height onload event frame.onload = function() // function execute while load the iframe { // set the height of the iframe as // the height of the iframe content frame.style.height = frame.contentWindow.document.body.scrollHeight + 'px'; // set the width of the iframe as the // width of the iframe content frame.style.width = frame.contentWindow.document.body.scrollWidth+'px'; } </script></body></html> ", "e": 27025, "s": 25986, "text": null }, { "code": null, "e": 27094, "s": 27025, "text": "Before adjusting the height and width of iframe the site looks like-" }, { "code": null, "e": 27162, "s": 27094, "text": "After adjusting the height and width of iframe the site looks like-" }, { "code": null, "e": 27222, "s": 27162, "text": "The html code for the page what is used inside the iframe :" }, { "code": "<html ><head> </head><body style=\"margin:0px;\"> <table style=\"width:100%; border-collapse:collapse; font:14px Arial,sans-serif;\"> <tr> <td colspan=\"2\" style=\"padding:10px; background-color:#16641a;\"> <h1 style=\"font-size:24px; color:#fbfffb;\"> Welcome to GeeksforGeeks</h1> </td> </tr> <tr style=\"height:300px;\"> <td style=\"width:20%; padding:20px; background-color:#ffffff; \"> <ul style=\"list-style:none; padding:0px; line-height:24px;\"> <li><a href=\"#\" style=\"color:rgb(70, 192, 59);\"> Coding</a></li><br> <li><a href=\"#\" style=\"color:rgb(70, 192, 59);;\"> WebTechnology</a></li><br> <li><a href=\"#\" style=\"color:rgb(70, 192, 59);\"> DSA</a></li> </ul> </td> <td style=\"padding:20px; background-color:#5c9b37; vertical-align:top;\"> <h2>Way to gain knowledge</h2> <ul style=\"list-style:none; padding:0px; line-height:24px;\"> <li style=\"color:#ffffff;\">Learn</a></li><br> <li style=\"color:#ffffff;\">Practice</a></li><br> <li style=\"color:#ffffff;\">Apply to real world</a></li> </ul> </td> </tr> <tr> <td colspan=\"2\" style=\"padding:5px; background-color:#2b2a2a; text-align:center;\"> <p style=\"color:#ffffff;\">copyright Β© geeksforgeeks, Some rights reserved</p> </td> </tr> </table></body></html>", "e": 28697, "s": 27222, "text": null }, { "code": null, "e": 28808, "s": 28697, "text": "Another way set the height and width of the iframe to fit with content is to set the Height and Width to 100%," }, { "code": null, "e": 28864, "s": 28808, "text": "<iframe width=\"100%\" height=\"100%\" src=\"URL\" ></iframe>" }, { "code": null, "e": 28907, "s": 28864, "text": "(This may not be applicable for all cases)" }, { "code": "<html> <head> <h4 style=\"color:#006400; font-size:24px;\"> Adjust width and height manually to fit iframe content</h4> </head> <body> <div id=\"frame\"> <iframe width=\"100%\" height=\"100%\" border:3px solid black;\" src=\"iframe Pge.html\" id=\"iFrame1\" ></iframe> </div> </body> </html> ", "e": 29323, "s": 28907, "text": null }, { "code": null, "e": 29341, "s": 29323, "text": "Same as previous," }, { "code": null, "e": 29500, "s": 29341, "text": "Another way set the height and width of the iframe to fit with content is to use resize property of CSS, this method is not dynamic, but useful for some time." }, { "code": "<html> <head> <style> #frame { width: 300px; height: 200px; resize: both; } </style> <h4 style=\"color:#006400; font-size:24px;\"> Adjust width and height manually to fit iframe content using CSS</h4> </head> <body style=\"background-color:#ffffff\"> <iframe height =\"100%\" width=\"100%\" style=\"border:3px solid black;\" src=\"iframe Pge.html\" id=\"frame\" ></iframe> </body> </html> ", "e": 30171, "s": 29500, "text": null }, { "code": null, "e": 30187, "s": 30171, "text": "JavaScript-Misc" }, { "code": null, "e": 30194, "s": 30187, "text": "Picked" }, { "code": null, "e": 30205, "s": 30194, "text": "JavaScript" }, { "code": null, "e": 30303, "s": 30205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30348, "s": 30303, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30409, "s": 30348, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30481, "s": 30409, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30533, "s": 30481, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 30579, "s": 30533, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 30620, "s": 30579, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30661, "s": 30620, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 30697, "s": 30661, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 30743, "s": 30697, "text": "Set the value of an input field in JavaScript" } ]
How to write Python regular expression to get zero or more occurrences within the pattern?
* An asterisk meta-character in a regular expression indicates 0 or more occurrences of the pattern to its left The following code matches and prints the zero or more occurrences of the pattern '\w' in the string 'chihua huahua' import re s = 'chihua huahua' result = re.findall(r'\w*', s) print result This gives the output ['chihua', '', 'huahua', '']
[ { "code": null, "e": 1180, "s": 1062, "text": "* An asterisk meta-character in a regular expression indicates 0 or more occurrences of the pattern to its left" }, { "code": null, "e": 1297, "s": 1180, "text": "The following code matches and prints the zero or more occurrences of the pattern '\\w' in the string 'chihua huahua'" }, { "code": null, "e": 1371, "s": 1297, "text": "import re\ns = 'chihua huahua'\nresult = re.findall(r'\\w*', s)\nprint result" }, { "code": null, "e": 1393, "s": 1371, "text": "This gives the output" }, { "code": null, "e": 1422, "s": 1393, "text": "['chihua', '', 'huahua', '']" } ]
Print all pairs with given sum in C++
In this problem, we are given an array of integers and an integer sum and we have to print all pairs of integers whose sum is equal to the sum value. Let’s take an example to understand the problem : Input βˆ’ array = {1, 6, -2, 3} sum = 4 Output βˆ’ (1, 3) , (6, -2) Here, we need pairs with the given sum value. A simple solution to the problem will be checking pairs of elements that generate the sum. This can be done by traversing array and find the number in array that sums up to sum value. This program will illustrate the solution βˆ’ Live Demo #include <iostream> using namespace std; int printPairsWithSum(int arr[], int n, int sum){ int count = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) cout<<"[ "<<arr[i]<<", "<<arr[j]<<" ]\n"; } int main(){ int arr[] = {1, 6, -2, 3}; int n = 4; int sum = 4; cout<<"Pairs with Sum "<<sum<<" are :\n"; printPairsWithSum(arr, n, sum); return 0; } Pairs with Sum 4 are : [ 1, 3 ] [ 6, -2 ] This method is easy to understand but not quite efficient. Another way will be using hashing. We will initialise a hash table and traverse the array and find pairs in it. On match, we will print the array : The following program will make you understand the algorithm better βˆ’ Live Demo #include <bits/stdc++.h> using namespace std; void printPairsWithSum(int arr[], int n, int sum){ unordered_map<int, int> pair; for (int i = 0; i < n; i++) { int rem = sum - arr[i]; if (pair.find(rem) != pair.end()) { int count = pair[rem]; for (int j = 0; j < count; j++) cout<<"["<<rem<<", "<<arr[i]<<" ]\n"; } pair[arr[i]]++; } } int main(){ int arr[] = {1, 6, -2, 3}; int n = 4; int sum = 4; cout<<"The pair with sum is \n"; printPairsWithSum(arr, n, sum); return 0; } Pairs with Sum 4 are : [ 1, 3 ] [ 6, -2 ]
[ { "code": null, "e": 1212, "s": 1062, "text": "In this problem, we are given an array of integers and an integer sum and we have to print all pairs of integers whose sum is equal to the sum value." }, { "code": null, "e": 1262, "s": 1212, "text": "Let’s take an example to understand the problem :" }, { "code": null, "e": 1300, "s": 1262, "text": "Input βˆ’ array = {1, 6, -2, 3} sum = 4" }, { "code": null, "e": 1326, "s": 1300, "text": "Output βˆ’ (1, 3) , (6, -2)" }, { "code": null, "e": 1372, "s": 1326, "text": "Here, we need pairs with the given sum value." }, { "code": null, "e": 1556, "s": 1372, "text": "A simple solution to the problem will be checking pairs of elements that generate the sum. This can be done by traversing array and find the number in array that sums up to sum value." }, { "code": null, "e": 1600, "s": 1556, "text": "This program will illustrate the solution βˆ’" }, { "code": null, "e": 1611, "s": 1600, "text": " Live Demo" }, { "code": null, "e": 2049, "s": 1611, "text": "#include <iostream>\nusing namespace std;\nint printPairsWithSum(int arr[], int n, int sum){\n int count = 0;\n for (int i = 0; i < n; i++)\n for (int j = i + 1; j < n; j++)\n if (arr[i] + arr[j] == sum)\n cout<<\"[ \"<<arr[i]<<\", \"<<arr[j]<<\" ]\\n\";\n}\nint main(){\n int arr[] = {1, 6, -2, 3};\n int n = 4;\n int sum = 4;\n cout<<\"Pairs with Sum \"<<sum<<\" are :\\n\";\n printPairsWithSum(arr, n, sum);\n return 0;\n}" }, { "code": null, "e": 2091, "s": 2049, "text": "Pairs with Sum 4 are :\n[ 1, 3 ]\n[ 6, -2 ]" }, { "code": null, "e": 2185, "s": 2091, "text": "This method is easy to understand but not quite efficient. Another way will be using hashing." }, { "code": null, "e": 2298, "s": 2185, "text": "We will initialise a hash table and traverse the array and find pairs in it. On match, we will print the array :" }, { "code": null, "e": 2368, "s": 2298, "text": "The following program will make you understand the algorithm better βˆ’" }, { "code": null, "e": 2379, "s": 2368, "text": " Live Demo" }, { "code": null, "e": 2929, "s": 2379, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid printPairsWithSum(int arr[], int n, int sum){\n unordered_map<int, int> pair;\n for (int i = 0; i < n; i++) {\n int rem = sum - arr[i];\n if (pair.find(rem) != pair.end()) {\n int count = pair[rem];\n for (int j = 0; j < count; j++)\n cout<<\"[\"<<rem<<\", \"<<arr[i]<<\" ]\\n\";\n }\n pair[arr[i]]++;\n }\n}\nint main(){\n int arr[] = {1, 6, -2, 3};\n int n = 4;\n int sum = 4;\n cout<<\"The pair with sum is \\n\";\n printPairsWithSum(arr, n, sum);\n return 0;\n}" }, { "code": null, "e": 2971, "s": 2929, "text": "Pairs with Sum 4 are :\n[ 1, 3 ]\n[ 6, -2 ]" } ]