title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Print a given matrix in counter-clock wise spiral form - GeeksforGeeks
|
20 Apr, 2021
Given a 2D array, print it in counter-clock wise spiral form. See the following examples.Examples :
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7
Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
1 7 13 14 15 16 17 18 12 6 5 4 3 2 8 9 10 11
Explanation :
Below is the implementation :
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to print// the counter clock wise// spiral traversal of matrix#include <bits/stdc++.h>using namespace std; #define R 4#define C 4 // function to print the// required traversalvoid counterClockspiralPrint(int m, int n, int arr[R][C]){ int i, k = 0, l = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index // i - iterator // initialize the count int cnt = 0; // total number of // elements in matrix int total = m * n; while (k < m && l < n) { if (cnt == total) break; // Print the first column // from the remaining columns for (i = k; i < m; ++i) { cout << arr[i][l] << " "; cnt++; } l++; if (cnt == total) break; // Print the last row from // the remaining rows for (i = l; i < n; ++i) { cout << arr[m - 1][i] << " "; cnt++; } m--; if (cnt == total) break; // Print the last column // from the remaining columns if (k < m) { for (i = m - 1; i >= k; --i) { cout << arr[i][n - 1] << " "; cnt++; } n--; } if (cnt == total) break; // Print the first row // from the remaining rows if (l < n) { for (i = n - 1; i >= l; --i) { cout << arr[k][i] << " "; cnt++; } k++; } }} // Driver Codeint main(){ int arr[R][C] = {{ 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }}; counterClockspiralPrint(R, C, arr); return 0;}
// Java implementation to print// the counter clock wise// spiral traversal of matriximport java.io.*; class GFG{ static int R = 4; static int C = 4; // function to print the // required traversal static void counterClockspiralPrint(int m, int n, int arr[][]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ // initialize the count int cnt = 0; // total number of // elements in matrix int total = m * n; while (k < m && l < n) { if (cnt == total) break; // Print the first column // from the remaining columns for (i = k; i < m; ++i) { System.out.print(arr[i][l] + " "); cnt++; } l++; if (cnt == total) break; // Print the last row from // the remaining rows for (i = l; i < n; ++i) { System.out.print(arr[m - 1][i] + " "); cnt++; } m--; if (cnt == total) break; // Print the last column // from the remaining columns if (k < m) { for (i = m - 1; i >= k; --i) { System.out.print(arr[i][n - 1] + " "); cnt++; } n--; } if (cnt == total) break; // Print the first row // from the remaining rows if (l < n) { for (i = n - 1; i >= l; --i) { System.out.print(arr[k][i] + " "); cnt++; } k++; } } } // Driver Codepublic static void main(String[] args){ int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function calling counterClockspiralPrint(R, C, arr);}} // This code is contributed by vt_m
# Python3 implementation to print# the counter clock wise# spiral traversal of matrixR = 4C = 4 # Function to print# the required traversaldef counterClockspiralPrint(m, n, arr) : k = 0; l = 0 # k - starting row index # m - ending row index # l - starting column index # n - ending column index # i - iterator # initialize the count cnt = 0 # total number of # elements in matrix total = m * n while (k < m and l < n) : if (cnt == total) : break # Print the first column # from the remaining columns for i in range(k, m) : print(arr[i][l], end = " ") cnt += 1 l += 1 if (cnt == total) : break # Print the last row from # the remaining rows for i in range (l, n) : print( arr[m - 1][i], end = " ") cnt += 1 m -= 1 if (cnt == total) : break # Print the last column # from the remaining columns if (k < m) : for i in range(m - 1, k - 1, -1) : print(arr[i][n - 1], end = " ") cnt += 1 n -= 1 if (cnt == total) : break # Print the first row # from the remaining rows if (l < n) : for i in range(n - 1, l - 1, -1) : print( arr[k][i], end = " ") cnt += 1 k += 1 # Driver Codearr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] counterClockspiralPrint(R, C, arr) # This code is contributed by Nikita Tiwari
// C# implementation to print// the counter clock wise// spiral traversal of matrix;using System; class GFG{ static int R = 4; static int C = 4; // function to print the required traversal static void counterClockspiralPrint(int m, int n, int[,] arr) { int i, k = 0, l = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index // i - iterator // initialize the count int cnt = 0; // total number of elements in matrix int total = m * n; while (k < m && l < n) { if (cnt == total) break; // Print the first column from // the remaining columns for (i = k; i < m; ++i) { Console.Write(arr[i,l] + " "); cnt++; } l++; if (cnt == total) break; // Print the last row from // the remaining rows for (i = l; i < n; ++i) { Console.Write(arr[m - 1, i] + " "); cnt++; } m--; if (cnt == total) break; // Print the last column from // the remaining columns if (k < m) { for (i = m - 1; i >= k; --i) { Console.Write(arr[i, n - 1] + " "); cnt++; } n--; } if (cnt == total) break; // Print the first row from // the remaining rows if (l < n) { for (i = n - 1; i >= l; --i) { Console.Write(arr[k, i] + " "); cnt++; } k++; } } } // Driver codepublic static void Main(){ int[,] arr =new int[,] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function calling counterClockspiralPrint(R, C, arr);}} // This code is contributed by KRV.
<?php// PHP implementation to print// the counter clock wise// spiral traversal of matrix $R = 4;$C = 4; // function to print// the required traversalfunction counterClockspiralPrint($m, $n, $arr){ $i; $k = 0; $l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ // initialize the count $cnt = 0; // total number of // elements in matrix $total = $m * $n; while ($k < $m and $l < $n) { if ($cnt == $total) break; // Print the first column // from the remaining columns for ($i = $k; $i < $m; ++$i) { echo $arr[$i][$l] ," "; $cnt++; } $l++; if ($cnt == $total) break; // Print the last row from // the remaining rows for ($i = $l; $i < $n; ++$i) { echo $arr[$m - 1][$i] , " "; $cnt++; } $m--; if ($cnt == $total) break; // Print the last column // from the remaining columns if ($k < $m) { for ($i = $m - 1; $i >= $k; --$i) { echo $arr[$i][$n - 1] , " "; $cnt++; } $n--; } if ($cnt == $total) break; // Print the first row // from the remaining rows if ($l < $n) { for ($i = $n - 1; $i >= $l; --$i) { echo $arr[$k][$i] , " "; $cnt++; } $k++; } }} // Driver Codeglobal $R,$C; $arr = array(array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ), array( 9, 10, 11, 12 ), array( 13, 14, 15, 16 ));echo counterClockspiralPrint($R, $C, $arr); // This code is contributed by anuj_67.?>
<script>// Javascript implementation to print// the counter clock wise// spiral traversal of matrix let R = 4;let C = 4; // function to print the// required traversalfunction counterClockspiralPrint(m, n, arr){ let i, k = 0, l = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index // i - iterator // initialize the count let cnt = 0; // total number of // elements in matrix let total = m * n; while (k < m && l < n) { if (cnt == total) break; // Print the first column // from the remaining columns for (i = k; i < m; ++i) { document.write(arr[i][l] + " "); cnt++; } l++; if (cnt == total) break; // Print the last row from // the remaining rows for (i = l; i < n; ++i) { document.write(arr[m - 1][i] + " "); cnt++; } m--; if (cnt == total) break; // Print the last column // from the remaining columns if (k < m) { for (i = m - 1; i >= k; --i) { document.write(arr[i][n - 1] + " "); cnt++; } n--; } if (cnt == total) break; // Print the first row // from the remaining rows if (l < n) { for (i = n - 1; i >= l; --i) { document.write(arr[k][i] + " "); cnt++; } k++; } }} // Driver Code let arr = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]]; counterClockspiralPrint(R, C, arr); // This code is contributed by rishavmahato348.</script>
Output :
1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7
Time Complexity : O(mn).Alternate Implementation :
Python
# Python3 implementation to print# the counter clock wise# spiral traversal of matrix #function to print Matrix in CounterClockwisedef counterClockspiralPrint(Matrix): size = len(Matrix) flag = 0 k, i = 0, size # Print all layers one by one while(i > 0): # Print First Column of Current Layer for j in range(flag,i): print(Matrix[j][k], end = ' ') i = i - 1 k = j # Print bottom row and last column # of current layer if (i > 0): for j in range(size - i,i + 1): print(Matrix[k][j], end = ' ') for j in range(k-1,size-i-2,-1): print(Matrix[j][k], end = ' ') else: break k = j i = i-1 # Print top row of current layer if (i > 0): for j in range(i,size - i-2,-1): print(Matrix[k][j], end = ' ') k,i = k+1,i+1 flag = flag + 1 else: break # Driver codearr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] counterClockspiralPrint(arr) # This code is contributed by Srihari R
KRV
vt_m
sriharikrishna06
rishavmahato348
spiral
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Maximum size square sub-matrix with all 1s
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Count all possible paths from top left to bottom right of a mXn matrix
Maximum size rectangle binary sub-matrix with all 1s
Program to multiply two matrices
|
[
{
"code": null,
"e": 42519,
"s": 42491,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 42621,
"s": 42519,
"text": "Given a 2D array, print it in counter-clock wise spiral form. See the following examples.Examples : "
},
{
"code": null,
"e": 42921,
"s": 42621,
"text": "Input:\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 16\nOutput: \n1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7 \n\nInput:\n 1 2 3 4 5 6\n 7 8 9 10 11 12\n 13 14 15 16 17 18\nOutput: \n1 7 13 14 15 16 17 18 12 6 5 4 3 2 8 9 10 11 "
},
{
"code": null,
"e": 42937,
"s": 42921,
"text": "Explanation : "
},
{
"code": null,
"e": 42969,
"s": 42937,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 42973,
"s": 42969,
"text": "C++"
},
{
"code": null,
"e": 42978,
"s": 42973,
"text": "Java"
},
{
"code": null,
"e": 42986,
"s": 42978,
"text": "Python3"
},
{
"code": null,
"e": 42989,
"s": 42986,
"text": "C#"
},
{
"code": null,
"e": 42993,
"s": 42989,
"text": "PHP"
},
{
"code": null,
"e": 43004,
"s": 42993,
"text": "Javascript"
},
{
"code": "// C++ implementation to print// the counter clock wise// spiral traversal of matrix#include <bits/stdc++.h>using namespace std; #define R 4#define C 4 // function to print the// required traversalvoid counterClockspiralPrint(int m, int n, int arr[R][C]){ int i, k = 0, l = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index // i - iterator // initialize the count int cnt = 0; // total number of // elements in matrix int total = m * n; while (k < m && l < n) { if (cnt == total) break; // Print the first column // from the remaining columns for (i = k; i < m; ++i) { cout << arr[i][l] << \" \"; cnt++; } l++; if (cnt == total) break; // Print the last row from // the remaining rows for (i = l; i < n; ++i) { cout << arr[m - 1][i] << \" \"; cnt++; } m--; if (cnt == total) break; // Print the last column // from the remaining columns if (k < m) { for (i = m - 1; i >= k; --i) { cout << arr[i][n - 1] << \" \"; cnt++; } n--; } if (cnt == total) break; // Print the first row // from the remaining rows if (l < n) { for (i = n - 1; i >= l; --i) { cout << arr[k][i] << \" \"; cnt++; } k++; } }} // Driver Codeint main(){ int arr[R][C] = {{ 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }}; counterClockspiralPrint(R, C, arr); return 0;}",
"e": 44921,
"s": 43004,
"text": null
},
{
"code": "// Java implementation to print// the counter clock wise// spiral traversal of matriximport java.io.*; class GFG{ static int R = 4; static int C = 4; // function to print the // required traversal static void counterClockspiralPrint(int m, int n, int arr[][]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ // initialize the count int cnt = 0; // total number of // elements in matrix int total = m * n; while (k < m && l < n) { if (cnt == total) break; // Print the first column // from the remaining columns for (i = k; i < m; ++i) { System.out.print(arr[i][l] + \" \"); cnt++; } l++; if (cnt == total) break; // Print the last row from // the remaining rows for (i = l; i < n; ++i) { System.out.print(arr[m - 1][i] + \" \"); cnt++; } m--; if (cnt == total) break; // Print the last column // from the remaining columns if (k < m) { for (i = m - 1; i >= k; --i) { System.out.print(arr[i][n - 1] + \" \"); cnt++; } n--; } if (cnt == total) break; // Print the first row // from the remaining rows if (l < n) { for (i = n - 1; i >= l; --i) { System.out.print(arr[k][i] + \" \"); cnt++; } k++; } } } // Driver Codepublic static void main(String[] args){ int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function calling counterClockspiralPrint(R, C, arr);}} // This code is contributed by vt_m",
"e": 47228,
"s": 44921,
"text": null
},
{
"code": "# Python3 implementation to print# the counter clock wise# spiral traversal of matrixR = 4C = 4 # Function to print# the required traversaldef counterClockspiralPrint(m, n, arr) : k = 0; l = 0 # k - starting row index # m - ending row index # l - starting column index # n - ending column index # i - iterator # initialize the count cnt = 0 # total number of # elements in matrix total = m * n while (k < m and l < n) : if (cnt == total) : break # Print the first column # from the remaining columns for i in range(k, m) : print(arr[i][l], end = \" \") cnt += 1 l += 1 if (cnt == total) : break # Print the last row from # the remaining rows for i in range (l, n) : print( arr[m - 1][i], end = \" \") cnt += 1 m -= 1 if (cnt == total) : break # Print the last column # from the remaining columns if (k < m) : for i in range(m - 1, k - 1, -1) : print(arr[i][n - 1], end = \" \") cnt += 1 n -= 1 if (cnt == total) : break # Print the first row # from the remaining rows if (l < n) : for i in range(n - 1, l - 1, -1) : print( arr[k][i], end = \" \") cnt += 1 k += 1 # Driver Codearr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] counterClockspiralPrint(R, C, arr) # This code is contributed by Nikita Tiwari",
"e": 48910,
"s": 47228,
"text": null
},
{
"code": "// C# implementation to print// the counter clock wise// spiral traversal of matrix;using System; class GFG{ static int R = 4; static int C = 4; // function to print the required traversal static void counterClockspiralPrint(int m, int n, int[,] arr) { int i, k = 0, l = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index // i - iterator // initialize the count int cnt = 0; // total number of elements in matrix int total = m * n; while (k < m && l < n) { if (cnt == total) break; // Print the first column from // the remaining columns for (i = k; i < m; ++i) { Console.Write(arr[i,l] + \" \"); cnt++; } l++; if (cnt == total) break; // Print the last row from // the remaining rows for (i = l; i < n; ++i) { Console.Write(arr[m - 1, i] + \" \"); cnt++; } m--; if (cnt == total) break; // Print the last column from // the remaining columns if (k < m) { for (i = m - 1; i >= k; --i) { Console.Write(arr[i, n - 1] + \" \"); cnt++; } n--; } if (cnt == total) break; // Print the first row from // the remaining rows if (l < n) { for (i = n - 1; i >= l; --i) { Console.Write(arr[k, i] + \" \"); cnt++; } k++; } } } // Driver codepublic static void Main(){ int[,] arr =new int[,] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function calling counterClockspiralPrint(R, C, arr);}} // This code is contributed by KRV.",
"e": 51186,
"s": 48910,
"text": null
},
{
"code": "<?php// PHP implementation to print// the counter clock wise// spiral traversal of matrix $R = 4;$C = 4; // function to print// the required traversalfunction counterClockspiralPrint($m, $n, $arr){ $i; $k = 0; $l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ // initialize the count $cnt = 0; // total number of // elements in matrix $total = $m * $n; while ($k < $m and $l < $n) { if ($cnt == $total) break; // Print the first column // from the remaining columns for ($i = $k; $i < $m; ++$i) { echo $arr[$i][$l] ,\" \"; $cnt++; } $l++; if ($cnt == $total) break; // Print the last row from // the remaining rows for ($i = $l; $i < $n; ++$i) { echo $arr[$m - 1][$i] , \" \"; $cnt++; } $m--; if ($cnt == $total) break; // Print the last column // from the remaining columns if ($k < $m) { for ($i = $m - 1; $i >= $k; --$i) { echo $arr[$i][$n - 1] , \" \"; $cnt++; } $n--; } if ($cnt == $total) break; // Print the first row // from the remaining rows if ($l < $n) { for ($i = $n - 1; $i >= $l; --$i) { echo $arr[$k][$i] , \" \"; $cnt++; } $k++; } }} // Driver Codeglobal $R,$C; $arr = array(array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ), array( 9, 10, 11, 12 ), array( 13, 14, 15, 16 ));echo counterClockspiralPrint($R, $C, $arr); // This code is contributed by anuj_67.?>",
"e": 53081,
"s": 51186,
"text": null
},
{
"code": "<script>// Javascript implementation to print// the counter clock wise// spiral traversal of matrix let R = 4;let C = 4; // function to print the// required traversalfunction counterClockspiralPrint(m, n, arr){ let i, k = 0, l = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index // i - iterator // initialize the count let cnt = 0; // total number of // elements in matrix let total = m * n; while (k < m && l < n) { if (cnt == total) break; // Print the first column // from the remaining columns for (i = k; i < m; ++i) { document.write(arr[i][l] + \" \"); cnt++; } l++; if (cnt == total) break; // Print the last row from // the remaining rows for (i = l; i < n; ++i) { document.write(arr[m - 1][i] + \" \"); cnt++; } m--; if (cnt == total) break; // Print the last column // from the remaining columns if (k < m) { for (i = m - 1; i >= k; --i) { document.write(arr[i][n - 1] + \" \"); cnt++; } n--; } if (cnt == total) break; // Print the first row // from the remaining rows if (l < n) { for (i = n - 1; i >= l; --i) { document.write(arr[k][i] + \" \"); cnt++; } k++; } }} // Driver Code let arr = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]]; counterClockspiralPrint(R, C, arr); // This code is contributed by rishavmahato348.</script>",
"e": 54951,
"s": 53081,
"text": null
},
{
"code": null,
"e": 54962,
"s": 54951,
"text": "Output : "
},
{
"code": null,
"e": 55003,
"s": 54962,
"text": "1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7 "
},
{
"code": null,
"e": 55056,
"s": 55003,
"text": "Time Complexity : O(mn).Alternate Implementation : "
},
{
"code": null,
"e": 55063,
"s": 55056,
"text": "Python"
},
{
"code": "# Python3 implementation to print# the counter clock wise# spiral traversal of matrix #function to print Matrix in CounterClockwisedef counterClockspiralPrint(Matrix): size = len(Matrix) flag = 0 k, i = 0, size # Print all layers one by one while(i > 0): # Print First Column of Current Layer for j in range(flag,i): print(Matrix[j][k], end = ' ') i = i - 1 k = j # Print bottom row and last column # of current layer if (i > 0): for j in range(size - i,i + 1): print(Matrix[k][j], end = ' ') for j in range(k-1,size-i-2,-1): print(Matrix[j][k], end = ' ') else: break k = j i = i-1 # Print top row of current layer if (i > 0): for j in range(i,size - i-2,-1): print(Matrix[k][j], end = ' ') k,i = k+1,i+1 flag = flag + 1 else: break # Driver codearr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] counterClockspiralPrint(arr) # This code is contributed by Srihari R",
"e": 56211,
"s": 55063,
"text": null
},
{
"code": null,
"e": 56215,
"s": 56211,
"text": "KRV"
},
{
"code": null,
"e": 56220,
"s": 56215,
"text": "vt_m"
},
{
"code": null,
"e": 56237,
"s": 56220,
"text": "sriharikrishna06"
},
{
"code": null,
"e": 56253,
"s": 56237,
"text": "rishavmahato348"
},
{
"code": null,
"e": 56260,
"s": 56253,
"text": "spiral"
},
{
"code": null,
"e": 56267,
"s": 56260,
"text": "Matrix"
},
{
"code": null,
"e": 56274,
"s": 56267,
"text": "Matrix"
},
{
"code": null,
"e": 56372,
"s": 56274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 56407,
"s": 56372,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 56451,
"s": 56407,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 56482,
"s": 56451,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 56525,
"s": 56482,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 56549,
"s": 56525,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 56596,
"s": 56549,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 56658,
"s": 56596,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 56729,
"s": 56658,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 56782,
"s": 56729,
"text": "Maximum size rectangle binary sub-matrix with all 1s"
}
] |
What is the Call Stack in JavaScript ? - GeeksforGeeks
|
05 Jan, 2021
The call stack is used by JavaScript to keep track of multiple function calls. It is like a real stack in data structures where data can be pushed and popped and follows the Last In First Out (LIFO) principle. We use call stack for memorizing which function is running right now. The below example demonstrates the call stack.
Example:
Javascript
function f1() { console.log('Hi by f1!');} function f2() { f1(); console.log('Hi by f2!');} f2();
Output:
"Hi by f1!"
"Hi by f2!"
Explanation:
The steps and illustrations below explain the call stack of the above function.
Step 1: When the code loads in memory, the global execution context gets pushed in the stack.
Step 2: The f2() function gets called, and the execution context of f2() gets pushed into the stack.
Step 3: The execution of f2() starts and during its execution, the f1() function gets called inside the f2() function. This causes the execution context of f1() to get pushed in the call stack.
Step 4: Now the f1() function starts executing. A new stack frame of the console.log() method will be pushed to the stack.
Step 5: When the console.log() method runs, it will print “Hi by f1” and then it will be popped from the stack. The execution context go will back to the function and now there not any line of code that remains in the f1() function, as a result, it will also be popped from the call stack.
Step 6: This will similarly happen with the console.log() method that prints the line “Hi by f2” and then finally the function f2() would finish and would be pushed off the stack.
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n05 Jan, 2021"
},
{
"code": null,
"e": 26872,
"s": 26545,
"text": "The call stack is used by JavaScript to keep track of multiple function calls. It is like a real stack in data structures where data can be pushed and popped and follows the Last In First Out (LIFO) principle. We use call stack for memorizing which function is running right now. The below example demonstrates the call stack."
},
{
"code": null,
"e": 26881,
"s": 26872,
"text": "Example:"
},
{
"code": null,
"e": 26892,
"s": 26881,
"text": "Javascript"
},
{
"code": "function f1() { console.log('Hi by f1!');} function f2() { f1(); console.log('Hi by f2!');} f2();",
"e": 26995,
"s": 26892,
"text": null
},
{
"code": null,
"e": 27003,
"s": 26995,
"text": "Output:"
},
{
"code": null,
"e": 27027,
"s": 27003,
"text": "\"Hi by f1!\"\n\"Hi by f2!\""
},
{
"code": null,
"e": 27040,
"s": 27027,
"text": "Explanation:"
},
{
"code": null,
"e": 27120,
"s": 27040,
"text": "The steps and illustrations below explain the call stack of the above function."
},
{
"code": null,
"e": 27214,
"s": 27120,
"text": "Step 1: When the code loads in memory, the global execution context gets pushed in the stack."
},
{
"code": null,
"e": 27315,
"s": 27214,
"text": "Step 2: The f2() function gets called, and the execution context of f2() gets pushed into the stack."
},
{
"code": null,
"e": 27509,
"s": 27315,
"text": "Step 3: The execution of f2() starts and during its execution, the f1() function gets called inside the f2() function. This causes the execution context of f1() to get pushed in the call stack."
},
{
"code": null,
"e": 27632,
"s": 27509,
"text": "Step 4: Now the f1() function starts executing. A new stack frame of the console.log() method will be pushed to the stack."
},
{
"code": null,
"e": 27922,
"s": 27632,
"text": "Step 5: When the console.log() method runs, it will print “Hi by f1” and then it will be popped from the stack. The execution context go will back to the function and now there not any line of code that remains in the f1() function, as a result, it will also be popped from the call stack."
},
{
"code": null,
"e": 28102,
"s": 27922,
"text": "Step 6: This will similarly happen with the console.log() method that prints the line “Hi by f2” and then finally the function f2() would finish and would be pushed off the stack."
},
{
"code": null,
"e": 28118,
"s": 28102,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 28129,
"s": 28118,
"text": "JavaScript"
},
{
"code": null,
"e": 28146,
"s": 28129,
"text": "Web Technologies"
},
{
"code": null,
"e": 28244,
"s": 28146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28284,
"s": 28244,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28345,
"s": 28284,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28386,
"s": 28345,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28408,
"s": 28386,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28462,
"s": 28408,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28502,
"s": 28462,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28535,
"s": 28502,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28578,
"s": 28535,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28628,
"s": 28578,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python - How to save canvas in pyqt5? - GeeksforGeeks
|
25 Nov, 2021
There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library.
In this tutorial we’ll take a look how to save canvas in pyqt5. We draw things on canvas using QPainter class.
QPainter : Qt’s painting system is able to render vector graphics, images, and outline font-based text with sub-pixel accuracy using anti-aliasing to improve rendering quality.
In this article, we create a canvas and will draw a line on it and see how to save that canvas as image file at desired location on the system. Below is the implementation.
Python3
# importing modulesfrom PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtCore import * import sys # creating class for windowclass Window(QMainWindow): def __init__(self): super().__init__() title = "Paint and save Application" top = 400 left = 400 width = 800 height = 600 # setting title of window self.setWindowTitle(title) # setting geometry self.setGeometry(top, left, width, height) # creating canvas self.image = QImage(self.size(), QImage.Format_RGB32) # setting canvas color to white self.image.fill(Qt.white) # creating menu bar mainMenu = self.menuBar() # adding file menu in it fileMenu = mainMenu.addMenu("File") # creating save action saveAction = QAction("Save", self) # setting save action shortcut saveAction.setShortcut("Ctrl + S") # adding save action to filemenu fileMenu.addAction(saveAction) # setting triggered method saveAction.triggered.connect(self.save) # calling draw_something method self.draw_something() # paintEvent for creating blank canvas def paintEvent(self, event): canvasPainter = QPainter(self) canvasPainter.drawImage(self.rect(), self.image, self.image.rect()) # this method will draw a line def draw_something(self): painter = QPainter(self.image) painter.setPen(QPen(Qt.black, 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) # drawing a line painter.drawLine(100, 100, 300, 300) # updating it to canvas self.update() # save method def save(self): # selecting file path filePath, _ = QFileDialog.getSaveFileName(self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ") # if file path is blank return back if filePath == "": return # saving canvas at desired path self.image.save(filePath) # main methodif __name__ == "__main__": app = QApplication(sys.argv) window = Window() window.show() # looping for window sys.exit(app.exec())
Output : After running the code window will appear with a canvas of white color on which line is drawn.
After clicking on the file menu save button will appear.
When save button is pressed it will ask for the location and name and image will get saved at desirable location.
This code will save the canvas in png format at the desired location.
sweetyty
adnanirshad158
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
|
[
{
"code": null,
"e": 25617,
"s": 25589,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 25919,
"s": 25617,
"text": "There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library."
},
{
"code": null,
"e": 26030,
"s": 25919,
"text": "In this tutorial we’ll take a look how to save canvas in pyqt5. We draw things on canvas using QPainter class."
},
{
"code": null,
"e": 26207,
"s": 26030,
"text": "QPainter : Qt’s painting system is able to render vector graphics, images, and outline font-based text with sub-pixel accuracy using anti-aliasing to improve rendering quality."
},
{
"code": null,
"e": 26381,
"s": 26207,
"text": "In this article, we create a canvas and will draw a line on it and see how to save that canvas as image file at desired location on the system. Below is the implementation. "
},
{
"code": null,
"e": 26389,
"s": 26381,
"text": "Python3"
},
{
"code": "# importing modulesfrom PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtCore import * import sys # creating class for windowclass Window(QMainWindow): def __init__(self): super().__init__() title = \"Paint and save Application\" top = 400 left = 400 width = 800 height = 600 # setting title of window self.setWindowTitle(title) # setting geometry self.setGeometry(top, left, width, height) # creating canvas self.image = QImage(self.size(), QImage.Format_RGB32) # setting canvas color to white self.image.fill(Qt.white) # creating menu bar mainMenu = self.menuBar() # adding file menu in it fileMenu = mainMenu.addMenu(\"File\") # creating save action saveAction = QAction(\"Save\", self) # setting save action shortcut saveAction.setShortcut(\"Ctrl + S\") # adding save action to filemenu fileMenu.addAction(saveAction) # setting triggered method saveAction.triggered.connect(self.save) # calling draw_something method self.draw_something() # paintEvent for creating blank canvas def paintEvent(self, event): canvasPainter = QPainter(self) canvasPainter.drawImage(self.rect(), self.image, self.image.rect()) # this method will draw a line def draw_something(self): painter = QPainter(self.image) painter.setPen(QPen(Qt.black, 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) # drawing a line painter.drawLine(100, 100, 300, 300) # updating it to canvas self.update() # save method def save(self): # selecting file path filePath, _ = QFileDialog.getSaveFileName(self, \"Save Image\", \"\", \"PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) \") # if file path is blank return back if filePath == \"\": return # saving canvas at desired path self.image.save(filePath) # main methodif __name__ == \"__main__\": app = QApplication(sys.argv) window = Window() window.show() # looping for window sys.exit(app.exec())",
"e": 28709,
"s": 26389,
"text": null
},
{
"code": null,
"e": 28814,
"s": 28709,
"text": "Output : After running the code window will appear with a canvas of white color on which line is drawn. "
},
{
"code": null,
"e": 28873,
"s": 28814,
"text": "After clicking on the file menu save button will appear. "
},
{
"code": null,
"e": 28988,
"s": 28873,
"text": "When save button is pressed it will ask for the location and name and image will get saved at desirable location. "
},
{
"code": null,
"e": 29059,
"s": 28988,
"text": "This code will save the canvas in png format at the desired location. "
},
{
"code": null,
"e": 29068,
"s": 29059,
"text": "sweetyty"
},
{
"code": null,
"e": 29083,
"s": 29068,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29094,
"s": 29083,
"text": "Python-gui"
},
{
"code": null,
"e": 29106,
"s": 29094,
"text": "Python-PyQt"
},
{
"code": null,
"e": 29113,
"s": 29106,
"text": "Python"
},
{
"code": null,
"e": 29211,
"s": 29113,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29229,
"s": 29211,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29261,
"s": 29229,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29283,
"s": 29261,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29325,
"s": 29283,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29355,
"s": 29325,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29381,
"s": 29355,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29410,
"s": 29381,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29454,
"s": 29410,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29491,
"s": 29454,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Method Class | getTypeParameters() Method in Java - GeeksforGeeks
|
03 Jan, 2022
The java.lang.reflect.Method.getTypeParameters() method of Method class returns an array of TypeVariable objects declared by the generic declaration of this Method object, in declaration order. Elements of array represent the type variables objects declared by Method. An array of length 0 is returned by this getTypeParameters(), if the Method Object generic declaration contains no type variables.
Syntax:
public TypeVariable<Method>[] getTypeParameters()
Return Value: This method returns an array of TypeVariable objects declared by the generic declaration of this Method object
Exception: This method returns GenericSignatureFormatError if the generic signature of this Method object does not match to the format specified in The JVM Specification.
Below program illustrates getTypeParameters() method of Method class:
Example 1:
Explanation: This code fetches list of all Method of a class. These are then iterated through loop and the TypeVariable is fetched, if there are some TypeVariable defined at time of Declaration of those methods. If there are some TypeVariable available for those methods, then TypeVariable name is printed.
Java
/** Program Demonstrate getTypeParameters() method * of Method Class.*/import java.lang.reflect.Method;import java.lang.reflect.TypeVariable; public class GFG { // In this method, there is a // Type parameter N which extends Number class public <N extends Number> void getSampleMethod(N n) { } // create main method public static void main(String args[]) { try { // create class object for class name GFG Class c = GFG.class; // get list of all Method objects of class GFG Method[] methods = c.getMethods(); // loop through all methods and // try to get Type Parameter of Method for (Method m : methods) { // get TypeVariable array by getTypeParameters() method TypeVariable[] types = m.getTypeParameters(); // print Type Parameter details for every TypeVariable for (TypeVariable t : types) { // print type parameter name // along with there method name System.out.println("Type variable for Method Name " + m.getName() + " is " + t.getName()); } } } catch (Exception e) { // print Exception Message if // any exception occured in program e.printStackTrace(); } }}
Type variable for Method Name getSampleMethod is N
Example 2: In this program there are more than one type parameter of methods. In this program, the type parameter are fetched using getTypeParameter() function and prints details of those type parameters.
Java
/** Program Demonstrate getTypeParameters() method * of Method Class having more than one type parameter of methods*/import java.lang.*; public class GFG { // In this method, // there are three Type parameters // N which extends Number class, // E extends RuntimeException Class // and C extends Character class. public <N extends Number, E extends RuntimeException, C extends Character> void getSampleMethod(N n) throws E { } // In this method, // there are Two Type parameters : // A which extends the ArrayList class, // L extends the LinkedList class public <A extends ArrayList, L extends LinkedList> L SetSampleMethod(A a, L l) { return l; } // create main method of class public static void main(String args[]) { try { // create class object for // class name GFG to get methods list // of GFG class Class c = GFG.class; // get list of all Method objects of // class GFG in array of Methods Method[] methods = c.getMethods(); // loop through all methods and // try to get Type Parameter of Method for (Method m : methods) { // get TypeVariable array by // getTypeParameters method TypeVariable[] types = m.getTypeParameters(); // If there are 1 or more than 1 // type variables for the current // method of loop then print method name if (types.length > 0) System.out.println("\nType variable Details" + " for Method Name " + m.getName()); // print Type Parameter details // for Current Method of loop for (TypeVariable t : types) { // get bounds for current TypeVariable // and print the Name of TypeVariable and bounds Type[] bounds = t.getBounds(); // print TypeVariable name and Bounds System.out.println("Name : " + t.getName()); System.out.println("Bounds : " + Arrays.toString(bounds)); } } } catch (Exception e) { // print Exception message if some Exception occurs e.printStackTrace(); } }}
Type variable Details for Method Name getSampleMethod
Name : N
Bounds : [class java.lang.Number]
Name : E
Bounds : [class java.lang.RuntimeException]
Name : C
Bounds : [class java.lang.Character]
Type variable Details for Method Name SetSampleMethod
Name : A
Bounds : [class java.util.ArrayList]
Name : L
Bounds : [class java.util.LinkedList]
Reference:https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getTypeParameters–
surindertarika1234
java-basics
Java-Functions
Java-lang package
java-lang-reflect-package
Java-Method Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
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": 25641,
"s": 25613,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 26041,
"s": 25641,
"text": "The java.lang.reflect.Method.getTypeParameters() method of Method class returns an array of TypeVariable objects declared by the generic declaration of this Method object, in declaration order. Elements of array represent the type variables objects declared by Method. An array of length 0 is returned by this getTypeParameters(), if the Method Object generic declaration contains no type variables."
},
{
"code": null,
"e": 26049,
"s": 26041,
"text": "Syntax:"
},
{
"code": null,
"e": 26099,
"s": 26049,
"text": "public TypeVariable<Method>[] getTypeParameters()"
},
{
"code": null,
"e": 26224,
"s": 26099,
"text": "Return Value: This method returns an array of TypeVariable objects declared by the generic declaration of this Method object"
},
{
"code": null,
"e": 26395,
"s": 26224,
"text": "Exception: This method returns GenericSignatureFormatError if the generic signature of this Method object does not match to the format specified in The JVM Specification."
},
{
"code": null,
"e": 26465,
"s": 26395,
"text": "Below program illustrates getTypeParameters() method of Method class:"
},
{
"code": null,
"e": 26476,
"s": 26465,
"text": "Example 1:"
},
{
"code": null,
"e": 26783,
"s": 26476,
"text": "Explanation: This code fetches list of all Method of a class. These are then iterated through loop and the TypeVariable is fetched, if there are some TypeVariable defined at time of Declaration of those methods. If there are some TypeVariable available for those methods, then TypeVariable name is printed."
},
{
"code": null,
"e": 26788,
"s": 26783,
"text": "Java"
},
{
"code": "/** Program Demonstrate getTypeParameters() method * of Method Class.*/import java.lang.reflect.Method;import java.lang.reflect.TypeVariable; public class GFG { // In this method, there is a // Type parameter N which extends Number class public <N extends Number> void getSampleMethod(N n) { } // create main method public static void main(String args[]) { try { // create class object for class name GFG Class c = GFG.class; // get list of all Method objects of class GFG Method[] methods = c.getMethods(); // loop through all methods and // try to get Type Parameter of Method for (Method m : methods) { // get TypeVariable array by getTypeParameters() method TypeVariable[] types = m.getTypeParameters(); // print Type Parameter details for every TypeVariable for (TypeVariable t : types) { // print type parameter name // along with there method name System.out.println(\"Type variable for Method Name \" + m.getName() + \" is \" + t.getName()); } } } catch (Exception e) { // print Exception Message if // any exception occured in program e.printStackTrace(); } }}",
"e": 28259,
"s": 26788,
"text": null
},
{
"code": null,
"e": 28311,
"s": 28259,
"text": "Type variable for Method Name getSampleMethod is N\n"
},
{
"code": null,
"e": 28516,
"s": 28311,
"text": "Example 2: In this program there are more than one type parameter of methods. In this program, the type parameter are fetched using getTypeParameter() function and prints details of those type parameters."
},
{
"code": null,
"e": 28521,
"s": 28516,
"text": "Java"
},
{
"code": "/** Program Demonstrate getTypeParameters() method * of Method Class having more than one type parameter of methods*/import java.lang.*; public class GFG { // In this method, // there are three Type parameters // N which extends Number class, // E extends RuntimeException Class // and C extends Character class. public <N extends Number, E extends RuntimeException, C extends Character> void getSampleMethod(N n) throws E { } // In this method, // there are Two Type parameters : // A which extends the ArrayList class, // L extends the LinkedList class public <A extends ArrayList, L extends LinkedList> L SetSampleMethod(A a, L l) { return l; } // create main method of class public static void main(String args[]) { try { // create class object for // class name GFG to get methods list // of GFG class Class c = GFG.class; // get list of all Method objects of // class GFG in array of Methods Method[] methods = c.getMethods(); // loop through all methods and // try to get Type Parameter of Method for (Method m : methods) { // get TypeVariable array by // getTypeParameters method TypeVariable[] types = m.getTypeParameters(); // If there are 1 or more than 1 // type variables for the current // method of loop then print method name if (types.length > 0) System.out.println(\"\\nType variable Details\" + \" for Method Name \" + m.getName()); // print Type Parameter details // for Current Method of loop for (TypeVariable t : types) { // get bounds for current TypeVariable // and print the Name of TypeVariable and bounds Type[] bounds = t.getBounds(); // print TypeVariable name and Bounds System.out.println(\"Name : \" + t.getName()); System.out.println(\"Bounds : \" + Arrays.toString(bounds)); } } } catch (Exception e) { // print Exception message if some Exception occurs e.printStackTrace(); } }}",
"e": 31094,
"s": 28521,
"text": null
},
{
"code": null,
"e": 31439,
"s": 31094,
"text": "Type variable Details for Method Name getSampleMethod\nName : N\nBounds : [class java.lang.Number]\nName : E\nBounds : [class java.lang.RuntimeException]\nName : C\nBounds : [class java.lang.Character]\n\nType variable Details for Method Name SetSampleMethod\nName : A\nBounds : [class java.util.ArrayList]\nName : L\nBounds : [class java.util.LinkedList]\n"
},
{
"code": null,
"e": 31540,
"s": 31439,
"text": "Reference:https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getTypeParameters–"
},
{
"code": null,
"e": 31559,
"s": 31540,
"text": "surindertarika1234"
},
{
"code": null,
"e": 31571,
"s": 31559,
"text": "java-basics"
},
{
"code": null,
"e": 31586,
"s": 31571,
"text": "Java-Functions"
},
{
"code": null,
"e": 31604,
"s": 31586,
"text": "Java-lang package"
},
{
"code": null,
"e": 31630,
"s": 31604,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 31648,
"s": 31630,
"text": "Java-Method Class"
},
{
"code": null,
"e": 31653,
"s": 31648,
"text": "Java"
},
{
"code": null,
"e": 31658,
"s": 31653,
"text": "Java"
},
{
"code": null,
"e": 31756,
"s": 31658,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31807,
"s": 31756,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31837,
"s": 31807,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31852,
"s": 31837,
"text": "Stream In Java"
},
{
"code": null,
"e": 31883,
"s": 31852,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 31901,
"s": 31883,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31933,
"s": 31901,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31953,
"s": 31933,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31985,
"s": 31953,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32009,
"s": 31985,
"text": "Singleton Class in Java"
}
] |
Python | sympy.crt() method - GeeksforGeeks
|
17 Sep, 2019
With the help of sympy.crt() method, we can implement the Chinese Remainder Theorem in SymPy.
Syntax: crt(m, v)
Parameter:m – It denotes a list of integers.v – It denotes a list of integers.
Returns: Returns a tuple of integers where the first element is the required result.
Example #1:
# import crt() method from sympyfrom sympy.ntheory.modular import crt m = [5, 7]v = [1, 3] # Use crt() method crt_m_v = crt(m, v) print("Result of the Chinese Remainder Theorem = {} ".format(crt_m_v[0]))
Output:
Result of the Chinese Remainder Theorem = 31
Example #2:
# import crt() method from sympyfrom sympy.ntheory.modular import crt m = [99, 97, 95]v = [49, 76, 65] # Use crt() method crt_m_v = crt(m, v) print("Result of the Chinese Remainder Theorem = {} ".format(crt_m_v[0]))
Output:
Result of the Chinese Remainder Theorem = 639985
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25873,
"s": 25845,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 25967,
"s": 25873,
"text": "With the help of sympy.crt() method, we can implement the Chinese Remainder Theorem in SymPy."
},
{
"code": null,
"e": 25985,
"s": 25967,
"text": "Syntax: crt(m, v)"
},
{
"code": null,
"e": 26064,
"s": 25985,
"text": "Parameter:m – It denotes a list of integers.v – It denotes a list of integers."
},
{
"code": null,
"e": 26149,
"s": 26064,
"text": "Returns: Returns a tuple of integers where the first element is the required result."
},
{
"code": null,
"e": 26161,
"s": 26149,
"text": "Example #1:"
},
{
"code": "# import crt() method from sympyfrom sympy.ntheory.modular import crt m = [5, 7]v = [1, 3] # Use crt() method crt_m_v = crt(m, v) print(\"Result of the Chinese Remainder Theorem = {} \".format(crt_m_v[0]))",
"e": 26373,
"s": 26161,
"text": null
},
{
"code": null,
"e": 26381,
"s": 26373,
"text": "Output:"
},
{
"code": null,
"e": 26428,
"s": 26381,
"text": "Result of the Chinese Remainder Theorem = 31 \n"
},
{
"code": null,
"e": 26440,
"s": 26428,
"text": "Example #2:"
},
{
"code": "# import crt() method from sympyfrom sympy.ntheory.modular import crt m = [99, 97, 95]v = [49, 76, 65] # Use crt() method crt_m_v = crt(m, v) print(\"Result of the Chinese Remainder Theorem = {} \".format(crt_m_v[0]))",
"e": 26664,
"s": 26440,
"text": null
},
{
"code": null,
"e": 26672,
"s": 26664,
"text": "Output:"
},
{
"code": null,
"e": 26723,
"s": 26672,
"text": "Result of the Chinese Remainder Theorem = 639985 \n"
},
{
"code": null,
"e": 26729,
"s": 26723,
"text": "SymPy"
},
{
"code": null,
"e": 26736,
"s": 26729,
"text": "Python"
},
{
"code": null,
"e": 26834,
"s": 26736,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26852,
"s": 26834,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26887,
"s": 26852,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26919,
"s": 26887,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26941,
"s": 26919,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26983,
"s": 26941,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27013,
"s": 26983,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27039,
"s": 27013,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27068,
"s": 27039,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27112,
"s": 27068,
"text": "Reading and Writing to text files in Python"
}
] |
How to publish a ReactJS component to NPM ? - GeeksforGeeks
|
17 Jun, 2021
Follow these simple steps in order to publish your own ReactJS component to NPM.
Step 1: Initial Setup
In order to publish any ReactJS Component to npm (node package manager), first we have to create a React component in the React app. Following are the instructions for creating any react app.
Create a React application using the following command:
npx create-react-app foldername
After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 2: Creating the Component
Open your project folder in your code editor you will see many folders, depending upon your choice make a folder called components, like in our case we had made the folder inside the src folder as shown below.
Then go to your created folder and create your ReactJs Component, like in your case we have created a Navbar component using react-bootstrap called Header.js.
Header.js
import React from "react";import { Nav, Navbar, NavDropdown, Form, FormControl, Button,} from "react-bootstrap"; const Header = () => { return ( <> <Navbar bg="light" expand="lg"> <Navbar.Brand href="#home"> ReactNavbarComponent </Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="ml-auto"> <Nav.Link href="#home">Home</Nav.Link> <Nav.Link href="#link">Link</Nav.Link> <NavDropdown title="Dropdown" id="basic-nav-dropdown"> <NavDropdown.Item href="#action/3.1"> Action </NavDropdown.Item> <NavDropdown.Item href="#action/3.2"> Another action </NavDropdown.Item> <NavDropdown.Item href="#action/3.3"> Something </NavDropdown.Item> <NavDropdown.Divider /> <NavDropdown.Item href="#action/3.4"> Separated link </NavDropdown.Item> </NavDropdown> </Nav> <Form inline> <FormControl type="text" placeholder="Search" className="mr-sm-2" /> <Button variant="outline-success"> Search </Button> </Form> </Navbar.Collapse> </Navbar> </> );}; export default Header;
Step 3: Environment Setup for Publishing
Go to the components folder using your terminal & type npm init. You will see the following things in your command line.
Use `npm install <pkg>` afterward to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (components) react-navbar
version: (1.0.0)
description: React-navbar
entry point: (Header.js) # Entry Point publishing
test command:
git repository:
keywords:
author: <Name>
license: (ISC)
About to write to C:\Users\Desktop\Tcw\app\src\components\package.json:
{
"name": "react-navbar",
"version": "1.0.0",
"description": "React-navbar",
"main": "Header.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "<Name>",
"license": "ISC"
}
Is this OK? (yes)
Install all the dependencies needed for your component as peer dependencies. For this first, you have to go to your terminal and type the following command:
npm install (your dependences name)
For our example, we have to install these two dependencies for our component using the following command:
npm install react
npm install react-bootstrap
Now go to the package.json file & change the dependencies as peer dependencies and delete the node_module folder from the components folder.
Now if you write npm install your terminal you will see the following instructions:
npm WARN react-navbar@1.0.0 requires a peer of react@^17.0.2 but none is installed. You must install peer dependencies yourself.npm WARN react-navbar@1.0.0 requires a peer of react-bootstrap@^1.6.0 but none is installed. You must install peer dependencies yourself.npm WARN react-navbar@1.0.0 No repository field.
up to date in 3.59sfound 0 vulnerabilities
Step 4: Publishing to npm
Go to the npm website and create an account using your mail ID and password. Make sure that you are in the current directory that is the components directory and type the following commands:
npm login
# Use your username and password what you have created in the npm website
# Then run this command
npm publish
Now your ReactJs component has been successfully published into the npm. Go to your npm account and there you can see your package as shown below.
Node-npm
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26097,
"s": 26069,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 26178,
"s": 26097,
"text": "Follow these simple steps in order to publish your own ReactJS component to NPM."
},
{
"code": null,
"e": 26200,
"s": 26178,
"text": "Step 1: Initial Setup"
},
{
"code": null,
"e": 26392,
"s": 26200,
"text": "In order to publish any ReactJS Component to npm (node package manager), first we have to create a React component in the React app. Following are the instructions for creating any react app."
},
{
"code": null,
"e": 26448,
"s": 26392,
"text": "Create a React application using the following command:"
},
{
"code": null,
"e": 26480,
"s": 26448,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 26572,
"s": 26480,
"text": "After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 26586,
"s": 26572,
"text": "cd foldername"
},
{
"code": null,
"e": 26617,
"s": 26586,
"text": "Step 2: Creating the Component"
},
{
"code": null,
"e": 26827,
"s": 26617,
"text": "Open your project folder in your code editor you will see many folders, depending upon your choice make a folder called components, like in our case we had made the folder inside the src folder as shown below."
},
{
"code": null,
"e": 26986,
"s": 26827,
"text": "Then go to your created folder and create your ReactJs Component, like in your case we have created a Navbar component using react-bootstrap called Header.js."
},
{
"code": null,
"e": 26996,
"s": 26986,
"text": "Header.js"
},
{
"code": "import React from \"react\";import { Nav, Navbar, NavDropdown, Form, FormControl, Button,} from \"react-bootstrap\"; const Header = () => { return ( <> <Navbar bg=\"light\" expand=\"lg\"> <Navbar.Brand href=\"#home\"> ReactNavbarComponent </Navbar.Brand> <Navbar.Toggle aria-controls=\"basic-navbar-nav\" /> <Navbar.Collapse id=\"basic-navbar-nav\"> <Nav className=\"ml-auto\"> <Nav.Link href=\"#home\">Home</Nav.Link> <Nav.Link href=\"#link\">Link</Nav.Link> <NavDropdown title=\"Dropdown\" id=\"basic-nav-dropdown\"> <NavDropdown.Item href=\"#action/3.1\"> Action </NavDropdown.Item> <NavDropdown.Item href=\"#action/3.2\"> Another action </NavDropdown.Item> <NavDropdown.Item href=\"#action/3.3\"> Something </NavDropdown.Item> <NavDropdown.Divider /> <NavDropdown.Item href=\"#action/3.4\"> Separated link </NavDropdown.Item> </NavDropdown> </Nav> <Form inline> <FormControl type=\"text\" placeholder=\"Search\" className=\"mr-sm-2\" /> <Button variant=\"outline-success\"> Search </Button> </Form> </Navbar.Collapse> </Navbar> </> );}; export default Header;",
"e": 28893,
"s": 26996,
"text": null
},
{
"code": null,
"e": 28934,
"s": 28893,
"text": "Step 3: Environment Setup for Publishing"
},
{
"code": null,
"e": 29055,
"s": 28934,
"text": "Go to the components folder using your terminal & type npm init. You will see the following things in your command line."
},
{
"code": null,
"e": 29738,
"s": 29055,
"text": "Use `npm install <pkg>` afterward to install a package and\nsave it as a dependency in the package.json file.\n\nPress ^C at any time to quit.\npackage name: (components) react-navbar\nversion: (1.0.0)\ndescription: React-navbar\nentry point: (Header.js) # Entry Point publishing\ntest command:\ngit repository:\nkeywords:\nauthor: <Name>\nlicense: (ISC)\nAbout to write to C:\\Users\\Desktop\\Tcw\\app\\src\\components\\package.json:\n{\n \"name\": \"react-navbar\",\n \"version\": \"1.0.0\",\n \"description\": \"React-navbar\",\n \"main\": \"Header.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"<Name>\",\n \"license\": \"ISC\"\n}\n\n\nIs this OK? (yes)"
},
{
"code": null,
"e": 29896,
"s": 29738,
"text": "Install all the dependencies needed for your component as peer dependencies. For this first, you have to go to your terminal and type the following command: "
},
{
"code": null,
"e": 29932,
"s": 29896,
"text": "npm install (your dependences name)"
},
{
"code": null,
"e": 30038,
"s": 29932,
"text": "For our example, we have to install these two dependencies for our component using the following command:"
},
{
"code": null,
"e": 30084,
"s": 30038,
"text": "npm install react\nnpm install react-bootstrap"
},
{
"code": null,
"e": 30225,
"s": 30084,
"text": "Now go to the package.json file & change the dependencies as peer dependencies and delete the node_module folder from the components folder."
},
{
"code": null,
"e": 30309,
"s": 30225,
"text": "Now if you write npm install your terminal you will see the following instructions:"
},
{
"code": null,
"e": 30623,
"s": 30309,
"text": "npm WARN react-navbar@1.0.0 requires a peer of react@^17.0.2 but none is installed. You must install peer dependencies yourself.npm WARN react-navbar@1.0.0 requires a peer of react-bootstrap@^1.6.0 but none is installed. You must install peer dependencies yourself.npm WARN react-navbar@1.0.0 No repository field."
},
{
"code": null,
"e": 30666,
"s": 30623,
"text": "up to date in 3.59sfound 0 vulnerabilities"
},
{
"code": null,
"e": 30692,
"s": 30666,
"text": "Step 4: Publishing to npm"
},
{
"code": null,
"e": 30883,
"s": 30692,
"text": "Go to the npm website and create an account using your mail ID and password. Make sure that you are in the current directory that is the components directory and type the following commands:"
},
{
"code": null,
"e": 31004,
"s": 30883,
"text": "npm login \n# Use your username and password what you have created in the npm website\n# Then run this command\nnpm publish"
},
{
"code": null,
"e": 31151,
"s": 31004,
"text": "Now your ReactJs component has been successfully published into the npm. Go to your npm account and there you can see your package as shown below."
},
{
"code": null,
"e": 31160,
"s": 31151,
"text": "Node-npm"
},
{
"code": null,
"e": 31167,
"s": 31160,
"text": "Picked"
},
{
"code": null,
"e": 31183,
"s": 31167,
"text": "React-Questions"
},
{
"code": null,
"e": 31191,
"s": 31183,
"text": "ReactJS"
},
{
"code": null,
"e": 31208,
"s": 31191,
"text": "Web Technologies"
},
{
"code": null,
"e": 31306,
"s": 31208,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31333,
"s": 31306,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 31375,
"s": 31333,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 31413,
"s": 31375,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 31448,
"s": 31413,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 31506,
"s": 31448,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 31546,
"s": 31506,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31579,
"s": 31546,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31624,
"s": 31579,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31674,
"s": 31624,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
__getitem__() in Python - GeeksforGeeks
|
26 Mar, 2020
In Python, everything is an object. There are a lot of ‘ordinary’ system call methods on these objects behind the scene which is not visible to the programmer. Here come what are called as magic methods. Magic methods in python are special methods that are invoked when we run any ordinary python code. To differentiate them with normal functions, they have surrounding double underscores.
If we want to add a and b, we write the following syntax:
c = a + b
Internally it is called as:
c = a.__add__(b)
__getitem__() is a magic method in Python, which when used in a class, allows its instances to use the [] (indexer) operators. Say x is an instance of this class, then x[i] is roughly equivalent to type(x).__getitem__(x, i).
The method __getitem__(self, key) defines behavior for when an item is accessed, using the notation self[key]. This is also part of both the mutable and immutable container protocols.
Example:
# Code to demonstrate use# of __getitem__() in python class Test(object): # This function prints the type # of the object passed as well # as the object item def __getitem__(self, items): print (type(items), items) # Driver codetest = Test()test[5]test[5:65:5]test['GeeksforGeeks']test[1, 'x', 10.0]test['a':'z':2]test[object()]
Output:
<class 'int'> 5
<class 'slice'> slice(5, 65, 5)
<class 'str'> GeeksforGeeks
<class 'tuple'> (1, 'x', 10.0)
<class 'slice'> slice('a', 'z', 2)
<class 'object'> <object object at 0x7f75bcd6d0a0>
Unlike some other languages, Python basically lets you pass any object into the indexer. You may be surprised that the test[1, 'x', 10.0] actually parses. To the Python interpreter, that expression is equivalent to this: test.__getitem__((1, 'x', 10.0)). As you can see, the 1, ‘x’, 10.0 part is implicitly parsed as a tuple. The test[5:65:5] expression makes use of Python’s slice syntax. It is equivalent to this expression: test[slice(5, 65, 5)].
The __getitem__ magic method is usually used for list indexing, dictionary lookup, or accessing ranges of values. Considering how versatile it is, it’s probably one of Python’s most underutilized magic methods.
python-oop-concepts
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": 25537,
"s": 25509,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 25927,
"s": 25537,
"text": "In Python, everything is an object. There are a lot of ‘ordinary’ system call methods on these objects behind the scene which is not visible to the programmer. Here come what are called as magic methods. Magic methods in python are special methods that are invoked when we run any ordinary python code. To differentiate them with normal functions, they have surrounding double underscores."
},
{
"code": null,
"e": 25985,
"s": 25927,
"text": "If we want to add a and b, we write the following syntax:"
},
{
"code": null,
"e": 25996,
"s": 25985,
"text": "c = a + b\n"
},
{
"code": null,
"e": 26024,
"s": 25996,
"text": "Internally it is called as:"
},
{
"code": null,
"e": 26042,
"s": 26024,
"text": "c = a.__add__(b)\n"
},
{
"code": null,
"e": 26267,
"s": 26042,
"text": "__getitem__() is a magic method in Python, which when used in a class, allows its instances to use the [] (indexer) operators. Say x is an instance of this class, then x[i] is roughly equivalent to type(x).__getitem__(x, i)."
},
{
"code": null,
"e": 26451,
"s": 26267,
"text": "The method __getitem__(self, key) defines behavior for when an item is accessed, using the notation self[key]. This is also part of both the mutable and immutable container protocols."
},
{
"code": null,
"e": 26460,
"s": 26451,
"text": "Example:"
},
{
"code": "# Code to demonstrate use# of __getitem__() in python class Test(object): # This function prints the type # of the object passed as well # as the object item def __getitem__(self, items): print (type(items), items) # Driver codetest = Test()test[5]test[5:65:5]test['GeeksforGeeks']test[1, 'x', 10.0]test['a':'z':2]test[object()]",
"e": 26819,
"s": 26460,
"text": null
},
{
"code": null,
"e": 26827,
"s": 26819,
"text": "Output:"
},
{
"code": null,
"e": 27021,
"s": 26827,
"text": "<class 'int'> 5\n<class 'slice'> slice(5, 65, 5)\n<class 'str'> GeeksforGeeks\n<class 'tuple'> (1, 'x', 10.0)\n<class 'slice'> slice('a', 'z', 2)\n<class 'object'> <object object at 0x7f75bcd6d0a0>\n"
},
{
"code": null,
"e": 27471,
"s": 27021,
"text": "Unlike some other languages, Python basically lets you pass any object into the indexer. You may be surprised that the test[1, 'x', 10.0] actually parses. To the Python interpreter, that expression is equivalent to this: test.__getitem__((1, 'x', 10.0)). As you can see, the 1, ‘x’, 10.0 part is implicitly parsed as a tuple. The test[5:65:5] expression makes use of Python’s slice syntax. It is equivalent to this expression: test[slice(5, 65, 5)]."
},
{
"code": null,
"e": 27682,
"s": 27471,
"text": "The __getitem__ magic method is usually used for list indexing, dictionary lookup, or accessing ranges of values. Considering how versatile it is, it’s probably one of Python’s most underutilized magic methods."
},
{
"code": null,
"e": 27702,
"s": 27682,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 27709,
"s": 27702,
"text": "Python"
},
{
"code": null,
"e": 27807,
"s": 27709,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27839,
"s": 27807,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27881,
"s": 27839,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27923,
"s": 27881,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27979,
"s": 27923,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28006,
"s": 27979,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28037,
"s": 28006,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28076,
"s": 28037,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28105,
"s": 28076,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28127,
"s": 28105,
"text": "Defaultdict in Python"
}
] |
Java Collections emptySet() Method with Examples - GeeksforGeeks
|
28 Dec, 2021
The emptySet() method is used to get the set that has no elements. This method is used in set collection. A set is a data structure that can store unique elements.
Syntax:
public static final <T> Set<T> emptySet()
Parameters: This method will take no parameters.
Return Type: It will return an empty set that is immutable.
Example 1:
Java program to create an empty set
Java
import java.util.*; public class GFG { // main method public static void main(String[] args) { // create an empty set Set<String> data = Collections.<String>emptySet(); // display System.out.println(data); }}
[]
Example 2:
In this program, we are going to create an empty set and add elements to the set. This method will return an error.
Java
import java.util.*; public class GFG { // main method public static void main(String[] args) { // create an empty set Set<String> data = Collections.<String>emptySet(); // add 3 elements data.add("ojaswi"); data.add("ramya"); data.add("deepu"); // display System.out.println(data); }}
Output:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractCollection.add(AbstractCollection.java:262)
at GFG.main(GFG.java:8)
Java-Collections-Class
Java-Functions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Internal Working of HashMap in Java
Comparator Interface in Java with Examples
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 25389,
"s": 25225,
"text": "The emptySet() method is used to get the set that has no elements. This method is used in set collection. A set is a data structure that can store unique elements."
},
{
"code": null,
"e": 25397,
"s": 25389,
"text": "Syntax:"
},
{
"code": null,
"e": 25442,
"s": 25397,
"text": "public static final <T> Set<T> emptySet() "
},
{
"code": null,
"e": 25491,
"s": 25442,
"text": "Parameters: This method will take no parameters."
},
{
"code": null,
"e": 25551,
"s": 25491,
"text": "Return Type: It will return an empty set that is immutable."
},
{
"code": null,
"e": 25562,
"s": 25551,
"text": "Example 1:"
},
{
"code": null,
"e": 25598,
"s": 25562,
"text": "Java program to create an empty set"
},
{
"code": null,
"e": 25603,
"s": 25598,
"text": "Java"
},
{
"code": "import java.util.*; public class GFG { // main method public static void main(String[] args) { // create an empty set Set<String> data = Collections.<String>emptySet(); // display System.out.println(data); }}",
"e": 25861,
"s": 25603,
"text": null
},
{
"code": null,
"e": 25865,
"s": 25861,
"text": "[]\n"
},
{
"code": null,
"e": 25876,
"s": 25865,
"text": "Example 2:"
},
{
"code": null,
"e": 25992,
"s": 25876,
"text": "In this program, we are going to create an empty set and add elements to the set. This method will return an error."
},
{
"code": null,
"e": 25997,
"s": 25992,
"text": "Java"
},
{
"code": "import java.util.*; public class GFG { // main method public static void main(String[] args) { // create an empty set Set<String> data = Collections.<String>emptySet(); // add 3 elements data.add(\"ojaswi\"); data.add(\"ramya\"); data.add(\"deepu\"); // display System.out.println(data); }}",
"e": 26361,
"s": 25997,
"text": null
},
{
"code": null,
"e": 26369,
"s": 26361,
"text": "Output:"
},
{
"code": null,
"e": 26533,
"s": 26369,
"text": "Exception in thread \"main\" java.lang.UnsupportedOperationException\n at java.util.AbstractCollection.add(AbstractCollection.java:262)\n at GFG.main(GFG.java:8)"
},
{
"code": null,
"e": 26556,
"s": 26533,
"text": "Java-Collections-Class"
},
{
"code": null,
"e": 26571,
"s": 26556,
"text": "Java-Functions"
},
{
"code": null,
"e": 26578,
"s": 26571,
"text": "Picked"
},
{
"code": null,
"e": 26583,
"s": 26578,
"text": "Java"
},
{
"code": null,
"e": 26588,
"s": 26583,
"text": "Java"
},
{
"code": null,
"e": 26686,
"s": 26588,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26701,
"s": 26686,
"text": "Stream In Java"
},
{
"code": null,
"e": 26722,
"s": 26701,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26741,
"s": 26722,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26771,
"s": 26741,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26817,
"s": 26771,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26834,
"s": 26817,
"text": "Generics in Java"
},
{
"code": null,
"e": 26855,
"s": 26834,
"text": "Introduction to Java"
},
{
"code": null,
"e": 26891,
"s": 26855,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 26934,
"s": 26891,
"text": "Comparator Interface in Java with Examples"
}
] |
MySQL | IF( ) Function - GeeksforGeeks
|
21 Nov, 2019
The MySQL IF() function is used for validating a condition. The IF() function returns a value if the condition is TRUE and another value if the condition is FALSE. The MySQL IF() function can return values that can be either numeric or strings depending upon the context in which the function is used.The IF() function accepts one parameter which is the condition to be evaluated.
Syntax:
IF(condition, true_value, false_value)
Parameters Used:
condition – It is used to specify the condition to be evaluated.
true_value – It is an optional parameter which is used to specify the value to be returned if the condition evaluates to be true.
false_value – It is an optional parameter which is used to specify the value to be returned if the condition evaluates to be false.
Return Value:The MySQL IF() function returns a value if the condition is TRUE or a different value if the condition is FALSE.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
MySQL 4.0
MySQL 3.23
Example-1: Implementing IF() function on a numeric condition and returning a string value.
SELECT IF(5<12, 'TRUE', 'FALSE');
Output:
TRUE
Example-2: Implementing IF() function to compare two strings.
SELECT IF(STRCMP('geeksforgeeks', 'gfg')=0, 'TRUE', 'FALSE');
Output:
FALSE
Example-3: Implementing IF() function on a numeric condition and returning a numeric value.
SELECT IF(5<12, '1', '0');
Output:
1
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DDL and DML in DBMS
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL - ORDER BY
How to Create a Table With Multiple Foreign Keys in SQL?
|
[
{
"code": null,
"e": 25335,
"s": 25307,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 25716,
"s": 25335,
"text": "The MySQL IF() function is used for validating a condition. The IF() function returns a value if the condition is TRUE and another value if the condition is FALSE. The MySQL IF() function can return values that can be either numeric or strings depending upon the context in which the function is used.The IF() function accepts one parameter which is the condition to be evaluated."
},
{
"code": null,
"e": 25724,
"s": 25716,
"text": "Syntax:"
},
{
"code": null,
"e": 25763,
"s": 25724,
"text": "IF(condition, true_value, false_value)"
},
{
"code": null,
"e": 25780,
"s": 25763,
"text": "Parameters Used:"
},
{
"code": null,
"e": 25845,
"s": 25780,
"text": "condition – It is used to specify the condition to be evaluated."
},
{
"code": null,
"e": 25975,
"s": 25845,
"text": "true_value – It is an optional parameter which is used to specify the value to be returned if the condition evaluates to be true."
},
{
"code": null,
"e": 26107,
"s": 25975,
"text": "false_value – It is an optional parameter which is used to specify the value to be returned if the condition evaluates to be false."
},
{
"code": null,
"e": 26233,
"s": 26107,
"text": "Return Value:The MySQL IF() function returns a value if the condition is TRUE or a different value if the condition is FALSE."
},
{
"code": null,
"e": 26262,
"s": 26233,
"text": "Supported Versions of MySQL:"
},
{
"code": null,
"e": 26272,
"s": 26262,
"text": "MySQL 5.7"
},
{
"code": null,
"e": 26282,
"s": 26272,
"text": "MySQL 5.6"
},
{
"code": null,
"e": 26292,
"s": 26282,
"text": "MySQL 5.5"
},
{
"code": null,
"e": 26302,
"s": 26292,
"text": "MySQL 5.1"
},
{
"code": null,
"e": 26312,
"s": 26302,
"text": "MySQL 5.0"
},
{
"code": null,
"e": 26322,
"s": 26312,
"text": "MySQL 4.1"
},
{
"code": null,
"e": 26332,
"s": 26322,
"text": "MySQL 4.0"
},
{
"code": null,
"e": 26343,
"s": 26332,
"text": "MySQL 3.23"
},
{
"code": null,
"e": 26434,
"s": 26343,
"text": "Example-1: Implementing IF() function on a numeric condition and returning a string value."
},
{
"code": null,
"e": 26469,
"s": 26434,
"text": "SELECT IF(5<12, 'TRUE', 'FALSE'); "
},
{
"code": null,
"e": 26477,
"s": 26469,
"text": "Output:"
},
{
"code": null,
"e": 26483,
"s": 26477,
"text": "TRUE "
},
{
"code": null,
"e": 26545,
"s": 26483,
"text": "Example-2: Implementing IF() function to compare two strings."
},
{
"code": null,
"e": 26608,
"s": 26545,
"text": "SELECT IF(STRCMP('geeksforgeeks', 'gfg')=0, 'TRUE', 'FALSE'); "
},
{
"code": null,
"e": 26616,
"s": 26608,
"text": "Output:"
},
{
"code": null,
"e": 26623,
"s": 26616,
"text": "FALSE "
},
{
"code": null,
"e": 26715,
"s": 26623,
"text": "Example-3: Implementing IF() function on a numeric condition and returning a numeric value."
},
{
"code": null,
"e": 26743,
"s": 26715,
"text": "SELECT IF(5<12, '1', '0'); "
},
{
"code": null,
"e": 26751,
"s": 26743,
"text": "Output:"
},
{
"code": null,
"e": 26754,
"s": 26751,
"text": "1 "
},
{
"code": null,
"e": 26760,
"s": 26754,
"text": "mysql"
},
{
"code": null,
"e": 26769,
"s": 26760,
"text": "SQLmysql"
},
{
"code": null,
"e": 26773,
"s": 26769,
"text": "SQL"
},
{
"code": null,
"e": 26777,
"s": 26773,
"text": "SQL"
},
{
"code": null,
"e": 26875,
"s": 26777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26899,
"s": 26875,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26910,
"s": 26899,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26976,
"s": 26910,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27009,
"s": 26976,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 27048,
"s": 27009,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 27093,
"s": 27048,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 27125,
"s": 27093,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 27164,
"s": 27125,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 27179,
"s": 27164,
"text": "SQL - ORDER BY"
}
] |
Effect of Bias in Neural Network - GeeksforGeeks
|
25 Sep, 2018
Neural Network is conceptually based on actual neuron of brain. Neurons are the basic units of a large neural network. A single neuron passes single forward based on input provided.
In Neural network, some inputs are provided to an artificial neuron, and with each input a weight is associated. Weight increases the steepness of activation function. This means weight decide how fast the activation function will trigger whereas bias is used to delay the triggering of the activation function.
For a typical neuron, if the inputs are x1, x2, and x3, then the synaptic weights to be applied to them are denoted as w1, w2, and w3.
Output is
y = f(x) = Σxiwi
where i is 1 to the number of inputs.
The weight shows the effectiveness of a particular input. More the weight of input, more it will have impact on network.
On the other hand Bias is like the intercept added in a linear equation. It is an additional parameter in the Neural Network which is used to adjust the output along with the weighted sum of the inputs to the neuron. Therefore Bias is a constant which helps the model in a way that it can fit best for the given data.
The processing done by a neuron is thus denoted as :
output = sum (weights * inputs) + bias
In above figure
y = mx+c
where
m = weight
and
c = bias
Now, Suppose if c was absent, then the graph will be formed like this:
Due to absence of bias, model will train over point passing through origin only, which is not in accordance with real-world scenario. Also with the introduction of bias, the model will become more flexible.
For Example:Suppose an activation function act() which get triggered on some input greater than 0.Now,
input1 = 1
weight1 = 2
input2 = 2
weight2 = 2
so
output = input1*weight1 + input2*weight2
output = 6
let
suppose act(output) = 1
Now a bias is introduced in output as
bias = -6
the output become 0.
act(0) = 0
so activation function will not trigger.
Here in graph, as it can be seen that when:
weight WI changed from 1.0 to 4.0
changed from 1.0 to 4.0
weight W2 changed from -0.5 to 1.5
changed from -0.5 to 1.5
On increasing the weight the steepness is increasing.
Therefore it can be inferred that
More the weight earlier activation function will trigger.
Here in graph below, when
Bias changed from -1.0 to -5.0
The change in bias is increasing the value of triggering activation function.
Therefore it can be inferred that from above graph that,
bias helps in controlling the value at which activation function will trigger.
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Election algorithm and distributed processing
Introduction to Internet of Things (IoT) | Set 1
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Introduction to Parallel Computing
|
[
{
"code": null,
"e": 25919,
"s": 25891,
"text": "\n25 Sep, 2018"
},
{
"code": null,
"e": 26101,
"s": 25919,
"text": "Neural Network is conceptually based on actual neuron of brain. Neurons are the basic units of a large neural network. A single neuron passes single forward based on input provided."
},
{
"code": null,
"e": 26413,
"s": 26101,
"text": "In Neural network, some inputs are provided to an artificial neuron, and with each input a weight is associated. Weight increases the steepness of activation function. This means weight decide how fast the activation function will trigger whereas bias is used to delay the triggering of the activation function."
},
{
"code": null,
"e": 26548,
"s": 26413,
"text": "For a typical neuron, if the inputs are x1, x2, and x3, then the synaptic weights to be applied to them are denoted as w1, w2, and w3."
},
{
"code": null,
"e": 26558,
"s": 26548,
"text": "Output is"
},
{
"code": null,
"e": 26579,
"s": 26558,
"text": "y = f(x) = Σxiwi"
},
{
"code": null,
"e": 26617,
"s": 26579,
"text": "where i is 1 to the number of inputs."
},
{
"code": null,
"e": 26738,
"s": 26617,
"text": "The weight shows the effectiveness of a particular input. More the weight of input, more it will have impact on network."
},
{
"code": null,
"e": 27056,
"s": 26738,
"text": "On the other hand Bias is like the intercept added in a linear equation. It is an additional parameter in the Neural Network which is used to adjust the output along with the weighted sum of the inputs to the neuron. Therefore Bias is a constant which helps the model in a way that it can fit best for the given data."
},
{
"code": null,
"e": 27109,
"s": 27056,
"text": "The processing done by a neuron is thus denoted as :"
},
{
"code": null,
"e": 27150,
"s": 27109,
"text": "output = sum (weights * inputs) + bias"
},
{
"code": null,
"e": 27166,
"s": 27150,
"text": "In above figure"
},
{
"code": null,
"e": 27175,
"s": 27166,
"text": "y = mx+c"
},
{
"code": null,
"e": 27181,
"s": 27175,
"text": "where"
},
{
"code": null,
"e": 27194,
"s": 27181,
"text": "m = weight"
},
{
"code": null,
"e": 27198,
"s": 27194,
"text": "and"
},
{
"code": null,
"e": 27209,
"s": 27198,
"text": "c = bias"
},
{
"code": null,
"e": 27280,
"s": 27209,
"text": "Now, Suppose if c was absent, then the graph will be formed like this:"
},
{
"code": null,
"e": 27487,
"s": 27280,
"text": "Due to absence of bias, model will train over point passing through origin only, which is not in accordance with real-world scenario. Also with the introduction of bias, the model will become more flexible."
},
{
"code": null,
"e": 27590,
"s": 27487,
"text": "For Example:Suppose an activation function act() which get triggered on some input greater than 0.Now,"
},
{
"code": null,
"e": 27601,
"s": 27590,
"text": "input1 = 1"
},
{
"code": null,
"e": 27613,
"s": 27601,
"text": "weight1 = 2"
},
{
"code": null,
"e": 27624,
"s": 27613,
"text": "input2 = 2"
},
{
"code": null,
"e": 27636,
"s": 27624,
"text": "weight2 = 2"
},
{
"code": null,
"e": 27639,
"s": 27636,
"text": "so"
},
{
"code": null,
"e": 27682,
"s": 27639,
"text": "output = input1*weight1 + input2*weight2"
},
{
"code": null,
"e": 27695,
"s": 27682,
"text": "output = 6"
},
{
"code": null,
"e": 27699,
"s": 27695,
"text": "let"
},
{
"code": null,
"e": 27725,
"s": 27699,
"text": "suppose act(output) = 1"
},
{
"code": null,
"e": 27763,
"s": 27725,
"text": "Now a bias is introduced in output as"
},
{
"code": null,
"e": 27775,
"s": 27763,
"text": "bias = -6"
},
{
"code": null,
"e": 27796,
"s": 27775,
"text": "the output become 0."
},
{
"code": null,
"e": 27809,
"s": 27796,
"text": "act(0) = 0"
},
{
"code": null,
"e": 27850,
"s": 27809,
"text": "so activation function will not trigger."
},
{
"code": null,
"e": 27894,
"s": 27850,
"text": "Here in graph, as it can be seen that when:"
},
{
"code": null,
"e": 27930,
"s": 27894,
"text": "weight WI changed from 1.0 to 4.0 "
},
{
"code": null,
"e": 27957,
"s": 27930,
"text": " changed from 1.0 to 4.0 "
},
{
"code": null,
"e": 27994,
"s": 27957,
"text": "weight W2 changed from -0.5 to 1.5 "
},
{
"code": null,
"e": 28022,
"s": 27994,
"text": " changed from -0.5 to 1.5 "
},
{
"code": null,
"e": 28076,
"s": 28022,
"text": "On increasing the weight the steepness is increasing."
},
{
"code": null,
"e": 28110,
"s": 28076,
"text": "Therefore it can be inferred that"
},
{
"code": null,
"e": 28168,
"s": 28110,
"text": "More the weight earlier activation function will trigger."
},
{
"code": null,
"e": 28194,
"s": 28168,
"text": "Here in graph below, when"
},
{
"code": null,
"e": 28226,
"s": 28194,
"text": "Bias changed from -1.0 to -5.0"
},
{
"code": null,
"e": 28304,
"s": 28226,
"text": "The change in bias is increasing the value of triggering activation function."
},
{
"code": null,
"e": 28361,
"s": 28304,
"text": "Therefore it can be inferred that from above graph that,"
},
{
"code": null,
"e": 28440,
"s": 28361,
"text": "bias helps in controlling the value at which activation function will trigger."
},
{
"code": null,
"e": 28445,
"s": 28440,
"text": "Misc"
},
{
"code": null,
"e": 28450,
"s": 28445,
"text": "Misc"
},
{
"code": null,
"e": 28455,
"s": 28450,
"text": "Misc"
},
{
"code": null,
"e": 28553,
"s": 28455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28574,
"s": 28553,
"text": "Activation Functions"
},
{
"code": null,
"e": 28612,
"s": 28574,
"text": "Characteristics of Internet of Things"
},
{
"code": null,
"e": 28648,
"s": 28612,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 28683,
"s": 28648,
"text": "Sensors in Internet of Things(IoT)"
},
{
"code": null,
"e": 28722,
"s": 28683,
"text": "Challenges in Internet of things (IoT)"
},
{
"code": null,
"e": 28768,
"s": 28722,
"text": "Election algorithm and distributed processing"
},
{
"code": null,
"e": 28817,
"s": 28768,
"text": "Introduction to Internet of Things (IoT) | Set 1"
},
{
"code": null,
"e": 28849,
"s": 28817,
"text": "Introduction to Electronic Mail"
},
{
"code": null,
"e": 28899,
"s": 28849,
"text": "Communication Models in IoT (Internet of Things )"
}
] |
Count of triplets in an Array such that A[i] * A[j] = A[k] and i < j < k - GeeksforGeeks
|
24 May, 2021
Given an array A[ ] consisting of N positive integers, the task is to find the number of triplets A[i], A[j] & A[k] in the array such that i < j < k and A[i] * A[j] = A[k].
Examples:
Input: N = 5, A[ ] = {2, 3, 4, 6, 12} Output: 3 Explanation: The valid triplets from the given array are: (A[0], A[1], A[3]) = (2, 3, 6) where (2*3 = 6) (A[0], A[3], A[4]) = (2, 6, 12) where (2*6 = 12) (A[1], A[2], A[4]) = (3, 4, 12) where (3*4 = 12) Hence, a total of 3 triplets exists which satisfies the given condition.Input: N = 3, A[ ] = {1, 1, 1} Output: 1 Explanation: The only valid triplet is (A[0], A[1], A[2]) = (1, 1, 1)
Naive Approach: The simplest approach to solve the problem is to generate all possible triplets and for each triplet, check if it satisfies the required condition. If found to be true, increase the count of triplets. After complete traversal of the array and generating all possible triplets, print the final count. Time Complexity: O(N3) Auxiliary Space: O(1)Efficient Approach: The above approach can be optimized using Two Pointers and HashMap. Follow the steps below to solve the problem:
Initialize a Map to store frequencies of array elements.
Iterate over the array in reverse, i.e. loop with a variable j in the range [N – 2, 1].
For every j, increase the count of A[j + 1] in the map. Iterate over the range [0, j – 1] using variable i and check if A[i] * A[j] is present in the map or not.
If A[i] * A[j] is found in the map, increase the count of triplets by the frequency of A[i] * A[j] stored in the map.
After complete traversal of the array, print the final count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Returns total number of// valid triplets possibleint countTriplets(int A[], int N){ // Stores the count int ans = 0; // Map to store frequency // of array elements map<int, int> map; for (int j = N - 2; j >= 1; j--) { // Increment the frequency // of A[j+1] as it can be // a valid A[k] map[A[j + 1]]++; for (int i = 0; i < j; i++) { int target = A[i] * A[j]; // If target exists in the map if (map.find(target) != map.end()) ans += map[target]; } } // Return the final count return ans;} // Driver Codeint main(){ int N = 5; int A[] = { 2, 3, 4, 6, 12 }; cout << countTriplets(A, N); return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Returns total number of// valid triplets possiblestatic int countTriplets(int A[], int N){ // Stores the count int ans = 0; // Map to store frequency // of array elements HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int j = N - 2; j >= 1; j--) { // Increment the frequency // of A[j+1] as it can be // a valid A[k] if(map.containsKey(A[j + 1])) map.put(A[j + 1], map.get(A[j + 1]) + 1); else map.put(A[j + 1], 1); for(int i = 0; i < j; i++) { int target = A[i] * A[j]; // If target exists in the map if (map.containsKey(target)) ans += map.get(target); } } // Return the final count return ans;} // Driver Codepublic static void main(String[] args){ int N = 5; int A[] = { 2, 3, 4, 6, 12 }; System.out.print(countTriplets(A, N));}} // This code is contributed by sapnasingh4991
# Python3 program for the above approachfrom collections import defaultdict # Returns total number of# valid triplets possibledef countTriplets(A, N): # Stores the count ans = 0 # Map to store frequency # of array elements map = defaultdict(lambda: 0) for j in range(N - 2, 0, -1): # Increment the frequency # of A[j+1] as it can be # a valid A[k] map[A[j + 1]] += 1 for i in range(j): target = A[i] * A[j] # If target exists in the map if(target in map.keys()): ans += map[target] # Return the final count return ans # Driver codeif __name__ == '__main__': N = 5 A = [ 2, 3, 4, 6, 12 ] print(countTriplets(A, N)) # This code is contributed by Shivam Singh
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Returns total number of// valid triplets possiblestatic int countTriplets(int []A, int N){ // Stores the count int ans = 0; // Map to store frequency // of array elements Dictionary<int, int> map = new Dictionary<int, int>(); for(int j = N - 2; j >= 1; j--) { // Increment the frequency // of A[j+1] as it can be // a valid A[k] if(map.ContainsKey(A[j + 1])) map[A[j + 1]] = map[A[j + 1]] + 1; else map.Add(A[j + 1], 1); for(int i = 0; i < j; i++) { int target = A[i] * A[j]; // If target exists in the map if (map.ContainsKey(target)) ans += map[target]; } } // Return the readonly count return ans;} // Driver Codepublic static void Main(String[] args){ int N = 5; int []A = { 2, 3, 4, 6, 12 }; Console.Write(countTriplets(A, N));}} // This code is contributed by sapnasingh4991
<script> // Javascript program to implement// the above approach // Returns total number of// valid triplets possiblefunction countTriplets(A, N){ // Stores the count let ans = 0; // Map to store frequency // of array elements let map = new Map(); for(let j = N - 2; j >= 1; j--) { // Increment the frequency // of A[j+1] as it can be // a valid A[k] if(map.has(A[j + 1])) map.set(A[j + 1], map.get(A[j + 1]) + 1); else map.set(A[j + 1], 1); for(let i = 0; i < j; i++) { let target = A[i] * A[j]; // If target exists in the map if (map.has(target)) ans += map.get(target); } } // Return the final count return ans;} // Driver code let N = 5; let A = [ 2, 3, 4, 6, 12 ]; document.write(countTriplets(A, N)); // This code is contributed by souravghosh0416.</script>
3
Time Complexity: O(N2) Auxiliary Space: O(N)
SHIVAMSINGH67
sapnasingh4991
souravghosh0416
cpp-map
frequency-counting
two-pointer-algorithm
Arrays
Hash
Mathematical
Searching
two-pointer-algorithm
Arrays
Searching
Hash
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
Sort string of characters
|
[
{
"code": null,
"e": 26469,
"s": 26441,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 26642,
"s": 26469,
"text": "Given an array A[ ] consisting of N positive integers, the task is to find the number of triplets A[i], A[j] & A[k] in the array such that i < j < k and A[i] * A[j] = A[k]."
},
{
"code": null,
"e": 26652,
"s": 26642,
"text": "Examples:"
},
{
"code": null,
"e": 27088,
"s": 26652,
"text": "Input: N = 5, A[ ] = {2, 3, 4, 6, 12} Output: 3 Explanation: The valid triplets from the given array are: (A[0], A[1], A[3]) = (2, 3, 6) where (2*3 = 6) (A[0], A[3], A[4]) = (2, 6, 12) where (2*6 = 12) (A[1], A[2], A[4]) = (3, 4, 12) where (3*4 = 12) Hence, a total of 3 triplets exists which satisfies the given condition.Input: N = 3, A[ ] = {1, 1, 1} Output: 1 Explanation: The only valid triplet is (A[0], A[1], A[2]) = (1, 1, 1) "
},
{
"code": null,
"e": 27583,
"s": 27088,
"text": "Naive Approach: The simplest approach to solve the problem is to generate all possible triplets and for each triplet, check if it satisfies the required condition. If found to be true, increase the count of triplets. After complete traversal of the array and generating all possible triplets, print the final count. Time Complexity: O(N3) Auxiliary Space: O(1)Efficient Approach: The above approach can be optimized using Two Pointers and HashMap. Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 27640,
"s": 27583,
"text": "Initialize a Map to store frequencies of array elements."
},
{
"code": null,
"e": 27728,
"s": 27640,
"text": "Iterate over the array in reverse, i.e. loop with a variable j in the range [N – 2, 1]."
},
{
"code": null,
"e": 27890,
"s": 27728,
"text": "For every j, increase the count of A[j + 1] in the map. Iterate over the range [0, j – 1] using variable i and check if A[i] * A[j] is present in the map or not."
},
{
"code": null,
"e": 28008,
"s": 27890,
"text": "If A[i] * A[j] is found in the map, increase the count of triplets by the frequency of A[i] * A[j] stored in the map."
},
{
"code": null,
"e": 28070,
"s": 28008,
"text": "After complete traversal of the array, print the final count."
},
{
"code": null,
"e": 28122,
"s": 28070,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28126,
"s": 28122,
"text": "C++"
},
{
"code": null,
"e": 28131,
"s": 28126,
"text": "Java"
},
{
"code": null,
"e": 28139,
"s": 28131,
"text": "Python3"
},
{
"code": null,
"e": 28142,
"s": 28139,
"text": "C#"
},
{
"code": null,
"e": 28153,
"s": 28142,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Returns total number of// valid triplets possibleint countTriplets(int A[], int N){ // Stores the count int ans = 0; // Map to store frequency // of array elements map<int, int> map; for (int j = N - 2; j >= 1; j--) { // Increment the frequency // of A[j+1] as it can be // a valid A[k] map[A[j + 1]]++; for (int i = 0; i < j; i++) { int target = A[i] * A[j]; // If target exists in the map if (map.find(target) != map.end()) ans += map[target]; } } // Return the final count return ans;} // Driver Codeint main(){ int N = 5; int A[] = { 2, 3, 4, 6, 12 }; cout << countTriplets(A, N); return 0;}",
"e": 28998,
"s": 28153,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Returns total number of// valid triplets possiblestatic int countTriplets(int A[], int N){ // Stores the count int ans = 0; // Map to store frequency // of array elements HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int j = N - 2; j >= 1; j--) { // Increment the frequency // of A[j+1] as it can be // a valid A[k] if(map.containsKey(A[j + 1])) map.put(A[j + 1], map.get(A[j + 1]) + 1); else map.put(A[j + 1], 1); for(int i = 0; i < j; i++) { int target = A[i] * A[j]; // If target exists in the map if (map.containsKey(target)) ans += map.get(target); } } // Return the final count return ans;} // Driver Codepublic static void main(String[] args){ int N = 5; int A[] = { 2, 3, 4, 6, 12 }; System.out.print(countTriplets(A, N));}} // This code is contributed by sapnasingh4991",
"e": 30148,
"s": 28998,
"text": null
},
{
"code": "# Python3 program for the above approachfrom collections import defaultdict # Returns total number of# valid triplets possibledef countTriplets(A, N): # Stores the count ans = 0 # Map to store frequency # of array elements map = defaultdict(lambda: 0) for j in range(N - 2, 0, -1): # Increment the frequency # of A[j+1] as it can be # a valid A[k] map[A[j + 1]] += 1 for i in range(j): target = A[i] * A[j] # If target exists in the map if(target in map.keys()): ans += map[target] # Return the final count return ans # Driver codeif __name__ == '__main__': N = 5 A = [ 2, 3, 4, 6, 12 ] print(countTriplets(A, N)) # This code is contributed by Shivam Singh",
"e": 30930,
"s": 30148,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Returns total number of// valid triplets possiblestatic int countTriplets(int []A, int N){ // Stores the count int ans = 0; // Map to store frequency // of array elements Dictionary<int, int> map = new Dictionary<int, int>(); for(int j = N - 2; j >= 1; j--) { // Increment the frequency // of A[j+1] as it can be // a valid A[k] if(map.ContainsKey(A[j + 1])) map[A[j + 1]] = map[A[j + 1]] + 1; else map.Add(A[j + 1], 1); for(int i = 0; i < j; i++) { int target = A[i] * A[j]; // If target exists in the map if (map.ContainsKey(target)) ans += map[target]; } } // Return the readonly count return ans;} // Driver Codepublic static void Main(String[] args){ int N = 5; int []A = { 2, 3, 4, 6, 12 }; Console.Write(countTriplets(A, N));}} // This code is contributed by sapnasingh4991",
"e": 32088,
"s": 30930,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Returns total number of// valid triplets possiblefunction countTriplets(A, N){ // Stores the count let ans = 0; // Map to store frequency // of array elements let map = new Map(); for(let j = N - 2; j >= 1; j--) { // Increment the frequency // of A[j+1] as it can be // a valid A[k] if(map.has(A[j + 1])) map.set(A[j + 1], map.get(A[j + 1]) + 1); else map.set(A[j + 1], 1); for(let i = 0; i < j; i++) { let target = A[i] * A[j]; // If target exists in the map if (map.has(target)) ans += map.get(target); } } // Return the final count return ans;} // Driver code let N = 5; let A = [ 2, 3, 4, 6, 12 ]; document.write(countTriplets(A, N)); // This code is contributed by souravghosh0416.</script>",
"e": 33078,
"s": 32088,
"text": null
},
{
"code": null,
"e": 33080,
"s": 33078,
"text": "3"
},
{
"code": null,
"e": 33126,
"s": 33080,
"text": "Time Complexity: O(N2) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 33140,
"s": 33126,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 33155,
"s": 33140,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 33171,
"s": 33155,
"text": "souravghosh0416"
},
{
"code": null,
"e": 33179,
"s": 33171,
"text": "cpp-map"
},
{
"code": null,
"e": 33198,
"s": 33179,
"text": "frequency-counting"
},
{
"code": null,
"e": 33220,
"s": 33198,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 33227,
"s": 33220,
"text": "Arrays"
},
{
"code": null,
"e": 33232,
"s": 33227,
"text": "Hash"
},
{
"code": null,
"e": 33245,
"s": 33232,
"text": "Mathematical"
},
{
"code": null,
"e": 33255,
"s": 33245,
"text": "Searching"
},
{
"code": null,
"e": 33277,
"s": 33255,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 33284,
"s": 33277,
"text": "Arrays"
},
{
"code": null,
"e": 33294,
"s": 33284,
"text": "Searching"
},
{
"code": null,
"e": 33299,
"s": 33294,
"text": "Hash"
},
{
"code": null,
"e": 33312,
"s": 33299,
"text": "Mathematical"
},
{
"code": null,
"e": 33410,
"s": 33312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33478,
"s": 33410,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 33522,
"s": 33478,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 33570,
"s": 33522,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33593,
"s": 33570,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 33625,
"s": 33593,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33661,
"s": 33625,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 33692,
"s": 33661,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 33726,
"s": 33692,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 33762,
"s": 33726,
"text": "Hashing | Set 2 (Separate Chaining)"
}
] |
numpy.ptp() in Python - GeeksforGeeks
|
23 Nov, 2021
numpy.ptp()function plays an important role in statistics by finding out Range of given numbers. Range = max value – min value.
Syntax : ndarray.ptp(arr, axis=None, out=None) Parameters : arr :input array. axis :axis along which we want the range value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row. out : [ndarray, optional]Different array in which we want to place the result. The array must have same dimensions as expected output. Return : Range of the array (a scalar value if axis is none) or array with range of values along specified axis.
Code #1: Working
Python
# Python Program illustrating# numpy.ptp() method import numpy as np # 1D arrayarr = [1, 2, 7, 20, np.nan]print("arr : ", arr)print("Range of arr : ", np.ptp(arr)) # 1D arrayarr = [1, 2, 7, 10, 16]print("arr : ", arr)print("Range of arr : ", np.ptp(arr))
Output :
arr : [1, 2, 7, 20, nan]
Range of arr : nan
arr : [1, 2, 7, 10, 16]
Range of arr : 15
Code #2 :
Python
# Python Program illustrating# numpy.ptp() method import numpy as np # 3D arrayarr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]]print("\narr : \n", arr) # Range of the flattened arrayprint("\nRange of arr, axis = None : ", np.ptp(arr)) # Range along the first axis# axis 0 means verticalprint("Range of arr, axis = 0 : ", np.ptp(arr, axis = 0)) # Range along the second axis# axis 1 means horizontalprint("Min of arr, axis = 1 : ", np.ptp(arr, axis = 1))
Output :
arr :
[[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4]]
Range of arr, axis = None : 53
Range of arr, axis = 0 : [ 9 15 42 32 40]
Min of arr, axis = 1 : [32 21 53]
Code #3 :
Python
# Python Program illustrating# numpy.ptp() method import numpy as np arr1 = np.arange(5)print("\nInitial arr1 : ", arr1) # using out parameternp.ptp(arr, axis = 0, out = arr1) print("Changed arr1(having results) : ", arr1)
Output :
Initial arr1 : [0 1 2 3 4]
Changed arr1(having results) : [ 9 15 42 32 40]
cedricaganzebahirwe
Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 26055,
"s": 26027,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 26185,
"s": 26055,
"text": "numpy.ptp()function plays an important role in statistics by finding out Range of given numbers. Range = max value – min value. "
},
{
"code": null,
"e": 26707,
"s": 26185,
"text": "Syntax : ndarray.ptp(arr, axis=None, out=None) Parameters : arr :input array. axis :axis along which we want the range value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row. out : [ndarray, optional]Different array in which we want to place the result. The array must have same dimensions as expected output. Return : Range of the array (a scalar value if axis is none) or array with range of values along specified axis. "
},
{
"code": null,
"e": 26725,
"s": 26707,
"text": "Code #1: Working "
},
{
"code": null,
"e": 26732,
"s": 26725,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.ptp() method import numpy as np # 1D arrayarr = [1, 2, 7, 20, np.nan]print(\"arr : \", arr)print(\"Range of arr : \", np.ptp(arr)) # 1D arrayarr = [1, 2, 7, 10, 16]print(\"arr : \", arr)print(\"Range of arr : \", np.ptp(arr))",
"e": 26991,
"s": 26732,
"text": null
},
{
"code": null,
"e": 27001,
"s": 26991,
"text": "Output : "
},
{
"code": null,
"e": 27091,
"s": 27001,
"text": "arr : [1, 2, 7, 20, nan]\nRange of arr : nan\narr : [1, 2, 7, 10, 16]\nRange of arr : 15"
},
{
"code": null,
"e": 27103,
"s": 27091,
"text": " Code #2 : "
},
{
"code": null,
"e": 27110,
"s": 27103,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.ptp() method import numpy as np # 3D arrayarr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]]print(\"\\narr : \\n\", arr) # Range of the flattened arrayprint(\"\\nRange of arr, axis = None : \", np.ptp(arr)) # Range along the first axis# axis 0 means verticalprint(\"Range of arr, axis = 0 : \", np.ptp(arr, axis = 0)) # Range along the second axis# axis 1 means horizontalprint(\"Min of arr, axis = 1 : \", np.ptp(arr, axis = 1)) ",
"e": 27607,
"s": 27110,
"text": null
},
{
"code": null,
"e": 27617,
"s": 27607,
"text": "Output : "
},
{
"code": null,
"e": 27798,
"s": 27617,
"text": "arr : \n [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4]]\n\nRange of arr, axis = None : 53\nRange of arr, axis = 0 : [ 9 15 42 32 40]\nMin of arr, axis = 1 : [32 21 53]"
},
{
"code": null,
"e": 27810,
"s": 27798,
"text": " Code #3 : "
},
{
"code": null,
"e": 27817,
"s": 27810,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.ptp() method import numpy as np arr1 = np.arange(5)print(\"\\nInitial arr1 : \", arr1) # using out parameternp.ptp(arr, axis = 0, out = arr1) print(\"Changed arr1(having results) : \", arr1)",
"e": 28042,
"s": 27817,
"text": null
},
{
"code": null,
"e": 28053,
"s": 28042,
"text": "Output : "
},
{
"code": null,
"e": 28130,
"s": 28053,
"text": "Initial arr1 : [0 1 2 3 4]\nChanged arr1(having results) : [ 9 15 42 32 40]"
},
{
"code": null,
"e": 28150,
"s": 28130,
"text": "cedricaganzebahirwe"
},
{
"code": null,
"e": 28184,
"s": 28150,
"text": "Python numpy-Statistics Functions"
},
{
"code": null,
"e": 28197,
"s": 28184,
"text": "Python-numpy"
},
{
"code": null,
"e": 28204,
"s": 28197,
"text": "Python"
},
{
"code": null,
"e": 28302,
"s": 28204,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28320,
"s": 28302,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28352,
"s": 28320,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28374,
"s": 28352,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28416,
"s": 28374,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28446,
"s": 28416,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28475,
"s": 28446,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28519,
"s": 28475,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28556,
"s": 28519,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28592,
"s": 28556,
"text": "Convert integer to string in Python"
}
] |
The Complete Guide to Proxies For Web Scraping - GeeksforGeeks
|
13 Jul, 2021
In computer networking, a proxy server is a server application or appliance that acts as an intermediary for requests from clients seeking resources from servers that provide those resources.
Since web scraping requires a lot of requests made to a server from an IP address, the server may detect too many requests and may block the IP address to stop further scraping. To avoid blocking, proxies are used and scraping will continue working as the IP address is changed and won’t cause any issues. It also helps in hiding the machine’s IP address as it creates anonymity.
There are three types of proxies.
Data Center Proxy: These proxies are from cloud service providers and are sometimes flagged as many people use them, but since they are cheaper, a pool of proxies can be brought for web scraping activities.
Residential IP Proxy: These proxies contain IP addresses from local ISP, so the webmaster cannot detect if it is a scraper or a real person browsing the website. They are very expensive compared to Data Center Proxies and may cause legal consents as the owner isn’t fully aware if you are using their IP for web scraping purposes.
Mobile IP Proxy: These proxies are IPs of private mobile devices and work similarly to Residential IP Proxies. They are very expensive and may cause legal consents as the device owner isn’t fully aware if you are using their GSM network for web scraping since they are provided by mobile network operators.
Identify Bans – The proxy should be able to detect various types of blocking methods and fix the underlying problems – i.e. captchas, redirects, blocks, ghosting, etc.
Retry Errors – Retry the request using a different proxy server if there are any connection problems, blocks, captchas, etc with the current proxy.
Control Proxies – Few websites with authentication require to keep the session with the same IP or else authentication might be required again if there is any change in proxy server.
Adding Delays – Randomize delays and apply good throttling so the website cannot detect that you are scraping.
Geographical Location – Few websites may require IP’s from specific countries, so the proxy pool should contain the set of proxies from the given geolocation.
Public Proxies are not recommended as they are of low quality and are also considered dangerous as they can infect the machine and even make the web scraping activity public if the SSL certificates are not configured properly.
Shared proxies are generally used if the budget is low and a shared pool of IP’s is required. If the budget is higher and performance is top priority then dedicated pool of proxies is the way to go.
Sending too many requests from a single IP address is a clear indication that you are automating HTTP/HTTPS requests and the webmaster will surely block your IP address to stop further scraping. The best alternative is to create a proxy pool and iterate/rotate them after a certain amount of requests from a single proxy server.
This reduces the chances of IP blocking and the scraper remains unaffected.
proxies = {‘http://78.47.16.54:80’, ‘http://203.75.190.21:80’, ‘http://77.72.3.163:80’}
Import the requests module.
Create a pool of proxies and then rotate/iterate them.
Send a GET request using requests.get() by passing the proxy as a parameter to the URL.
Returns the proxy server address of the current session if there is no connection error.
Program:
Python3
import requests # Initialise proxy and url.proxy = 'http://114.121.248.251:8080'url = 'https://ipecho.net/plain' # Send a GET request to the url and# pass the proxy as parameter.page = requests.get(url, proxies={"http": proxy, "https": proxy}) # Prints the content of the requested url.print(page.text)
Output:
114.121.248.251
The same can be applied to multiple proxies, given below is the implementation for the same.
Program:
Python3
# Import the required Modulesimport requests # Create a pool of proxiesproxies = { 'http://114.121.248.251:8080', 'http://222.85.190.32:8090', 'http://47.107.128.69:888', 'http://41.65.146.38:8080', 'http://190.63.184.11:8080', 'http://45.7.135.34:999', 'http://141.94.104.25:8080', 'http://222.74.202.229:8080', 'http://141.94.106.43:8080', 'http://191.101.39.96:80'} url = 'https://ipecho.net/plain' # Iterate the proxies and check if it is working.for proxy in proxies: try: # https://ipecho.net/plain returns the ip address # of the current session if a GET request is sent. page = requests.get( url, proxies={"http": proxy, "https": proxy}) # Prints Proxy server IP address if proxy is alive. print("Status OK, Output:", page.text) except OSError as e: # Proxy returns Connection error print(e)
Output:
proxy in request module
Picked
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Python math function | sqrt()
Python | Output Formatting
Python - Pandas dataframe.append()
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 25730,
"s": 25537,
"text": "In computer networking, a proxy server is a server application or appliance that acts as an intermediary for requests from clients seeking resources from servers that provide those resources. "
},
{
"code": null,
"e": 26110,
"s": 25730,
"text": "Since web scraping requires a lot of requests made to a server from an IP address, the server may detect too many requests and may block the IP address to stop further scraping. To avoid blocking, proxies are used and scraping will continue working as the IP address is changed and won’t cause any issues. It also helps in hiding the machine’s IP address as it creates anonymity."
},
{
"code": null,
"e": 26144,
"s": 26110,
"text": "There are three types of proxies."
},
{
"code": null,
"e": 26351,
"s": 26144,
"text": "Data Center Proxy: These proxies are from cloud service providers and are sometimes flagged as many people use them, but since they are cheaper, a pool of proxies can be brought for web scraping activities."
},
{
"code": null,
"e": 26682,
"s": 26351,
"text": "Residential IP Proxy: These proxies contain IP addresses from local ISP, so the webmaster cannot detect if it is a scraper or a real person browsing the website. They are very expensive compared to Data Center Proxies and may cause legal consents as the owner isn’t fully aware if you are using their IP for web scraping purposes."
},
{
"code": null,
"e": 26989,
"s": 26682,
"text": "Mobile IP Proxy: These proxies are IPs of private mobile devices and work similarly to Residential IP Proxies. They are very expensive and may cause legal consents as the device owner isn’t fully aware if you are using their GSM network for web scraping since they are provided by mobile network operators."
},
{
"code": null,
"e": 27157,
"s": 26989,
"text": "Identify Bans – The proxy should be able to detect various types of blocking methods and fix the underlying problems – i.e. captchas, redirects, blocks, ghosting, etc."
},
{
"code": null,
"e": 27305,
"s": 27157,
"text": "Retry Errors – Retry the request using a different proxy server if there are any connection problems, blocks, captchas, etc with the current proxy."
},
{
"code": null,
"e": 27488,
"s": 27305,
"text": "Control Proxies – Few websites with authentication require to keep the session with the same IP or else authentication might be required again if there is any change in proxy server."
},
{
"code": null,
"e": 27599,
"s": 27488,
"text": "Adding Delays – Randomize delays and apply good throttling so the website cannot detect that you are scraping."
},
{
"code": null,
"e": 27758,
"s": 27599,
"text": "Geographical Location – Few websites may require IP’s from specific countries, so the proxy pool should contain the set of proxies from the given geolocation."
},
{
"code": null,
"e": 27985,
"s": 27758,
"text": "Public Proxies are not recommended as they are of low quality and are also considered dangerous as they can infect the machine and even make the web scraping activity public if the SSL certificates are not configured properly."
},
{
"code": null,
"e": 28184,
"s": 27985,
"text": "Shared proxies are generally used if the budget is low and a shared pool of IP’s is required. If the budget is higher and performance is top priority then dedicated pool of proxies is the way to go."
},
{
"code": null,
"e": 28513,
"s": 28184,
"text": "Sending too many requests from a single IP address is a clear indication that you are automating HTTP/HTTPS requests and the webmaster will surely block your IP address to stop further scraping. The best alternative is to create a proxy pool and iterate/rotate them after a certain amount of requests from a single proxy server."
},
{
"code": null,
"e": 28589,
"s": 28513,
"text": "This reduces the chances of IP blocking and the scraper remains unaffected."
},
{
"code": null,
"e": 28678,
"s": 28589,
"text": "proxies = {‘http://78.47.16.54:80’, ‘http://203.75.190.21:80’, ‘http://77.72.3.163:80’}"
},
{
"code": null,
"e": 28706,
"s": 28678,
"text": "Import the requests module."
},
{
"code": null,
"e": 28761,
"s": 28706,
"text": "Create a pool of proxies and then rotate/iterate them."
},
{
"code": null,
"e": 28849,
"s": 28761,
"text": "Send a GET request using requests.get() by passing the proxy as a parameter to the URL."
},
{
"code": null,
"e": 28938,
"s": 28849,
"text": "Returns the proxy server address of the current session if there is no connection error."
},
{
"code": null,
"e": 28947,
"s": 28938,
"text": "Program:"
},
{
"code": null,
"e": 28955,
"s": 28947,
"text": "Python3"
},
{
"code": "import requests # Initialise proxy and url.proxy = 'http://114.121.248.251:8080'url = 'https://ipecho.net/plain' # Send a GET request to the url and# pass the proxy as parameter.page = requests.get(url, proxies={\"http\": proxy, \"https\": proxy}) # Prints the content of the requested url.print(page.text)",
"e": 29280,
"s": 28955,
"text": null
},
{
"code": null,
"e": 29288,
"s": 29280,
"text": "Output:"
},
{
"code": null,
"e": 29304,
"s": 29288,
"text": "114.121.248.251"
},
{
"code": null,
"e": 29397,
"s": 29304,
"text": "The same can be applied to multiple proxies, given below is the implementation for the same."
},
{
"code": null,
"e": 29406,
"s": 29397,
"text": "Program:"
},
{
"code": null,
"e": 29414,
"s": 29406,
"text": "Python3"
},
{
"code": "# Import the required Modulesimport requests # Create a pool of proxiesproxies = { 'http://114.121.248.251:8080', 'http://222.85.190.32:8090', 'http://47.107.128.69:888', 'http://41.65.146.38:8080', 'http://190.63.184.11:8080', 'http://45.7.135.34:999', 'http://141.94.104.25:8080', 'http://222.74.202.229:8080', 'http://141.94.106.43:8080', 'http://191.101.39.96:80'} url = 'https://ipecho.net/plain' # Iterate the proxies and check if it is working.for proxy in proxies: try: # https://ipecho.net/plain returns the ip address # of the current session if a GET request is sent. page = requests.get( url, proxies={\"http\": proxy, \"https\": proxy}) # Prints Proxy server IP address if proxy is alive. print(\"Status OK, Output:\", page.text) except OSError as e: # Proxy returns Connection error print(e)",
"e": 30319,
"s": 29414,
"text": null
},
{
"code": null,
"e": 30327,
"s": 30319,
"text": "Output:"
},
{
"code": null,
"e": 30351,
"s": 30327,
"text": "proxy in request module"
},
{
"code": null,
"e": 30358,
"s": 30351,
"text": "Picked"
},
{
"code": null,
"e": 30374,
"s": 30358,
"text": "Python-requests"
},
{
"code": null,
"e": 30381,
"s": 30374,
"text": "Python"
},
{
"code": null,
"e": 30479,
"s": 30381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30501,
"s": 30479,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30533,
"s": 30501,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30549,
"s": 30533,
"text": "Deque in Python"
},
{
"code": null,
"e": 30572,
"s": 30549,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 30614,
"s": 30572,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30644,
"s": 30614,
"text": "Python math function | sqrt()"
},
{
"code": null,
"e": 30671,
"s": 30644,
"text": "Python | Output Formatting"
},
{
"code": null,
"e": 30706,
"s": 30671,
"text": "Python - Pandas dataframe.append()"
},
{
"code": null,
"e": 30762,
"s": 30706,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Sort an array according to the other | Practice | GeeksforGeeks
|
Given two integer arrays A1[ ] and A2[ ] of size N and M respectively. Sort the first array A1[ ] such that all the relative positions of the elements in the first array are the same as the elements in the second array A2[ ].
See example for better understanding.
Note: If elements are repeated in the second array, consider their first occurance only.
Example 1:
Input:
N = 11
M = 4
A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
A2[] = {2, 1, 8, 3}
Output:
2 2 1 1 8 8 3 5 6 7 9
Explanation: Array elements of A1[] are
sorted according to A2[]. So 2 comes first
then 1 comes, then comes 8, then finally 3
comes, now we append remaining elements in
sorted order.
Example 2:
Input:
N = 11
M = 4
A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
A2[] = {99, 22, 444, 56}
Output:
1 1 2 2 3 5 6 7 8 8 9
Explanation: No A1[] elements are in A2[]
so we cannot sort A1[] according to A2[].
Hence we sort the elements in non-decreasing
order.
Your Task:
You don't need to read input or print anything. Your task is to complete the function sortA1ByA2() which takes the array A1[ ], array A2[ ] and their respective size N and M as input parameters and returns the sorted array A1[ ] such that the relative positions of the elements in A1[ ] are same as the elements in A2[ ]. For the elements not present in A2[ ] but in A1[ ], it appends them at the last in increasing order.
Expected Time Complexity: O(N * Log(N)).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ N, M ≤ 106
1 ≤ A1[i], A2[i] ≤ 106
0
pratikbhankhodiya1 day ago
vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M)
{
map<int,int> mp;
int i=0;
for(auto it:A1) mp[it]++;
for(auto it:A2){
while(mp[it]-->0) A1[i++]=it;
}
for(auto &pair:mp){
auto it=pair.first;
auto freq=pair.second;
while(freq-->0) A1[i++]=it;
}
return A1;
}
0
aakarshgoel102 days ago
public static int[] sortA1ByA2(int A1[], int N, int A2[], int M) { ArrayList<Integer> result = new ArrayList<>(); HashMap<Integer, Integer> hashmap = new HashMap<>(); for (int ip = 0; ip < N; ip++) { if (hashmap.containsKey(A1[ip])) { hashmap.put(A1[ip], hashmap.get(A1[ip]) + 1); } else { hashmap.put(A1[ip], 1); }
}
for (int i = 0; i < M; i++) { if (hashmap.containsKey(A2[i])) { for (int j = 0; j < hashmap.get(A2[i]); j++) { result.add(A2[i]); } hashmap.remove(A2[i]); } } ArrayList<Integer> remainingArray = new ArrayList<>(); int k = 0; for (Map.Entry<Integer, Integer> map : hashmap.entrySet()) { for (int j = 0; j < map.getValue(); j++) { remainingArray.add(map.getKey()); } } Collections.sort(remainingArray); for (int elem : remainingArray) { result.add(elem); } int finalArray[] = new int[result.size()]; for (int i = 0; i < finalArray.length; i++) { finalArray[i] = result.get(i); }
return finalArray;
}
}
// { Driver Code Starts.class Main {public static void main (String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); int a1[]=new int[n]; int a2[]=new int[m]; for(int i=0;i<n;i++) a1[i]=sc.nextInt(); for(int i=0;i<m;i++) a2[i]=sc.nextInt(); Solution ob=new Solution(); a1 = ob.sortA1ByA2(a1,n,a2,m); for(int x:a1) System.out.print(x+" "); System.out.println(); }}
}
// } Driver Code Ends
0
gulrezalam1 week ago
what is meaning of
Collections.sort(a,(n1,n2)->{ return n1-n2; });
where a is an array
0
akshayjadhav32 weeks ago
vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M) { multiset<int>s{A1.begin(),A1.begin()+N}; vector<int>v; int i=0; while(i<M) { while(s.find(A2[i])!=s.end()) { auto it=s.find(A2[i]); v.push_back(*it); s.erase(it); } i++; } auto it1=s.begin(); while(it1!=s.end()) { v.push_back(*it1); it1++; } return v; }
0
arya049442 weeks ago
vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M)
{
//Your code here
map<int,int> mp;
for(auto a:A1){
mp[a]++;
}
int i=0;
for(auto a:A2){
int k=mp[a];
mp[a]=0;
while(k--){
A1[i++]=a;
}
}
for(auto m:mp){
int k=m.second;
m.second=0;
while(k--){
A1[i++]=m.first;
}
}
return A1;
}
+1
sriniprasanna773 weeks ago
This can be done using hashmap by keeping track of any elements and their occurrences in a1[].
Sort a1[] and (a) clone into temp[]; (b) create an HashMap with key = a[i], value = occurenceCountloop through a2[] and find value from HashMap for a2[i]if mapvalue > 0, then a2[] has element that occurs in a1[]start assiging a[i] with the element for mapvalue number of times (occurences)Most important step : set -1 as value for all matching elements in hashmapFinally, copy the remainder elements from temp over to a1[] continuing the index
Sort a1[] and (a) clone into temp[]; (b) create an HashMap with key = a[i], value = occurenceCount
loop through a2[] and find value from HashMap for a2[i]
if mapvalue > 0, then a2[] has element that occurs in a1[]
start assiging a[i] with the element for mapvalue number of times (occurences)
Most important step : set -1 as value for all matching elements in hashmap
Finally, copy the remainder elements from temp over to a1[] continuing the index
public static int[] sortA1ByA2(int a1[], int N, int a2[], int M) { //Your code here int[] temp = new int[a1.length]; HashMap<Integer,Integer> a1Map = new HashMap<>(); Arrays.sort(a1); for(int i = 0; i < N; i++) { a1Map.put(a1[i],a1Map.getOrDefault(a1[i], 0) != 0?a1Map.get(a1[i])+1:1); temp[i] = a1[i]; } int idx = 0; for (int n: a2) { int mapVal = a1Map.getOrDefault(n,0); if (mapVal > 0) { for(int i=0; i<mapVal; i++) { a1[idx] = n; idx++; } a1Map.put(n,-1); //important line } } for (int n: temp) { int mapVal = a1Map.get(n); if (mapVal > 0) { a1[idx] = n; idx++; } } return a1; }
0
harshilgupta00993 weeks ago
vector<int> sortA1ByA2(vector<int> arr1, int n, vector<int> arr2, int m)
{
//Your code here
vector<int> ans;
unordered_map<int,int> umap;
for(int i=0;i<n;i++){
umap[arr1[i]]++;
}
for(int i=0;i<m;i++){
while(umap[arr2[i]]!=0){
ans.push_back(arr2[i]);
umap[arr2[i]]--;
}
if(umap[arr2[i]]==0)
umap.erase(arr2[i]);
}
vector<int> v;
for(auto x:umap){
while(x.second!=0){
v.push_back(x.first);
x.second--;
}
}
sort(v.begin(),v.end());
for(int x:v)
ans.push_back(x);
return ans;
}
0
shubham211019973 weeks ago
public static int[] sortA1ByA2(int arr1[], int n, int arr2[], int m)
{
/* Naive Solution
ArrayList<Integer>a=new ArrayList<Integer>();
for(int i=0;i<n;i++)
a.add(arr1[i]);
ArrayList<Integer>b=new ArrayList<Integer>();
for(int i=0;i<m;i++) {
b.add(arr2[i]);
}
int arr[]=new int[n];
int k=0;
for(int i=0;i<m;i++) {
while(a.contains(b.get(i))) {
arr[k++]=b.get(i);
a.remove(b.get(i));
}
}
Collections.sort(a,(n1,n2)->{
return n1-n2;
});
for(int i=0;i<a.size();i++) {
arr[k++]=a.get(i);
}
return arr;*/
int arr[]=new int[n];
int k=0;
TreeMap<Integer,Integer> h=new TreeMap<>();
for(int i:arr1){
h.put(i,h.getOrDefault(i,0)+1);
}
for(int i:arr2){
if(h.containsKey(i)==true){
while(h.get(i)!=0){
arr[k++]=i;
h.put(i,h.get(i)-1);
}
h.remove(i);
}
}
// Collections.sort(h,(a,b)->{
// return a-b;
// });
for(Entry<Integer,Integer> e : h.entrySet()){
for(int p=0;p<e.getValue();p++)
arr[k++]=e.getKey();
}
return arr;
}
0
shubham211019973 weeks ago
public static int[] sortA1ByA2(int arr1[], int n, int arr2[], int m)
{
ArrayList<Integer>a=new ArrayList<Integer>();
for(int i=0;i<n;i++)
a.add(arr1[i]);
ArrayList<Integer>b=new ArrayList<Integer>();
for(int i=0;i<m;i++) {
b.add(arr2[i]);
}
int arr[]=new int[n];
int k=0;
for(int i=0;i<m;i++) {
while(a.contains(b.get(i))) {
arr[k++]=b.get(i);
a.remove(b.get(i));
}
}
Collections.sort(a,(n1,n2)->{
return n1-n2;
});
for(int i=0;i<a.size();i++) {
arr[k++]=a.get(i);
}
return arr;
}
0
ravinuthalavamsikrishna3 weeks ago
def relativeSort (self,A1, N, A2, M): # Your Code Here d={} for i in A1: d[i]=d.get(i,0)+1 l=[] l2=[] for i in A2: if i in d.keys(): l+=[i]*(d[i]) del d[i] l2=[] for i,j in d.items(): l2+=[i]*j l2.sort() l+=l2 return l
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": 591,
"s": 238,
"text": "Given two integer arrays A1[ ] and A2[ ] of size N and M respectively. Sort the first array A1[ ] such that all the relative positions of the elements in the first array are the same as the elements in the second array A2[ ].\nSee example for better understanding.\nNote: If elements are repeated in the second array, consider their first occurance only."
},
{
"code": null,
"e": 602,
"s": 591,
"text": "Example 1:"
},
{
"code": null,
"e": 899,
"s": 602,
"text": "Input:\nN = 11 \nM = 4\nA1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}\nA2[] = {2, 1, 8, 3}\nOutput: \n2 2 1 1 8 8 3 5 6 7 9\nExplanation: Array elements of A1[] are\nsorted according to A2[]. So 2 comes first\nthen 1 comes, then comes 8, then finally 3\ncomes, now we append remaining elements in\nsorted order.\n"
},
{
"code": null,
"e": 910,
"s": 899,
"text": "Example 2:"
},
{
"code": null,
"e": 1165,
"s": 910,
"text": "Input:\nN = 11 \nM = 4\nA1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}\nA2[] = {99, 22, 444, 56}\nOutput: \n1 1 2 2 3 5 6 7 8 8 9\nExplanation: No A1[] elements are in A2[]\nso we cannot sort A1[] according to A2[].\nHence we sort the elements in non-decreasing \norder."
},
{
"code": null,
"e": 1600,
"s": 1165,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function sortA1ByA2() which takes the array A1[ ], array A2[ ] and their respective size N and M as input parameters and returns the sorted array A1[ ] such that the relative positions of the elements in A1[ ] are same as the elements in A2[ ]. For the elements not present in A2[ ] but in A1[ ], it appends them at the last in increasing order. "
},
{
"code": null,
"e": 1673,
"s": 1600,
"text": "Expected Time Complexity: O(N * Log(N)).\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 1725,
"s": 1673,
"text": "Constraints:\n1 ≤ N, M ≤ 106\n1 ≤ A1[i], A2[i] ≤ 106 "
},
{
"code": null,
"e": 1727,
"s": 1725,
"text": "0"
},
{
"code": null,
"e": 1754,
"s": 1727,
"text": "pratikbhankhodiya1 day ago"
},
{
"code": null,
"e": 2154,
"s": 1754,
"text": "vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M) \n {\n map<int,int> mp;\n int i=0;\n for(auto it:A1) mp[it]++;\n for(auto it:A2){\n while(mp[it]-->0) A1[i++]=it;\n }\n for(auto &pair:mp){\n auto it=pair.first;\n auto freq=pair.second;\n while(freq-->0) A1[i++]=it;\n }\n return A1;\n } "
},
{
"code": null,
"e": 2156,
"s": 2154,
"text": "0"
},
{
"code": null,
"e": 2180,
"s": 2156,
"text": "aakarshgoel102 days ago"
},
{
"code": null,
"e": 2581,
"s": 2182,
"text": " public static int[] sortA1ByA2(int A1[], int N, int A2[], int M) { ArrayList<Integer> result = new ArrayList<>(); HashMap<Integer, Integer> hashmap = new HashMap<>(); for (int ip = 0; ip < N; ip++) { if (hashmap.containsKey(A1[ip])) { hashmap.put(A1[ip], hashmap.get(A1[ip]) + 1); } else { hashmap.put(A1[ip], 1); }"
},
{
"code": null,
"e": 2590,
"s": 2581,
"text": " }"
},
{
"code": null,
"e": 3374,
"s": 2590,
"text": " for (int i = 0; i < M; i++) { if (hashmap.containsKey(A2[i])) { for (int j = 0; j < hashmap.get(A2[i]); j++) { result.add(A2[i]); } hashmap.remove(A2[i]); } } ArrayList<Integer> remainingArray = new ArrayList<>(); int k = 0; for (Map.Entry<Integer, Integer> map : hashmap.entrySet()) { for (int j = 0; j < map.getValue(); j++) { remainingArray.add(map.getKey()); } } Collections.sort(remainingArray); for (int elem : remainingArray) { result.add(elem); } int finalArray[] = new int[result.size()]; for (int i = 0; i < finalArray.length; i++) { finalArray[i] = result.get(i); }"
},
{
"code": null,
"e": 3400,
"s": 3374,
"text": " return finalArray;"
},
{
"code": null,
"e": 3405,
"s": 3400,
"text": " }"
},
{
"code": null,
"e": 3407,
"s": 3405,
"text": "}"
},
{
"code": null,
"e": 3914,
"s": 3409,
"text": "// { Driver Code Starts.class Main {public static void main (String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int m=sc.nextInt(); int a1[]=new int[n]; int a2[]=new int[m]; for(int i=0;i<n;i++) a1[i]=sc.nextInt(); for(int i=0;i<m;i++) a2[i]=sc.nextInt(); Solution ob=new Solution(); a1 = ob.sortA1ByA2(a1,n,a2,m); for(int x:a1) System.out.print(x+\" \"); System.out.println(); }} "
},
{
"code": null,
"e": 3916,
"s": 3914,
"text": "}"
},
{
"code": null,
"e": 3939,
"s": 3916,
"text": " // } Driver Code Ends"
},
{
"code": null,
"e": 3941,
"s": 3939,
"text": "0"
},
{
"code": null,
"e": 3962,
"s": 3941,
"text": "gulrezalam1 week ago"
},
{
"code": null,
"e": 3989,
"s": 3962,
"text": "what is meaning of "
},
{
"code": null,
"e": 4051,
"s": 3991,
"text": " Collections.sort(a,(n1,n2)->{ return n1-n2; });"
},
{
"code": null,
"e": 4077,
"s": 4057,
"text": "where a is an array"
},
{
"code": null,
"e": 4079,
"s": 4077,
"text": "0"
},
{
"code": null,
"e": 4104,
"s": 4079,
"text": "akshayjadhav32 weeks ago"
},
{
"code": null,
"e": 4803,
"s": 4104,
"text": "vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M) { multiset<int>s{A1.begin(),A1.begin()+N}; vector<int>v; int i=0; while(i<M) { while(s.find(A2[i])!=s.end()) { auto it=s.find(A2[i]); v.push_back(*it); s.erase(it); } i++; } auto it1=s.begin(); while(it1!=s.end()) { v.push_back(*it1); it1++; } return v; }"
},
{
"code": null,
"e": 4805,
"s": 4803,
"text": "0"
},
{
"code": null,
"e": 4826,
"s": 4805,
"text": "arya049442 weeks ago"
},
{
"code": null,
"e": 5384,
"s": 4826,
"text": " vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M) \n {\n //Your code here\n map<int,int> mp;\n for(auto a:A1){\n mp[a]++;\n }\n int i=0;\n for(auto a:A2){\n int k=mp[a];\n mp[a]=0;\n while(k--){\n A1[i++]=a;\n }\n \n }\n \n for(auto m:mp){\n int k=m.second;\n m.second=0;\n while(k--){\n A1[i++]=m.first;\n }\n }\n \n return A1;\n } "
},
{
"code": null,
"e": 5387,
"s": 5384,
"text": "+1"
},
{
"code": null,
"e": 5414,
"s": 5387,
"text": "sriniprasanna773 weeks ago"
},
{
"code": null,
"e": 5509,
"s": 5414,
"text": "This can be done using hashmap by keeping track of any elements and their occurrences in a1[]."
},
{
"code": null,
"e": 5953,
"s": 5509,
"text": "Sort a1[] and (a) clone into temp[]; (b) create an HashMap with key = a[i], value = occurenceCountloop through a2[] and find value from HashMap for a2[i]if mapvalue > 0, then a2[] has element that occurs in a1[]start assiging a[i] with the element for mapvalue number of times (occurences)Most important step : set -1 as value for all matching elements in hashmapFinally, copy the remainder elements from temp over to a1[] continuing the index"
},
{
"code": null,
"e": 6052,
"s": 5953,
"text": "Sort a1[] and (a) clone into temp[]; (b) create an HashMap with key = a[i], value = occurenceCount"
},
{
"code": null,
"e": 6108,
"s": 6052,
"text": "loop through a2[] and find value from HashMap for a2[i]"
},
{
"code": null,
"e": 6167,
"s": 6108,
"text": "if mapvalue > 0, then a2[] has element that occurs in a1[]"
},
{
"code": null,
"e": 6246,
"s": 6167,
"text": "start assiging a[i] with the element for mapvalue number of times (occurences)"
},
{
"code": null,
"e": 6321,
"s": 6246,
"text": "Most important step : set -1 as value for all matching elements in hashmap"
},
{
"code": null,
"e": 6402,
"s": 6321,
"text": "Finally, copy the remainder elements from temp over to a1[] continuing the index"
},
{
"code": null,
"e": 7034,
"s": 6402,
"text": "public static int[] sortA1ByA2(int a1[], int N, int a2[], int M) { //Your code here int[] temp = new int[a1.length]; HashMap<Integer,Integer> a1Map = new HashMap<>(); Arrays.sort(a1); for(int i = 0; i < N; i++) { a1Map.put(a1[i],a1Map.getOrDefault(a1[i], 0) != 0?a1Map.get(a1[i])+1:1); temp[i] = a1[i]; } int idx = 0; for (int n: a2) { int mapVal = a1Map.getOrDefault(n,0); if (mapVal > 0) { for(int i=0; i<mapVal; i++) { a1[idx] = n; idx++; } a1Map.put(n,-1); //important line } } for (int n: temp) { int mapVal = a1Map.get(n); if (mapVal > 0) { a1[idx] = n; idx++; } } return a1; }"
},
{
"code": null,
"e": 7036,
"s": 7034,
"text": "0"
},
{
"code": null,
"e": 7064,
"s": 7036,
"text": "harshilgupta00993 weeks ago"
},
{
"code": null,
"e": 7829,
"s": 7064,
"text": "vector<int> sortA1ByA2(vector<int> arr1, int n, vector<int> arr2, int m) \n {\n //Your code here\n vector<int> ans;\n unordered_map<int,int> umap;\n for(int i=0;i<n;i++){\n umap[arr1[i]]++;\n }\n for(int i=0;i<m;i++){\n while(umap[arr2[i]]!=0){\n ans.push_back(arr2[i]);\n umap[arr2[i]]--;\n }\n if(umap[arr2[i]]==0)\n umap.erase(arr2[i]);\n }\n vector<int> v;\n for(auto x:umap){\n while(x.second!=0){\n v.push_back(x.first);\n x.second--;\n }\n \n }\n sort(v.begin(),v.end());\n for(int x:v)\n ans.push_back(x);\n return ans;\n } "
},
{
"code": null,
"e": 7831,
"s": 7829,
"text": "0"
},
{
"code": null,
"e": 7858,
"s": 7831,
"text": "shubham211019973 weeks ago"
},
{
"code": null,
"e": 7927,
"s": 7858,
"text": "public static int[] sortA1ByA2(int arr1[], int n, int arr2[], int m)"
},
{
"code": null,
"e": 7932,
"s": 7927,
"text": " {"
},
{
"code": null,
"e": 7956,
"s": 7932,
"text": " /* Naive Solution"
},
{
"code": null,
"e": 8008,
"s": 7956,
"text": " ArrayList<Integer>a=new ArrayList<Integer>();"
},
{
"code": null,
"e": 8030,
"s": 8008,
"text": " for(int i=0;i<n;i++)"
},
{
"code": null,
"e": 8048,
"s": 8030,
"text": " a.add(arr1[i]);"
},
{
"code": null,
"e": 8095,
"s": 8048,
"text": " ArrayList<Integer>b=new ArrayList<Integer>();"
},
{
"code": null,
"e": 8119,
"s": 8095,
"text": " for(int i=0;i<m;i++) {"
},
{
"code": null,
"e": 8137,
"s": 8119,
"text": " b.add(arr2[i]);"
},
{
"code": null,
"e": 8140,
"s": 8137,
"text": " }"
},
{
"code": null,
"e": 8163,
"s": 8140,
"text": " int arr[]=new int[n];"
},
{
"code": null,
"e": 8173,
"s": 8163,
"text": " int k=0;"
},
{
"code": null,
"e": 8197,
"s": 8173,
"text": " for(int i=0;i<m;i++) {"
},
{
"code": null,
"e": 8229,
"s": 8197,
"text": " while(a.contains(b.get(i))) {"
},
{
"code": null,
"e": 8256,
"s": 8229,
"text": " arr[k++]=b.get(i);"
},
{
"code": null,
"e": 8279,
"s": 8256,
"text": " a.remove(b.get(i));"
},
{
"code": null,
"e": 8283,
"s": 8279,
"text": " }"
},
{
"code": null,
"e": 8286,
"s": 8283,
"text": " }"
},
{
"code": null,
"e": 8317,
"s": 8286,
"text": " Collections.sort(a,(n1,n2)->{"
},
{
"code": null,
"e": 8333,
"s": 8317,
"text": " return n1-n2;"
},
{
"code": null,
"e": 8338,
"s": 8333,
"text": " });"
},
{
"code": null,
"e": 8369,
"s": 8338,
"text": " for(int i=0;i<a.size();i++) {"
},
{
"code": null,
"e": 8393,
"s": 8369,
"text": " arr[k++]=a.get(i);"
},
{
"code": null,
"e": 8396,
"s": 8393,
"text": " }"
},
{
"code": null,
"e": 8413,
"s": 8398,
"text": " return arr;*/"
},
{
"code": null,
"e": 8436,
"s": 8413,
"text": " int arr[]=new int[n];"
},
{
"code": null,
"e": 8446,
"s": 8436,
"text": " int k=0;"
},
{
"code": null,
"e": 8491,
"s": 8446,
"text": " TreeMap<Integer,Integer> h=new TreeMap<>();"
},
{
"code": null,
"e": 8509,
"s": 8491,
"text": " for(int i:arr1){"
},
{
"code": null,
"e": 8546,
"s": 8509,
"text": " h.put(i,h.getOrDefault(i,0)+1);"
},
{
"code": null,
"e": 8549,
"s": 8546,
"text": " }"
},
{
"code": null,
"e": 8567,
"s": 8549,
"text": " for(int i:arr2){"
},
{
"code": null,
"e": 8599,
"s": 8567,
"text": " if(h.containsKey(i)==true){"
},
{
"code": null,
"e": 8627,
"s": 8599,
"text": " while(h.get(i)!=0){"
},
{
"code": null,
"e": 8651,
"s": 8627,
"text": " arr[k++]=i;"
},
{
"code": null,
"e": 8684,
"s": 8651,
"text": " h.put(i,h.get(i)-1);"
},
{
"code": null,
"e": 8694,
"s": 8684,
"text": " }"
},
{
"code": null,
"e": 8715,
"s": 8694,
"text": " h.remove(i);"
},
{
"code": null,
"e": 8721,
"s": 8715,
"text": " }"
},
{
"code": null,
"e": 8724,
"s": 8721,
"text": " }"
},
{
"code": null,
"e": 8757,
"s": 8724,
"text": "// Collections.sort(h,(a,b)->{"
},
{
"code": null,
"e": 8779,
"s": 8757,
"text": "// return a-b; "
},
{
"code": null,
"e": 8788,
"s": 8779,
"text": "// });"
},
{
"code": null,
"e": 8836,
"s": 8788,
"text": " for(Entry<Integer,Integer> e : h.entrySet()){"
},
{
"code": null,
"e": 8874,
"s": 8836,
"text": " for(int p=0;p<e.getValue();p++)"
},
{
"code": null,
"e": 8905,
"s": 8874,
"text": " arr[k++]=e.getKey();"
},
{
"code": null,
"e": 8913,
"s": 8905,
"text": " }"
},
{
"code": null,
"e": 8942,
"s": 8924,
"text": " return arr; "
},
{
"code": null,
"e": 8947,
"s": 8942,
"text": " }"
},
{
"code": null,
"e": 8949,
"s": 8947,
"text": "0"
},
{
"code": null,
"e": 8976,
"s": 8949,
"text": "shubham211019973 weeks ago"
},
{
"code": null,
"e": 9510,
"s": 8976,
"text": "public static int[] sortA1ByA2(int arr1[], int n, int arr2[], int m)\n {\n ArrayList<Integer>a=new ArrayList<Integer>();\n for(int i=0;i<n;i++)\n a.add(arr1[i]);\n ArrayList<Integer>b=new ArrayList<Integer>();\n for(int i=0;i<m;i++) {\n b.add(arr2[i]);\n }\n int arr[]=new int[n];\n int k=0;\n for(int i=0;i<m;i++) {\n while(a.contains(b.get(i))) {\n arr[k++]=b.get(i);\n a.remove(b.get(i));\n }\n }\n Collections.sort(a,(n1,n2)->{\n return n1-n2;\n });\n for(int i=0;i<a.size();i++) {\n arr[k++]=a.get(i);\n }\n \n return arr;\n }"
},
{
"code": null,
"e": 9512,
"s": 9510,
"text": "0"
},
{
"code": null,
"e": 9547,
"s": 9512,
"text": "ravinuthalavamsikrishna3 weeks ago"
},
{
"code": null,
"e": 9894,
"s": 9547,
"text": " def relativeSort (self,A1, N, A2, M): # Your Code Here d={} for i in A1: d[i]=d.get(i,0)+1 l=[] l2=[] for i in A2: if i in d.keys(): l+=[i]*(d[i]) del d[i] l2=[] for i,j in d.items(): l2+=[i]*j l2.sort() l+=l2 return l"
},
{
"code": null,
"e": 10040,
"s": 9894,
"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": 10076,
"s": 10040,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 10086,
"s": 10076,
"text": "\nProblem\n"
},
{
"code": null,
"e": 10096,
"s": 10086,
"text": "\nContest\n"
},
{
"code": null,
"e": 10159,
"s": 10096,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 10307,
"s": 10159,
"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": 10515,
"s": 10307,
"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": 10621,
"s": 10515,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Add space between histogram bars in Matplotlib - GeeksforGeeks
|
24 Jan, 2021
Matplotlib is a plotting library in Python programming language and it’s by default numerical mathematics extension of NumPy library in python language. While programming in python language we use the matplotlib library package for graph and histogram visualizations. But while plotting histogram using matplotlib in python, it lacks division or space between adjacent bars. This makes histograms very tedious to work with and it becomes very difficult to interpret. In this article, we will study how to add space between histogram bars in matplotlib. Let’s understand with this example:
Example 1: Creating a simple plot.
Python3
import matplotlib.pyplot as plt values = [1, 2, 3, 3, 4, 5, 6, 6, 7, 8] # Adjust the bar widths hereplt.hist(values) plt.ylabel("Quantity")plt.xlabel("Value")plt.show()
Output:
Now we will add space between the histogram bars:
The space between bars can be added by using rwidth parameter inside the “plt.hist()” function. This value specifies the width of the bar with respect to its default width and the value of rwidth cannot be greater than 1.
Python3
import matplotlib.pyplot as plt values = [1, 2, 3, 3, 4, 5, 6, 6, 7, 8] # Adjust the bar widths hereplt.hist(values, rwidth=0.7) plt.ylabel("Quantity")plt.xlabel("Value")plt.show()
Output:
Example 2: Creating a simple plot.
Python3
# Implementation of matplotlib function import matplotlib import numpy as np import matplotlib.pyplot as plt np.random.seed(10**7) n_bins = 20x = np.random.randn(10000, 3) colors = ['green', 'blue', 'lime'] plt.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors) plt.legend(prop ={'size': 10}) plt.show()
Output:
With adding space:
Python3
# Implementation of matplotlib function import matplotlib import numpy as np import matplotlib.pyplot as plt np.random.seed(10**7) n_bins = 20x = np.random.randn(10000, 3) colors = ['green', 'blue', 'lime'] plt.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors, rwidth = 0.5) plt.legend(prop ={'size': 10}) plt.title('matplotlib.pyplot.hist() function Example\n\n', fontweight ="bold") plt.show()
Output:
Picked
Python-matplotlib
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 26150,
"s": 25561,
"text": "Matplotlib is a plotting library in Python programming language and it’s by default numerical mathematics extension of NumPy library in python language. While programming in python language we use the matplotlib library package for graph and histogram visualizations. But while plotting histogram using matplotlib in python, it lacks division or space between adjacent bars. This makes histograms very tedious to work with and it becomes very difficult to interpret. In this article, we will study how to add space between histogram bars in matplotlib. Let’s understand with this example:"
},
{
"code": null,
"e": 26185,
"s": 26150,
"text": "Example 1: Creating a simple plot."
},
{
"code": null,
"e": 26193,
"s": 26185,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt values = [1, 2, 3, 3, 4, 5, 6, 6, 7, 8] # Adjust the bar widths hereplt.hist(values) plt.ylabel(\"Quantity\")plt.xlabel(\"Value\")plt.show()",
"e": 26365,
"s": 26193,
"text": null
},
{
"code": null,
"e": 26373,
"s": 26365,
"text": "Output:"
},
{
"code": null,
"e": 26423,
"s": 26373,
"text": "Now we will add space between the histogram bars:"
},
{
"code": null,
"e": 26645,
"s": 26423,
"text": "The space between bars can be added by using rwidth parameter inside the “plt.hist()” function. This value specifies the width of the bar with respect to its default width and the value of rwidth cannot be greater than 1."
},
{
"code": null,
"e": 26653,
"s": 26645,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt values = [1, 2, 3, 3, 4, 5, 6, 6, 7, 8] # Adjust the bar widths hereplt.hist(values, rwidth=0.7) plt.ylabel(\"Quantity\")plt.xlabel(\"Value\")plt.show()",
"e": 26837,
"s": 26653,
"text": null
},
{
"code": null,
"e": 26845,
"s": 26837,
"text": "Output:"
},
{
"code": null,
"e": 26880,
"s": 26845,
"text": "Example 2: Creating a simple plot."
},
{
"code": null,
"e": 26888,
"s": 26880,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib function import matplotlib import numpy as np import matplotlib.pyplot as plt np.random.seed(10**7) n_bins = 20x = np.random.randn(10000, 3) colors = ['green', 'blue', 'lime'] plt.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors) plt.legend(prop ={'size': 10}) plt.show()",
"e": 27272,
"s": 26888,
"text": null
},
{
"code": null,
"e": 27280,
"s": 27272,
"text": "Output:"
},
{
"code": null,
"e": 27299,
"s": 27280,
"text": "With adding space:"
},
{
"code": null,
"e": 27307,
"s": 27299,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib function import matplotlib import numpy as np import matplotlib.pyplot as plt np.random.seed(10**7) n_bins = 20x = np.random.randn(10000, 3) colors = ['green', 'blue', 'lime'] plt.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors, rwidth = 0.5) plt.legend(prop ={'size': 10}) plt.title('matplotlib.pyplot.hist() function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 27808,
"s": 27307,
"text": null
},
{
"code": null,
"e": 27816,
"s": 27808,
"text": "Output:"
},
{
"code": null,
"e": 27823,
"s": 27816,
"text": "Picked"
},
{
"code": null,
"e": 27841,
"s": 27823,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27865,
"s": 27841,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27872,
"s": 27865,
"text": "Python"
},
{
"code": null,
"e": 27891,
"s": 27872,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27989,
"s": 27891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28021,
"s": 27989,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28063,
"s": 28021,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28105,
"s": 28063,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28161,
"s": 28105,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28188,
"s": 28161,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28227,
"s": 28188,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28258,
"s": 28227,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28280,
"s": 28258,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28309,
"s": 28280,
"text": "Create a directory in Python"
}
] |
Find k pairs with smallest sums in two arrays - GeeksforGeeks
|
03 Aug, 2021
Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples:
Input : arr1[] = {1, 7, 11}
arr2[] = {2, 4, 6}
k = 3
Output : [1, 2],
[1, 4],
[1, 6]
Explanation: The first 3 pairs are returned
from the sequence [1, 2], [1, 4], [1, 6],
[7, 2], [7, 4], [11, 2], [7, 6], [11, 4],
[11, 6]
Method 1 (Simple)
Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays.Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))
Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays.
Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))
Overall Time Complexity : O(n1 * n2 * log (n1 * n2))Method 2 (Efficient): We one by one find k smallest sum pairs, starting from least sum pair. The idea is to keep track of all elements of arr2[] which have been already considered for every element arr1[i1] so that in an iteration we only consider next element. For this purpose, we use an index array index2[] to track the indexes of next elements in the other array. It simply means that which element of second array to be added with the element of first array in each and every iteration. We increment value in index array for the element that forms next minimum value pair.
C++
Java
Python3
C#
Javascript
// C++ program to prints first k pairs with least sum from two// arrays.#include<bits/stdc++.h> using namespace std; // Function to find k pairs with least sum such// that one element of a pair is from arr1[] and// other element is from arr2[]void kSmallestPair(int arr1[], int n1, int arr2[], int n2, int k){ if (k > n1*n2) { cout << "k pairs don't exist"; return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. int index2[n1]; memset(index2, 0, sizeof(index2)); while (k > 0) { // Initialize current pair sum as infinite int min_sum = INT_MAX; int min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } cout << "(" << arr1[min_index] << ", " << arr2[index2[min_index]] << ") "; index2[min_index]++; k--; }} // Driver codeint main(){ int arr1[] = {1, 3, 11}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); return 0;}
// Java code to print first k pairs with least// sum from two arrays.import java.io.*; class KSmallestPair{ // Function to find k pairs with least sum such // that one element of a pair is from arr1[] and // other element is from arr2[] static void kSmallestPair(int arr1[], int n1, int arr2[], int n2, int k) { if (k > n1*n2) { System.out.print("k pairs don't exist"); return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. int index2[] = new int[n1]; while (k > 0) { // Initialize current pair sum as infinite int min_sum = Integer.MAX_VALUE; int min_index = 0; // To pick next pair, traverse for all // elements of arr1[], for every element, find // corresponding current element in arr2[] and // pick minimum of all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives // minimum sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } System.out.print("(" + arr1[min_index] + ", " + arr2[index2[min_index]]+ ") "); index2[min_index]++; k--; } } // Driver code public static void main (String[] args) { int arr1[] = {1, 3, 11}; int n1 = arr1.length; int arr2[] = {2, 4, 8}; int n2 = arr2.length; int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); }}/*This code is contributed by Prakriti Gupta*/
# Python3 program to prints first k pairs with least sum from two# arrays. import sys# Function to find k pairs with least sum such# that one element of a pair is from arr1[] and# other element is from arr2[]def kSmallestPair(arr1, n1, arr2, n2, k): if (k > n1*n2): print("k pairs don't exist") return # Stores current index in arr2[] for # every element of arr1[]. Initially # all values are considered 0. # Here current index is the index before # which all elements are considered as # part of output. index2 = [0 for i in range(n1)] while (k > 0): # Initialize current pair sum as infinite min_sum = sys.maxsize min_index = 0 # To pick next pair, traverse for all elements # of arr1[], for every element, find corresponding # current element in arr2[] and pick minimum of # all formed pairs. for i1 in range(0,n1,1): # Check if current element of arr1[] plus # element of array2 to be used gives minimum # sum if (index2[i1] < n2 and arr1[i1] + arr2[index2[i1]] < min_sum): # Update index that gives minimum min_index = i1 # update minimum sum min_sum = arr1[i1] + arr2[index2[i1]] print("(",arr1[min_index],",",arr2[index2[min_index]],")",end = " ") index2[min_index] += 1 k -= 1 # Driver codeif __name__ == '__main__': arr1 = [1, 3, 11] n1 = len(arr1) arr2 = [2, 4, 8] n2 = len(arr2) k = 4 kSmallestPair( arr1, n1, arr2, n2, k) # This code is contributed by# Shashank_Sharma
// C# code to print first k pairs with// least with least sum from two arrays.using System; class KSmallestPair{ // Function to find k pairs with least // sum such that one element of a pair // is from arr1[] and other element is // from arr2[] static void kSmallestPair(int []arr1, int n1, int []arr2, int n2, int k) { if (k > n1 * n2) { Console.Write("k pairs don't exist"); return; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. Here // current index is the index before // which all elements are considered // as part of output. int []index2 = new int[n1]; while (k > 0) { // Initialize current pair sum as infinite int min_sum = int.MaxValue; int min_index = 0; // To pick next pair, traverse for all // elements of arr1[], for every element, // find corresponding current element in // arr2[] and pick minimum of all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] // plus element of array2 to be used // gives minimum sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } Console.Write("(" + arr1[min_index] + ", " + arr2[index2[min_index]] + ") "); index2[min_index]++; k--; } } // Driver code public static void Main (String[] args) { int []arr1 = {1, 3, 11}; int n1 = arr1.Length; int []arr2 = {2, 4, 8}; int n2 = arr2.Length; int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); }} // This code is contributed by Parashar.
<script>// javascript program to prints first k pairs with least sum from two// arrays.// Function to find k pairs with least sum such// that one element of a pair is from arr1[] and// other element is from arr2[]function kSmallestPair(arr1,n1,arr2,n2,k){ if (k > n1*n2) { document.write("k pairs don't exist"); return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. let index2 = new Array(n1); index2.fill(0); while (k > 0) { // Initialize current pair sum as infinite let min_sum = Number.MAX_VALUE; let min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (let i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } document.write("(" + arr1[min_index] + ", " + arr2[index2[min_index]] + ") "); index2[min_index]++; k--; }} let arr1 = [1, 3, 11]; let n1 = arr1.length; let arr2 = [2, 4, 8]; let n2 = arr2.length; let k = 4; kSmallestPair( arr1, n1, arr2, n2, k); </script>
(1, 2) (1, 4) (3, 2) (3, 4)
Time Complexity : O(k*n1)Method 3 : Using Sorting, Min heap, Map Instead of brute forcing through all the possible sum combinations we should find a way to limit our search space to possible candidate sum combinations.
Sort both arrays array A and array B.Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum.Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements.Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j). Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.Go back to 4 until K times.
Sort both arrays array A and array B.
Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum.
Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements.
Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j). Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.Go back to 4 until K times.
Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.
Go back to 4 until K times.
C++
// C++ program to Prints// first k pairs with// least sum from two arrays. #include <bits/stdc++.h>using namespace std; // Function to find k pairs// with least sum such// that one element of a pair// is from arr1[] and// other element is from arr2[]void kSmallestPair(vector<int> A, vector<int> B, int K){ sort(A.begin(), A.end()); sort(B.begin(), B.end()); int n = A.size(); // Min heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices doe not repeat inside min heap. set<pair<int, int> > my_set; // initialize the heap with the minimum sum // combination i.e. (A[0] + B[0]) // and also push indices (0,0) along // with sum. pq.push(make_pair(A[0] + B[0], make_pair(0, 0))); my_set.insert(make_pair(0, 0)); // iterate upto K int flag=1; for (int count = 0; count < K && flag; count++) { // tuple format (sum, i, j). pair<int, pair<int, int> > temp = pq.top(); pq.pop(); int i = temp.second.first; int j = temp.second.second; cout << "(" << A[i] << ", " << B[j] << ")" << endl; // Extracting pair with least sum such // that one element is from arr1 and // another is from arr2 // check if i+1 is in the range of our first array A flag=0; if (i + 1 < A.size()) { int sum = A[i + 1] + B[j]; // insert (A[i + 1] + B[j], (i + 1, j)) // into min heap. pair<int, int> temp1 = make_pair(i + 1, j); // insert only if the pair (i + 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag=1; } // check if j+1 is in the range of our second array // B if (j + 1 < B.size()) { // insert (A[i] + B[j + 1], (i, j + 1)) // into min heap. int sum = A[i] + B[j + 1]; pair<int, int> temp1 = make_pair(i, j + 1); // insert only if the pair (i, j + 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag=1; } }} // Driver Code.int main(){ vector<int> A = { 1 }; vector<int> B = { 2, 4, 5, 9 }; int K = 3; kSmallestPair(A, B, K); return 0;} // This code is contributed by Dhairya.
(1, 2)
(1, 4)
(1, 5)
Time Complexity : O(n*logn) assuming k<=nReference : http://sudhansu-codezone.blogspot.in/2012/02/triplets-in-array-with-sum-0.htmlThis article is contributed by Sahil Chhabra . 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.
parashar
Dhairya Shah
Shashank_Sharma
shethnilay12
impwork8053
vaibhavrabadiya117
ss100429
sagartomar9927
Order-Statistics
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays in C/C++
Write a program to reverse an array or string
Program for array rotation
Largest Sum Contiguous Subarray
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 42521,
"s": 42493,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 42736,
"s": 42521,
"text": "Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: "
},
{
"code": null,
"e": 42997,
"s": 42736,
"text": "Input : arr1[] = {1, 7, 11}\n arr2[] = {2, 4, 6}\n k = 3\nOutput : [1, 2],\n [1, 4],\n [1, 6]\nExplanation: The first 3 pairs are returned \nfrom the sequence [1, 2], [1, 4], [1, 6], \n[7, 2], [7, 4], [11, 2], [7, 6], [11, 4], \n[11, 6]"
},
{
"code": null,
"e": 43017,
"s": 42997,
"text": "Method 1 (Simple) "
},
{
"code": null,
"e": 43232,
"s": 43017,
"text": "Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays.Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))"
},
{
"code": null,
"e": 43355,
"s": 43232,
"text": "Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays."
},
{
"code": null,
"e": 43448,
"s": 43355,
"text": "Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))"
},
{
"code": null,
"e": 44081,
"s": 43448,
"text": "Overall Time Complexity : O(n1 * n2 * log (n1 * n2))Method 2 (Efficient): We one by one find k smallest sum pairs, starting from least sum pair. The idea is to keep track of all elements of arr2[] which have been already considered for every element arr1[i1] so that in an iteration we only consider next element. For this purpose, we use an index array index2[] to track the indexes of next elements in the other array. It simply means that which element of second array to be added with the element of first array in each and every iteration. We increment value in index array for the element that forms next minimum value pair. "
},
{
"code": null,
"e": 44085,
"s": 44081,
"text": "C++"
},
{
"code": null,
"e": 44090,
"s": 44085,
"text": "Java"
},
{
"code": null,
"e": 44098,
"s": 44090,
"text": "Python3"
},
{
"code": null,
"e": 44101,
"s": 44098,
"text": "C#"
},
{
"code": null,
"e": 44112,
"s": 44101,
"text": "Javascript"
},
{
"code": "// C++ program to prints first k pairs with least sum from two// arrays.#include<bits/stdc++.h> using namespace std; // Function to find k pairs with least sum such// that one element of a pair is from arr1[] and// other element is from arr2[]void kSmallestPair(int arr1[], int n1, int arr2[], int n2, int k){ if (k > n1*n2) { cout << \"k pairs don't exist\"; return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. int index2[n1]; memset(index2, 0, sizeof(index2)); while (k > 0) { // Initialize current pair sum as infinite int min_sum = INT_MAX; int min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } cout << \"(\" << arr1[min_index] << \", \" << arr2[index2[min_index]] << \") \"; index2[min_index]++; k--; }} // Driver codeint main(){ int arr1[] = {1, 3, 11}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); return 0;}",
"e": 46009,
"s": 44112,
"text": null
},
{
"code": "// Java code to print first k pairs with least// sum from two arrays.import java.io.*; class KSmallestPair{ // Function to find k pairs with least sum such // that one element of a pair is from arr1[] and // other element is from arr2[] static void kSmallestPair(int arr1[], int n1, int arr2[], int n2, int k) { if (k > n1*n2) { System.out.print(\"k pairs don't exist\"); return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. int index2[] = new int[n1]; while (k > 0) { // Initialize current pair sum as infinite int min_sum = Integer.MAX_VALUE; int min_index = 0; // To pick next pair, traverse for all // elements of arr1[], for every element, find // corresponding current element in arr2[] and // pick minimum of all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives // minimum sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } System.out.print(\"(\" + arr1[min_index] + \", \" + arr2[index2[min_index]]+ \") \"); index2[min_index]++; k--; } } // Driver code public static void main (String[] args) { int arr1[] = {1, 3, 11}; int n1 = arr1.length; int arr2[] = {2, 4, 8}; int n2 = arr2.length; int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); }}/*This code is contributed by Prakriti Gupta*/",
"e": 48210,
"s": 46009,
"text": null
},
{
"code": "# Python3 program to prints first k pairs with least sum from two# arrays. import sys# Function to find k pairs with least sum such# that one element of a pair is from arr1[] and# other element is from arr2[]def kSmallestPair(arr1, n1, arr2, n2, k): if (k > n1*n2): print(\"k pairs don't exist\") return # Stores current index in arr2[] for # every element of arr1[]. Initially # all values are considered 0. # Here current index is the index before # which all elements are considered as # part of output. index2 = [0 for i in range(n1)] while (k > 0): # Initialize current pair sum as infinite min_sum = sys.maxsize min_index = 0 # To pick next pair, traverse for all elements # of arr1[], for every element, find corresponding # current element in arr2[] and pick minimum of # all formed pairs. for i1 in range(0,n1,1): # Check if current element of arr1[] plus # element of array2 to be used gives minimum # sum if (index2[i1] < n2 and arr1[i1] + arr2[index2[i1]] < min_sum): # Update index that gives minimum min_index = i1 # update minimum sum min_sum = arr1[i1] + arr2[index2[i1]] print(\"(\",arr1[min_index],\",\",arr2[index2[min_index]],\")\",end = \" \") index2[min_index] += 1 k -= 1 # Driver codeif __name__ == '__main__': arr1 = [1, 3, 11] n1 = len(arr1) arr2 = [2, 4, 8] n2 = len(arr2) k = 4 kSmallestPair( arr1, n1, arr2, n2, k) # This code is contributed by# Shashank_Sharma",
"e": 49848,
"s": 48210,
"text": null
},
{
"code": "// C# code to print first k pairs with// least with least sum from two arrays.using System; class KSmallestPair{ // Function to find k pairs with least // sum such that one element of a pair // is from arr1[] and other element is // from arr2[] static void kSmallestPair(int []arr1, int n1, int []arr2, int n2, int k) { if (k > n1 * n2) { Console.Write(\"k pairs don't exist\"); return; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. Here // current index is the index before // which all elements are considered // as part of output. int []index2 = new int[n1]; while (k > 0) { // Initialize current pair sum as infinite int min_sum = int.MaxValue; int min_index = 0; // To pick next pair, traverse for all // elements of arr1[], for every element, // find corresponding current element in // arr2[] and pick minimum of all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] // plus element of array2 to be used // gives minimum sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } Console.Write(\"(\" + arr1[min_index] + \", \" + arr2[index2[min_index]] + \") \"); index2[min_index]++; k--; } } // Driver code public static void Main (String[] args) { int []arr1 = {1, 3, 11}; int n1 = arr1.Length; int []arr2 = {2, 4, 8}; int n2 = arr2.Length; int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); }} // This code is contributed by Parashar.",
"e": 52011,
"s": 49848,
"text": null
},
{
"code": "<script>// javascript program to prints first k pairs with least sum from two// arrays.// Function to find k pairs with least sum such// that one element of a pair is from arr1[] and// other element is from arr2[]function kSmallestPair(arr1,n1,arr2,n2,k){ if (k > n1*n2) { document.write(\"k pairs don't exist\"); return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. let index2 = new Array(n1); index2.fill(0); while (k > 0) { // Initialize current pair sum as infinite let min_sum = Number.MAX_VALUE; let min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (let i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } document.write(\"(\" + arr1[min_index] + \", \" + arr2[index2[min_index]] + \") \"); index2[min_index]++; k--; }} let arr1 = [1, 3, 11]; let n1 = arr1.length; let arr2 = [2, 4, 8]; let n2 = arr2.length; let k = 4; kSmallestPair( arr1, n1, arr2, n2, k); </script>",
"e": 53767,
"s": 52011,
"text": null
},
{
"code": null,
"e": 53796,
"s": 53767,
"text": "(1, 2) (1, 4) (3, 2) (3, 4) "
},
{
"code": null,
"e": 54017,
"s": 53796,
"text": "Time Complexity : O(k*n1)Method 3 : Using Sorting, Min heap, Map Instead of brute forcing through all the possible sum combinations we should find a way to limit our search space to possible candidate sum combinations. "
},
{
"code": null,
"e": 54889,
"s": 54017,
"text": "Sort both arrays array A and array B.Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum.Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements.Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j). Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.Go back to 4 until K times."
},
{
"code": null,
"e": 54927,
"s": 54889,
"text": "Sort both arrays array A and array B."
},
{
"code": null,
"e": 55112,
"s": 54927,
"text": "Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum."
},
{
"code": null,
"e": 55362,
"s": 55112,
"text": "Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements."
},
{
"code": null,
"e": 55764,
"s": 55362,
"text": "Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j). Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.Go back to 4 until K times."
},
{
"code": null,
"e": 56000,
"s": 55764,
"text": "Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++."
},
{
"code": null,
"e": 56028,
"s": 56000,
"text": "Go back to 4 until K times."
},
{
"code": null,
"e": 56032,
"s": 56028,
"text": "C++"
},
{
"code": "// C++ program to Prints// first k pairs with// least sum from two arrays. #include <bits/stdc++.h>using namespace std; // Function to find k pairs// with least sum such// that one element of a pair// is from arr1[] and// other element is from arr2[]void kSmallestPair(vector<int> A, vector<int> B, int K){ sort(A.begin(), A.end()); sort(B.begin(), B.end()); int n = A.size(); // Min heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices doe not repeat inside min heap. set<pair<int, int> > my_set; // initialize the heap with the minimum sum // combination i.e. (A[0] + B[0]) // and also push indices (0,0) along // with sum. pq.push(make_pair(A[0] + B[0], make_pair(0, 0))); my_set.insert(make_pair(0, 0)); // iterate upto K int flag=1; for (int count = 0; count < K && flag; count++) { // tuple format (sum, i, j). pair<int, pair<int, int> > temp = pq.top(); pq.pop(); int i = temp.second.first; int j = temp.second.second; cout << \"(\" << A[i] << \", \" << B[j] << \")\" << endl; // Extracting pair with least sum such // that one element is from arr1 and // another is from arr2 // check if i+1 is in the range of our first array A flag=0; if (i + 1 < A.size()) { int sum = A[i + 1] + B[j]; // insert (A[i + 1] + B[j], (i + 1, j)) // into min heap. pair<int, int> temp1 = make_pair(i + 1, j); // insert only if the pair (i + 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag=1; } // check if j+1 is in the range of our second array // B if (j + 1 < B.size()) { // insert (A[i] + B[j + 1], (i, j + 1)) // into min heap. int sum = A[i] + B[j + 1]; pair<int, int> temp1 = make_pair(i, j + 1); // insert only if the pair (i, j + 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag=1; } }} // Driver Code.int main(){ vector<int> A = { 1 }; vector<int> B = { 2, 4, 5, 9 }; int K = 3; kSmallestPair(A, B, K); return 0;} // This code is contributed by Dhairya.",
"e": 59031,
"s": 56032,
"text": null
},
{
"code": null,
"e": 59052,
"s": 59031,
"text": "(1, 2)\n(1, 4)\n(1, 5)"
},
{
"code": null,
"e": 59605,
"s": 59052,
"text": "Time Complexity : O(n*logn) assuming k<=nReference : http://sudhansu-codezone.blogspot.in/2012/02/triplets-in-array-with-sum-0.htmlThis article is contributed by Sahil Chhabra . 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."
},
{
"code": null,
"e": 59614,
"s": 59605,
"text": "parashar"
},
{
"code": null,
"e": 59627,
"s": 59614,
"text": "Dhairya Shah"
},
{
"code": null,
"e": 59643,
"s": 59627,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 59656,
"s": 59643,
"text": "shethnilay12"
},
{
"code": null,
"e": 59668,
"s": 59656,
"text": "impwork8053"
},
{
"code": null,
"e": 59687,
"s": 59668,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 59696,
"s": 59687,
"text": "ss100429"
},
{
"code": null,
"e": 59711,
"s": 59696,
"text": "sagartomar9927"
},
{
"code": null,
"e": 59728,
"s": 59711,
"text": "Order-Statistics"
},
{
"code": null,
"e": 59735,
"s": 59728,
"text": "Arrays"
},
{
"code": null,
"e": 59742,
"s": 59735,
"text": "Arrays"
},
{
"code": null,
"e": 59840,
"s": 59742,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 59855,
"s": 59840,
"text": "Arrays in Java"
},
{
"code": null,
"e": 59871,
"s": 59855,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 59917,
"s": 59871,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 59944,
"s": 59917,
"text": "Program for array rotation"
},
{
"code": null,
"e": 59976,
"s": 59944,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 60020,
"s": 59976,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 60068,
"s": 60020,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 60091,
"s": 60068,
"text": "Introduction to Arrays"
}
] |
Inner Class in Java - GeeksforGeeks
|
24 Feb, 2022
In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is purely object-oriented so bringing it closer to the real world. Now geeks you must be wondering why they were introduced?
There are certain advantages associated with inner classes are as follows:
Making code clean and readable.
Private methods of the outer class can be accessed, so bringing a new dimension and making it closer to the real world.
Optimizing the code module.
We do use them often as we go advance in java object-oriented programming where we want certain operations to be performed, granting access to limited classes and many more which will be clear as we do discuss and implement all types of inner classes in Java.
There are basically four types of inner classes in java.
Nested Inner ClassMethod Local Inner ClassesStatic Nested ClassesAnonymous Inner Classes
Nested Inner Class
Method Local Inner Classes
Static Nested Classes
Anonymous Inner Classes
Let us discuss each of the above following types sequentially in-depth alongside a clean java program which is very crucial at every step as it becomes quite tricky as we adhere forwards.
Type 1: Nested Inner Class
It can access any private instance variable of the outer class. Like any other instance variable, we can have access modifier private, protected, public, and default modifier. Like class, an interface can also be nested and can have access specifiers.
Example 1A
Java
// Java Program to Demonstrate Nested class // Class 1// Helper classesclass Outer { // Class 2 // Simple nested inner class class Inner { // show() method of inner class public void show() { // Print statement System.out.println("In a nested class method"); } }} // Class 2// Main classclass Main { // Main driver method public static void main(String[] args) { // Note how inner class object is created inside // main() Outer.Inner in = new Outer().new Inner(); // Calling show() method over above object created in.show(); }}
In a nested class method
Note: We can not have a static method in a nested inner class because an inner class is implicitly associated with an object of its outer class so it cannot define any static method for itself. For example, the following program doesn’t compile.
Example 1B
Java
// Java Program to Demonstrate Nested class // Where Error is thrown // Class 1// Outer classclass Outer { // Method defined inside outer class void outerMethod() { // Print statement System.out.println("inside outerMethod"); } // Class 2 // Inner class class Inner { // Main driver method public static void main(String[] args) { // Display message for better readability System.out.println("inside inner class Method"); } }}
Output:
An interface can also be nested and nested interfaces have some interesting properties. We will be covering nested interfaces in the next post.
Type 2: Method Local Inner Classes
Inner class can be declared within a method of an outer class which we will be illustrating in the below example where Inner is an inner class in outerMethod().
Example 1
Java
// Java Program to Illustrate Inner class can be// declared within a method of outer class // Class 1// Outer classclass Outer { // Method inside outer class void outerMethod() { // Print statement System.out.println("inside outerMethod"); // Class 2 // Inner class // It is local to outerMethod() class Inner { // Method defined inside inner class void innerMethod() { // Print statement whenever inner class is // called System.out.println("inside innerMethod"); } } // Creating object of inner class Inner y = new Inner(); // Calling over method defined inside it y.innerMethod(); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of outer class inside main() // method Outer x = new Outer(); // Calling over the same method // as we did for inner class above x.outerMethod(); }}
inside outerMethod
inside innerMethod
Method Local inner classes can’t use a local variable of the outer method until that local variable is not declared as final. For example, the following code generates a compiler error.
Note: “x” is not final in outerMethod() and innerMethod() tries to access it.
Example 2
Java
class Outer { void outerMethod() { int x = 98; System.out.println("inside outerMethod"); class Inner { void innerMethod() { System.out.println("x= "+x); } } Inner y = new Inner(); y.innerMethod(); }}class MethodLocalVariableDemo { public static void main(String[] args) { Outer x=new Outer(); x.outerMethod(); }}
inside outerMethod
x= 98
Note: Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in method local inner class.
But the following code compiles and runs fine (Note that x is final this time)
Example 3
Java
class Outer { void outerMethod() { final int x=98; System.out.println("inside outerMethod"); class Inner { void innerMethod() { System.out.println("x = "+x); } } Inner y = new Inner(); y.innerMethod(); }}class MethodLocalVariableDemo { public static void main(String[] args){ Outer x = new Outer(); x.outerMethod(); }}
inside outerMethod
x = 98
The main reason we need to declare a local variable as a final is that the local variable lives on the stack till the method is on the stack but there might be a case the object of the inner class still lives on the heap. Method local inner class can’t be marked as private, protected, static, and transient but can be marked as abstract and final, but not both at the same time.
Type 3: Static Nested Classes
Static nested classes are not technically inner classes. They are like a static member of outer class.
Example
Java
// Java Program to Illustrate Static Nested Classes // Importing required classesimport java.util.*; // Class 1// Outer classclass Outer { // Method private static void outerMethod() { // Print statement System.out.println("inside outerMethod"); } // Class 2 // Static inner class static class Inner { public static void display() { // Print statement System.out.println("inside inner class Method"); // Calling method inside main() method outerMethod(); } }} // Class 3// Main classclass GFG { // Main driver method public static void main(String args[]) { Outer.Inner obj = new Outer.Inner(); // Calling method via above instance created obj.display(); }}
inside inner class Method
inside outerMethod
Type 4: Anonymous Inner Classes
Anonymous inner classes are declared without any name at all. They are created in two ways.
As a subclass of the specified type
As an implementer of the specified interface
Way 1: As a subclass of the specified type
Example:
Java
// Java Program to Illustrate Anonymous Inner classes// Declaration Without any Name // As a subclass of the specified type // Importing required classesimport java.util.*; // Class 1// Helper classclass Demo { // Method of helper class void show() { // Print statement System.out.println( "i am in show method of super class"); }} // Class 2// Main classclass Flavor1Demo { // An anonymous class with Demo as base class static Demo d = new Demo() { // Method 1 // show() method void show() { // Calling method show() via super keyword // which refers to parent class super.show(); // Print statement System.out.println("i am in Flavor1Demo class"); } }; // Method 2 // Main driver method public static void main(String[] args) { // Calling show() method inside main() method d.show(); }}
i am in show method of super class
i am in Flavor1Demo class
In the above code, we have two classes Demo and Flavor1Demo. Here demo act as a super-class and the anonymous class acts as a subclass, both classes have a method show(). In anonymous class show() method is overridden.
Way 2: As an implementer of the specified interface
Example:
Java
// Java Program to Illustrate Anonymous Inner Classes// Declaration Without Any Name// As an implementer of Specified interface // Interfaceinterface Hello { // Method defined inside interface void show();} // Main classclass GFG { // Class implementing interface static Hello h = new Hello() { // Method 1 // show() method inside main class public void show() { // Print statement System.out.println("i am in anonymous class"); } }; // Method 2 // Main driver method public static void main(String[] args) { // Calling show() method inside main() method h.show(); }}
i am in anonymous class
Output explanation:
In the above code, we create an object of anonymous inner class but this anonymous inner class is an implementer of the interface Hello. Any anonymous inner class can implement only one interface at one time. It can either extend a class or implement an interface at a time.This article is contributed by Pawan Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
surinderdawra388
chhabradhanvi
surindertarika1234
prachisoda1234
kashishsoda
akshitsaxenaa09
as5853535
simmytarika5
Java
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
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 24577,
"s": 24549,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 24869,
"s": 24577,
"text": "In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is purely object-oriented so bringing it closer to the real world. Now geeks you must be wondering why they were introduced? "
},
{
"code": null,
"e": 24944,
"s": 24869,
"text": "There are certain advantages associated with inner classes are as follows:"
},
{
"code": null,
"e": 24976,
"s": 24944,
"text": "Making code clean and readable."
},
{
"code": null,
"e": 25096,
"s": 24976,
"text": "Private methods of the outer class can be accessed, so bringing a new dimension and making it closer to the real world."
},
{
"code": null,
"e": 25124,
"s": 25096,
"text": "Optimizing the code module."
},
{
"code": null,
"e": 25384,
"s": 25124,
"text": "We do use them often as we go advance in java object-oriented programming where we want certain operations to be performed, granting access to limited classes and many more which will be clear as we do discuss and implement all types of inner classes in Java."
},
{
"code": null,
"e": 25441,
"s": 25384,
"text": "There are basically four types of inner classes in java."
},
{
"code": null,
"e": 25530,
"s": 25441,
"text": "Nested Inner ClassMethod Local Inner ClassesStatic Nested ClassesAnonymous Inner Classes"
},
{
"code": null,
"e": 25549,
"s": 25530,
"text": "Nested Inner Class"
},
{
"code": null,
"e": 25576,
"s": 25549,
"text": "Method Local Inner Classes"
},
{
"code": null,
"e": 25598,
"s": 25576,
"text": "Static Nested Classes"
},
{
"code": null,
"e": 25622,
"s": 25598,
"text": "Anonymous Inner Classes"
},
{
"code": null,
"e": 25810,
"s": 25622,
"text": "Let us discuss each of the above following types sequentially in-depth alongside a clean java program which is very crucial at every step as it becomes quite tricky as we adhere forwards."
},
{
"code": null,
"e": 25838,
"s": 25810,
"text": "Type 1: Nested Inner Class "
},
{
"code": null,
"e": 26091,
"s": 25838,
"text": "It can access any private instance variable of the outer class. Like any other instance variable, we can have access modifier private, protected, public, and default modifier. Like class, an interface can also be nested and can have access specifiers. "
},
{
"code": null,
"e": 26102,
"s": 26091,
"text": "Example 1A"
},
{
"code": null,
"e": 26107,
"s": 26102,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Nested class // Class 1// Helper classesclass Outer { // Class 2 // Simple nested inner class class Inner { // show() method of inner class public void show() { // Print statement System.out.println(\"In a nested class method\"); } }} // Class 2// Main classclass Main { // Main driver method public static void main(String[] args) { // Note how inner class object is created inside // main() Outer.Inner in = new Outer().new Inner(); // Calling show() method over above object created in.show(); }}",
"e": 26752,
"s": 26107,
"text": null
},
{
"code": null,
"e": 26777,
"s": 26752,
"text": "In a nested class method"
},
{
"code": null,
"e": 27025,
"s": 26777,
"text": "Note: We can not have a static method in a nested inner class because an inner class is implicitly associated with an object of its outer class so it cannot define any static method for itself. For example, the following program doesn’t compile. "
},
{
"code": null,
"e": 27036,
"s": 27025,
"text": "Example 1B"
},
{
"code": null,
"e": 27041,
"s": 27036,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Nested class // Where Error is thrown // Class 1// Outer classclass Outer { // Method defined inside outer class void outerMethod() { // Print statement System.out.println(\"inside outerMethod\"); } // Class 2 // Inner class class Inner { // Main driver method public static void main(String[] args) { // Display message for better readability System.out.println(\"inside inner class Method\"); } }}",
"e": 27561,
"s": 27041,
"text": null
},
{
"code": null,
"e": 27569,
"s": 27561,
"text": "Output:"
},
{
"code": null,
"e": 27713,
"s": 27569,
"text": "An interface can also be nested and nested interfaces have some interesting properties. We will be covering nested interfaces in the next post."
},
{
"code": null,
"e": 27749,
"s": 27713,
"text": "Type 2: Method Local Inner Classes "
},
{
"code": null,
"e": 27910,
"s": 27749,
"text": "Inner class can be declared within a method of an outer class which we will be illustrating in the below example where Inner is an inner class in outerMethod()."
},
{
"code": null,
"e": 27920,
"s": 27910,
"text": "Example 1"
},
{
"code": null,
"e": 27925,
"s": 27920,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Inner class can be// declared within a method of outer class // Class 1// Outer classclass Outer { // Method inside outer class void outerMethod() { // Print statement System.out.println(\"inside outerMethod\"); // Class 2 // Inner class // It is local to outerMethod() class Inner { // Method defined inside inner class void innerMethod() { // Print statement whenever inner class is // called System.out.println(\"inside innerMethod\"); } } // Creating object of inner class Inner y = new Inner(); // Calling over method defined inside it y.innerMethod(); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of outer class inside main() // method Outer x = new Outer(); // Calling over the same method // as we did for inner class above x.outerMethod(); }}",
"e": 29020,
"s": 27925,
"text": null
},
{
"code": null,
"e": 29058,
"s": 29020,
"text": "inside outerMethod\ninside innerMethod"
},
{
"code": null,
"e": 29245,
"s": 29058,
"text": "Method Local inner classes can’t use a local variable of the outer method until that local variable is not declared as final. For example, the following code generates a compiler error. "
},
{
"code": null,
"e": 29323,
"s": 29245,
"text": "Note: “x” is not final in outerMethod() and innerMethod() tries to access it."
},
{
"code": null,
"e": 29333,
"s": 29323,
"text": "Example 2"
},
{
"code": null,
"e": 29338,
"s": 29333,
"text": "Java"
},
{
"code": "class Outer { void outerMethod() { int x = 98; System.out.println(\"inside outerMethod\"); class Inner { void innerMethod() { System.out.println(\"x= \"+x); } } Inner y = new Inner(); y.innerMethod(); }}class MethodLocalVariableDemo { public static void main(String[] args) { Outer x=new Outer(); x.outerMethod(); }}",
"e": 29726,
"s": 29338,
"text": null
},
{
"code": null,
"e": 29751,
"s": 29726,
"text": "inside outerMethod\nx= 98"
},
{
"code": null,
"e": 29927,
"s": 29751,
"text": "Note: Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in method local inner class. "
},
{
"code": null,
"e": 30007,
"s": 29927,
"text": "But the following code compiles and runs fine (Note that x is final this time) "
},
{
"code": null,
"e": 30017,
"s": 30007,
"text": "Example 3"
},
{
"code": null,
"e": 30022,
"s": 30017,
"text": "Java"
},
{
"code": "class Outer { void outerMethod() { final int x=98; System.out.println(\"inside outerMethod\"); class Inner { void innerMethod() { System.out.println(\"x = \"+x); } } Inner y = new Inner(); y.innerMethod(); }}class MethodLocalVariableDemo { public static void main(String[] args){ Outer x = new Outer(); x.outerMethod(); }}",
"e": 30418,
"s": 30022,
"text": null
},
{
"code": null,
"e": 30444,
"s": 30418,
"text": "inside outerMethod\nx = 98"
},
{
"code": null,
"e": 30824,
"s": 30444,
"text": "The main reason we need to declare a local variable as a final is that the local variable lives on the stack till the method is on the stack but there might be a case the object of the inner class still lives on the heap. Method local inner class can’t be marked as private, protected, static, and transient but can be marked as abstract and final, but not both at the same time."
},
{
"code": null,
"e": 30854,
"s": 30824,
"text": "Type 3: Static Nested Classes"
},
{
"code": null,
"e": 30958,
"s": 30854,
"text": "Static nested classes are not technically inner classes. They are like a static member of outer class. "
},
{
"code": null,
"e": 30966,
"s": 30958,
"text": "Example"
},
{
"code": null,
"e": 30971,
"s": 30966,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Static Nested Classes // Importing required classesimport java.util.*; // Class 1// Outer classclass Outer { // Method private static void outerMethod() { // Print statement System.out.println(\"inside outerMethod\"); } // Class 2 // Static inner class static class Inner { public static void display() { // Print statement System.out.println(\"inside inner class Method\"); // Calling method inside main() method outerMethod(); } }} // Class 3// Main classclass GFG { // Main driver method public static void main(String args[]) { Outer.Inner obj = new Outer.Inner(); // Calling method via above instance created obj.display(); }}",
"e": 31774,
"s": 30971,
"text": null
},
{
"code": null,
"e": 31819,
"s": 31774,
"text": "inside inner class Method\ninside outerMethod"
},
{
"code": null,
"e": 31852,
"s": 31819,
"text": "Type 4: Anonymous Inner Classes "
},
{
"code": null,
"e": 31945,
"s": 31852,
"text": "Anonymous inner classes are declared without any name at all. They are created in two ways. "
},
{
"code": null,
"e": 31981,
"s": 31945,
"text": "As a subclass of the specified type"
},
{
"code": null,
"e": 32026,
"s": 31981,
"text": "As an implementer of the specified interface"
},
{
"code": null,
"e": 32070,
"s": 32026,
"text": "Way 1: As a subclass of the specified type "
},
{
"code": null,
"e": 32079,
"s": 32070,
"text": "Example:"
},
{
"code": null,
"e": 32084,
"s": 32079,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Anonymous Inner classes// Declaration Without any Name // As a subclass of the specified type // Importing required classesimport java.util.*; // Class 1// Helper classclass Demo { // Method of helper class void show() { // Print statement System.out.println( \"i am in show method of super class\"); }} // Class 2// Main classclass Flavor1Demo { // An anonymous class with Demo as base class static Demo d = new Demo() { // Method 1 // show() method void show() { // Calling method show() via super keyword // which refers to parent class super.show(); // Print statement System.out.println(\"i am in Flavor1Demo class\"); } }; // Method 2 // Main driver method public static void main(String[] args) { // Calling show() method inside main() method d.show(); }}",
"e": 33043,
"s": 32084,
"text": null
},
{
"code": null,
"e": 33104,
"s": 33043,
"text": "i am in show method of super class\ni am in Flavor1Demo class"
},
{
"code": null,
"e": 33323,
"s": 33104,
"text": "In the above code, we have two classes Demo and Flavor1Demo. Here demo act as a super-class and the anonymous class acts as a subclass, both classes have a method show(). In anonymous class show() method is overridden."
},
{
"code": null,
"e": 33377,
"s": 33323,
"text": "Way 2: As an implementer of the specified interface "
},
{
"code": null,
"e": 33386,
"s": 33377,
"text": "Example:"
},
{
"code": null,
"e": 33391,
"s": 33386,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Anonymous Inner Classes// Declaration Without Any Name// As an implementer of Specified interface // Interfaceinterface Hello { // Method defined inside interface void show();} // Main classclass GFG { // Class implementing interface static Hello h = new Hello() { // Method 1 // show() method inside main class public void show() { // Print statement System.out.println(\"i am in anonymous class\"); } }; // Method 2 // Main driver method public static void main(String[] args) { // Calling show() method inside main() method h.show(); }}",
"e": 34070,
"s": 33391,
"text": null
},
{
"code": null,
"e": 34094,
"s": 34070,
"text": "i am in anonymous class"
},
{
"code": null,
"e": 34114,
"s": 34094,
"text": "Output explanation:"
},
{
"code": null,
"e": 34557,
"s": 34114,
"text": "In the above code, we create an object of anonymous inner class but this anonymous inner class is an implementer of the interface Hello. Any anonymous inner class can implement only one interface at one time. It can either extend a class or implement an interface at a time.This article is contributed by Pawan Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 34571,
"s": 34557,
"text": "solankimayank"
},
{
"code": null,
"e": 34588,
"s": 34571,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34602,
"s": 34588,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 34621,
"s": 34602,
"text": "surindertarika1234"
},
{
"code": null,
"e": 34636,
"s": 34621,
"text": "prachisoda1234"
},
{
"code": null,
"e": 34648,
"s": 34636,
"text": "kashishsoda"
},
{
"code": null,
"e": 34664,
"s": 34648,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 34674,
"s": 34664,
"text": "as5853535"
},
{
"code": null,
"e": 34687,
"s": 34674,
"text": "simmytarika5"
},
{
"code": null,
"e": 34692,
"s": 34687,
"text": "Java"
},
{
"code": null,
"e": 34697,
"s": 34692,
"text": "Java"
},
{
"code": null,
"e": 34795,
"s": 34697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34810,
"s": 34795,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34854,
"s": 34810,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34876,
"s": 34854,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 34927,
"s": 34876,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 34963,
"s": 34927,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 34988,
"s": 34963,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35018,
"s": 34988,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 35033,
"s": 35018,
"text": "Stream In Java"
},
{
"code": null,
"e": 35052,
"s": 35033,
"text": "Interfaces in Java"
}
] |
Scala Int toChar() method with example - GeeksforGeeks
|
04 Feb, 2020
The toChar() method is utilized to convert the specified int number into char type value.
Method Definition: (Number).toChar
Return Type: It returns the converted char datatype value.
Example #1:
// Scala program of Int toChar()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toChar method val result = (64).toChar // Displays output println(result) }}
@
Example #2:
// Scala program of Int toChar()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toChar method val result = (68).toChar // Displays output println(result) }}
D
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
Scala | Traits
Scala ListBuffer
Scala | Case Class and Case Object
Hello World in Scala
Scala | Functions - Basics
Scala | Try-Catch Exceptions
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Comments In Scala
Scala List map() method with example
|
[
{
"code": null,
"e": 25301,
"s": 25273,
"text": "\n04 Feb, 2020"
},
{
"code": null,
"e": 25391,
"s": 25301,
"text": "The toChar() method is utilized to convert the specified int number into char type value."
},
{
"code": null,
"e": 25426,
"s": 25391,
"text": "Method Definition: (Number).toChar"
},
{
"code": null,
"e": 25485,
"s": 25426,
"text": "Return Type: It returns the converted char datatype value."
},
{
"code": null,
"e": 25497,
"s": 25485,
"text": "Example #1:"
},
{
"code": "// Scala program of Int toChar()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toChar method val result = (64).toChar // Displays output println(result) }} ",
"e": 25765,
"s": 25497,
"text": null
},
{
"code": null,
"e": 25768,
"s": 25765,
"text": "@\n"
},
{
"code": null,
"e": 25780,
"s": 25768,
"text": "Example #2:"
},
{
"code": "// Scala program of Int toChar()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toChar method val result = (68).toChar // Displays output println(result) }} ",
"e": 26048,
"s": 25780,
"text": null
},
{
"code": null,
"e": 26051,
"s": 26048,
"text": "D\n"
},
{
"code": null,
"e": 26057,
"s": 26051,
"text": "Scala"
},
{
"code": null,
"e": 26070,
"s": 26057,
"text": "Scala-Method"
},
{
"code": null,
"e": 26076,
"s": 26070,
"text": "Scala"
},
{
"code": null,
"e": 26174,
"s": 26076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26195,
"s": 26174,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 26210,
"s": 26195,
"text": "Scala | Traits"
},
{
"code": null,
"e": 26227,
"s": 26210,
"text": "Scala ListBuffer"
},
{
"code": null,
"e": 26262,
"s": 26227,
"text": "Scala | Case Class and Case Object"
},
{
"code": null,
"e": 26283,
"s": 26262,
"text": "Hello World in Scala"
},
{
"code": null,
"e": 26310,
"s": 26283,
"text": "Scala | Functions - Basics"
},
{
"code": null,
"e": 26339,
"s": 26310,
"text": "Scala | Try-Catch Exceptions"
},
{
"code": null,
"e": 26405,
"s": 26339,
"text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)"
},
{
"code": null,
"e": 26423,
"s": 26405,
"text": "Comments In Scala"
}
] |
Getter and Setter in Java - GeeksforGeeks
|
12 Apr, 2022
Getter and Setter are methods used to protect your data and make your code more secure. Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the convenience of the program, getter starts with the word “get” followed by the variable name.
While Setter sets or updates the value (mutators). It sets the value for any variable which is used in the programs of a class. and starts with the word “set” followed by the variable name. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type. In both getter and setter, the first letter of the variable should be capital.
Example 1
Java
// Java Program to Illustrate Getter and Setter // Importing input output classesimport java.io.*; // Class 1// Helper classclass GetSet { // Member variable of this class private String name; // Method 1 - Getter public String getName() { return name; } // Method 2 - Setter public void setName(String N) { // This keyword refers to current instance itself this.name = N; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of class 1 in main() method GetSet obj = new GetSet(); // Setting the name by calling setter method obj.setName("Geeks for Geeks"); // Getting the name by calling geter method System.out.println(obj.getName()); }}
Geeks for Geeks
Getter and Setter give you the convenience to enter the value of the variables of any data type as per accordance with the requirement of the code. Getters and setters let you manage how crucial variables in your code are accessed and altered. It can be seen as in the program been discussed below as follows:
Example 2
Java
// Java Program to Illustrate Getter and Setter // Importing input output classesimport java.io.*; class GetSet { // Member variable of this class private int num; // Method 1 - Setter public void setNumber(int number) { // Checking if number if between 1 to 10 exclusive if (number < 1 || number > 10) { throw new IllegalArgumentException(); } num = number; } // Method 2 - Getter public int getNumber() { return num; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { GetSet obj = new GetSet(); // Calling method 1 inside main() method obj.setNumber(5); // Printing the number as setted above System.out.println(obj.getNumber()); }}
5
Output explanation:
Here we can see that if we take a value greater than 10 then it shows an error, By using the setNumber() method, one can be sure the value of a number is always between 1 and 10. This is much better than updating the number variable directly.
Note: This could be avoided by making the number a private variable and utilizing the setNumber method. Using a getter method, on the other hand, is the sole way to read a number’s value.
mehtayash2001
gulshankumarpal4
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Internal Working of HashMap in Java
|
[
{
"code": null,
"e": 25261,
"s": 25233,
"text": "\n12 Apr, 2022"
},
{
"code": null,
"e": 25555,
"s": 25261,
"text": "Getter and Setter are methods used to protect your data and make your code more secure. Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the convenience of the program, getter starts with the word “get” followed by the variable name."
},
{
"code": null,
"e": 25934,
"s": 25555,
"text": "While Setter sets or updates the value (mutators). It sets the value for any variable which is used in the programs of a class. and starts with the word “set” followed by the variable name. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type. In both getter and setter, the first letter of the variable should be capital."
},
{
"code": null,
"e": 25944,
"s": 25934,
"text": "Example 1"
},
{
"code": null,
"e": 25949,
"s": 25944,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Getter and Setter // Importing input output classesimport java.io.*; // Class 1// Helper classclass GetSet { // Member variable of this class private String name; // Method 1 - Getter public String getName() { return name; } // Method 2 - Setter public void setName(String N) { // This keyword refers to current instance itself this.name = N; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of class 1 in main() method GetSet obj = new GetSet(); // Setting the name by calling setter method obj.setName(\"Geeks for Geeks\"); // Getting the name by calling geter method System.out.println(obj.getName()); }}",
"e": 26757,
"s": 25949,
"text": null
},
{
"code": null,
"e": 26773,
"s": 26757,
"text": "Geeks for Geeks"
},
{
"code": null,
"e": 27083,
"s": 26773,
"text": "Getter and Setter give you the convenience to enter the value of the variables of any data type as per accordance with the requirement of the code. Getters and setters let you manage how crucial variables in your code are accessed and altered. It can be seen as in the program been discussed below as follows:"
},
{
"code": null,
"e": 27093,
"s": 27083,
"text": "Example 2"
},
{
"code": null,
"e": 27098,
"s": 27093,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Getter and Setter // Importing input output classesimport java.io.*; class GetSet { // Member variable of this class private int num; // Method 1 - Setter public void setNumber(int number) { // Checking if number if between 1 to 10 exclusive if (number < 1 || number > 10) { throw new IllegalArgumentException(); } num = number; } // Method 2 - Getter public int getNumber() { return num; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { GetSet obj = new GetSet(); // Calling method 1 inside main() method obj.setNumber(5); // Printing the number as setted above System.out.println(obj.getNumber()); }}",
"e": 27901,
"s": 27098,
"text": null
},
{
"code": null,
"e": 27903,
"s": 27901,
"text": "5"
},
{
"code": null,
"e": 27923,
"s": 27903,
"text": "Output explanation:"
},
{
"code": null,
"e": 28166,
"s": 27923,
"text": "Here we can see that if we take a value greater than 10 then it shows an error, By using the setNumber() method, one can be sure the value of a number is always between 1 and 10. This is much better than updating the number variable directly."
},
{
"code": null,
"e": 28354,
"s": 28166,
"text": "Note: This could be avoided by making the number a private variable and utilizing the setNumber method. Using a getter method, on the other hand, is the sole way to read a number’s value."
},
{
"code": null,
"e": 28368,
"s": 28354,
"text": "mehtayash2001"
},
{
"code": null,
"e": 28385,
"s": 28368,
"text": "gulshankumarpal4"
},
{
"code": null,
"e": 28390,
"s": 28385,
"text": "Java"
},
{
"code": null,
"e": 28395,
"s": 28390,
"text": "Java"
},
{
"code": null,
"e": 28493,
"s": 28395,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28508,
"s": 28493,
"text": "Stream In Java"
},
{
"code": null,
"e": 28529,
"s": 28508,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28548,
"s": 28529,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28578,
"s": 28548,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28624,
"s": 28578,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28641,
"s": 28624,
"text": "Generics in Java"
},
{
"code": null,
"e": 28662,
"s": 28641,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28705,
"s": 28662,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28727,
"s": 28705,
"text": "PriorityQueue in Java"
}
] |
Default Values Assigned to Primitive Data Types in Java - GeeksforGeeks
|
29 Oct, 2021
Primitive data types are built-in data types in java and can be used directly without using any new keyword. As we know primitive data types are treated differently by java cause of which the wrapper class concept also comes into play. But here we will be entirely focussing on data types. So, in java, there are 8 primitive data types as shown in the table below with their corresponding sizes.
Now, here default values are values assigned by the compiler to the variables which are declared but not initialized or given a value. They are different according to the return type of data type which is shown below where default values assigned to variables of different primitive data types are given in the table. However, relying on such default values is not considered a good programming style.
Data Type
Default Values
Byte
0
Short
0
Int
0
Long
0
Float
0.0
Double
0.0
Boolean
false
Char
\u0000′ or null
Now as we know Initializing a variable means to give an initial value to a variable before using it. So, in order to use the default values first, declare the variable with data type and name (eg, int x, here int is the data type and x is the name of the variable), if you don’t declare the variable before using it, it would result in a compile-time error. Now to use the default value of the variable do not initialize it, i.e. do not assign a value to it.
Example 1
Java
// Java Program to Print Default Value Assigned// to Primitive Datatype // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Global class variable static int a; // Main driver method public static void main(String[] args) { // Trying to print the default value // assigned to variable System.out.println(a); }}
0
Output explanation:
Here ‘a‘ is a class member variable or you can say an instance variable and it will be initialized to its default value by the compiler.
Note: There would have been a problem if variable (‘a’) was not a class member as the compiler never assigns default values to an uninitialized local variable.
In this scenario, there will be an error pointing to variable ‘a‘ that variable ‘a‘ might not have been initialized yet. This is because here ‘a‘ is the main() method local variable and has to be initialized before being used. The compiler never assigns default values to an uninitialized local variable. If you haven’t initialized the variable where you have declared it, assign the variable a value before using it, or else it will result in a compile-time error.
It is as shown in the next example as shown below for a better understanding of the class variable.
Example 2
Java
// Java Program to Print Default Value Assigned// to Primitive Datatype // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring class member variable // (inside a local scope) int a; // Trying to printing the default value assigned System.out.println(a); }}
Output:
sweetyty
java-basics
Java-Data Types
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25249,
"s": 25221,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 25645,
"s": 25249,
"text": "Primitive data types are built-in data types in java and can be used directly without using any new keyword. As we know primitive data types are treated differently by java cause of which the wrapper class concept also comes into play. But here we will be entirely focussing on data types. So, in java, there are 8 primitive data types as shown in the table below with their corresponding sizes."
},
{
"code": null,
"e": 26047,
"s": 25645,
"text": "Now, here default values are values assigned by the compiler to the variables which are declared but not initialized or given a value. They are different according to the return type of data type which is shown below where default values assigned to variables of different primitive data types are given in the table. However, relying on such default values is not considered a good programming style."
},
{
"code": null,
"e": 26057,
"s": 26047,
"text": "Data Type"
},
{
"code": null,
"e": 26072,
"s": 26057,
"text": "Default Values"
},
{
"code": null,
"e": 26077,
"s": 26072,
"text": "Byte"
},
{
"code": null,
"e": 26079,
"s": 26077,
"text": "0"
},
{
"code": null,
"e": 26085,
"s": 26079,
"text": "Short"
},
{
"code": null,
"e": 26087,
"s": 26085,
"text": "0"
},
{
"code": null,
"e": 26091,
"s": 26087,
"text": "Int"
},
{
"code": null,
"e": 26093,
"s": 26091,
"text": "0"
},
{
"code": null,
"e": 26098,
"s": 26093,
"text": "Long"
},
{
"code": null,
"e": 26100,
"s": 26098,
"text": "0"
},
{
"code": null,
"e": 26106,
"s": 26100,
"text": "Float"
},
{
"code": null,
"e": 26110,
"s": 26106,
"text": "0.0"
},
{
"code": null,
"e": 26117,
"s": 26110,
"text": "Double"
},
{
"code": null,
"e": 26121,
"s": 26117,
"text": "0.0"
},
{
"code": null,
"e": 26129,
"s": 26121,
"text": "Boolean"
},
{
"code": null,
"e": 26135,
"s": 26129,
"text": "false"
},
{
"code": null,
"e": 26140,
"s": 26135,
"text": "Char"
},
{
"code": null,
"e": 26156,
"s": 26140,
"text": "\\u0000′ or null"
},
{
"code": null,
"e": 26615,
"s": 26156,
"text": "Now as we know Initializing a variable means to give an initial value to a variable before using it. So, in order to use the default values first, declare the variable with data type and name (eg, int x, here int is the data type and x is the name of the variable), if you don’t declare the variable before using it, it would result in a compile-time error. Now to use the default value of the variable do not initialize it, i.e. do not assign a value to it."
},
{
"code": null,
"e": 26625,
"s": 26615,
"text": "Example 1"
},
{
"code": null,
"e": 26630,
"s": 26625,
"text": "Java"
},
{
"code": "// Java Program to Print Default Value Assigned// to Primitive Datatype // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Global class variable static int a; // Main driver method public static void main(String[] args) { // Trying to print the default value // assigned to variable System.out.println(a); }}",
"e": 27019,
"s": 26630,
"text": null
},
{
"code": null,
"e": 27021,
"s": 27019,
"text": "0"
},
{
"code": null,
"e": 27041,
"s": 27021,
"text": "Output explanation:"
},
{
"code": null,
"e": 27178,
"s": 27041,
"text": "Here ‘a‘ is a class member variable or you can say an instance variable and it will be initialized to its default value by the compiler."
},
{
"code": null,
"e": 27338,
"s": 27178,
"text": "Note: There would have been a problem if variable (‘a’) was not a class member as the compiler never assigns default values to an uninitialized local variable."
},
{
"code": null,
"e": 27804,
"s": 27338,
"text": "In this scenario, there will be an error pointing to variable ‘a‘ that variable ‘a‘ might not have been initialized yet. This is because here ‘a‘ is the main() method local variable and has to be initialized before being used. The compiler never assigns default values to an uninitialized local variable. If you haven’t initialized the variable where you have declared it, assign the variable a value before using it, or else it will result in a compile-time error."
},
{
"code": null,
"e": 27904,
"s": 27804,
"text": "It is as shown in the next example as shown below for a better understanding of the class variable."
},
{
"code": null,
"e": 27914,
"s": 27904,
"text": "Example 2"
},
{
"code": null,
"e": 27919,
"s": 27914,
"text": "Java"
},
{
"code": "// Java Program to Print Default Value Assigned// to Primitive Datatype // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring class member variable // (inside a local scope) int a; // Trying to printing the default value assigned System.out.println(a); }}",
"e": 28281,
"s": 27919,
"text": null
},
{
"code": null,
"e": 28289,
"s": 28281,
"text": "Output:"
},
{
"code": null,
"e": 28298,
"s": 28289,
"text": "sweetyty"
},
{
"code": null,
"e": 28310,
"s": 28298,
"text": "java-basics"
},
{
"code": null,
"e": 28326,
"s": 28310,
"text": "Java-Data Types"
},
{
"code": null,
"e": 28331,
"s": 28326,
"text": "Java"
},
{
"code": null,
"e": 28336,
"s": 28331,
"text": "Java"
},
{
"code": null,
"e": 28434,
"s": 28336,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28449,
"s": 28434,
"text": "Stream In Java"
},
{
"code": null,
"e": 28470,
"s": 28449,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28489,
"s": 28470,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28519,
"s": 28489,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28565,
"s": 28519,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28582,
"s": 28565,
"text": "Generics in Java"
},
{
"code": null,
"e": 28603,
"s": 28582,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28646,
"s": 28603,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28682,
"s": 28646,
"text": "Internal Working of HashMap in Java"
}
] |
HTML | DOM Table rows Collection - GeeksforGeeks
|
19 Feb, 2019
The Table rows collection is used for returning the collection of all the <tr> elements in a table. The sequence of the <tr> elements are sorted in the same way as their position in the source code.
Syntax
tableObject.rows
Properties
length : It is used to return the number of <tr> elements in the collection.
Methods
[index] : It is used for returning the <tr> element from the collection with a specified index.
item(index) : It is also used for returning the <tr> element from the collection with a specified index.
namedItem(id) : It is also used for returning the <tr> element from the collection with a specified id.
Below program illustrates the Table rows collection :Example: Finding out the number of rows in a table.
<!DOCTYPE html><html> <head> <title>Table rows Collection in HTML </title> <style> table, td { border: 1px solid green; } h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Table rows Collection</h2> <p>To return the number of rows in the table, double-click the "Return Count" button.</p> <table id="Courses" align="center"> <caption>Courses by Geeksforgeeks</caption> <tr> <td>Java</td> <td>Fork Java</td> </tr> <tr> <td>Python</td> <td>Fork Python</td> </tr> <tr> <td>Placements</td> <td>Sudo Placement</td> </tr> </table> <br> <button ondblclick="tr()">Return Count</button> <p id="test"></p> <script> function tr() { // number of rows. var c = document.getElementById( "Courses").rows.length; document.getElementById("test").innerHTML = c + " Rows are present in the table."; } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Supported Browsers:
Apple Safari
Internet Explorer
Firefox
Google Chrome
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26139,
"s": 26111,
"text": "\n19 Feb, 2019"
},
{
"code": null,
"e": 26338,
"s": 26139,
"text": "The Table rows collection is used for returning the collection of all the <tr> elements in a table. The sequence of the <tr> elements are sorted in the same way as their position in the source code."
},
{
"code": null,
"e": 26345,
"s": 26338,
"text": "Syntax"
},
{
"code": null,
"e": 26362,
"s": 26345,
"text": "tableObject.rows"
},
{
"code": null,
"e": 26373,
"s": 26362,
"text": "Properties"
},
{
"code": null,
"e": 26450,
"s": 26373,
"text": "length : It is used to return the number of <tr> elements in the collection."
},
{
"code": null,
"e": 26458,
"s": 26450,
"text": "Methods"
},
{
"code": null,
"e": 26554,
"s": 26458,
"text": "[index] : It is used for returning the <tr> element from the collection with a specified index."
},
{
"code": null,
"e": 26659,
"s": 26554,
"text": "item(index) : It is also used for returning the <tr> element from the collection with a specified index."
},
{
"code": null,
"e": 26763,
"s": 26659,
"text": "namedItem(id) : It is also used for returning the <tr> element from the collection with a specified id."
},
{
"code": null,
"e": 26868,
"s": 26763,
"text": "Below program illustrates the Table rows collection :Example: Finding out the number of rows in a table."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Table rows Collection in HTML </title> <style> table, td { border: 1px solid green; } h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Table rows Collection</h2> <p>To return the number of rows in the table, double-click the \"Return Count\" button.</p> <table id=\"Courses\" align=\"center\"> <caption>Courses by Geeksforgeeks</caption> <tr> <td>Java</td> <td>Fork Java</td> </tr> <tr> <td>Python</td> <td>Fork Python</td> </tr> <tr> <td>Placements</td> <td>Sudo Placement</td> </tr> </table> <br> <button ondblclick=\"tr()\">Return Count</button> <p id=\"test\"></p> <script> function tr() { // number of rows. var c = document.getElementById( \"Courses\").rows.length; document.getElementById(\"test\").innerHTML = c + \" Rows are present in the table.\"; } </script> </body> </html>",
"e": 28153,
"s": 26868,
"text": null
},
{
"code": null,
"e": 28161,
"s": 28153,
"text": "Output:"
},
{
"code": null,
"e": 28189,
"s": 28161,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 28216,
"s": 28189,
"text": "After clicking the button:"
},
{
"code": null,
"e": 28236,
"s": 28216,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 28249,
"s": 28236,
"text": "Apple Safari"
},
{
"code": null,
"e": 28267,
"s": 28249,
"text": "Internet Explorer"
},
{
"code": null,
"e": 28275,
"s": 28267,
"text": "Firefox"
},
{
"code": null,
"e": 28289,
"s": 28275,
"text": "Google Chrome"
},
{
"code": null,
"e": 28295,
"s": 28289,
"text": "Opera"
},
{
"code": null,
"e": 28432,
"s": 28295,
"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": 28441,
"s": 28432,
"text": "HTML-DOM"
},
{
"code": null,
"e": 28446,
"s": 28441,
"text": "HTML"
},
{
"code": null,
"e": 28463,
"s": 28446,
"text": "Web Technologies"
},
{
"code": null,
"e": 28468,
"s": 28463,
"text": "HTML"
},
{
"code": null,
"e": 28566,
"s": 28468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28590,
"s": 28566,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28631,
"s": 28590,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 28668,
"s": 28631,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28697,
"s": 28668,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28717,
"s": 28697,
"text": "Angular File Upload"
},
{
"code": null,
"e": 28757,
"s": 28717,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28790,
"s": 28757,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28835,
"s": 28790,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28878,
"s": 28835,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
preventDefault() Event Method - GeeksforGeeks
|
18 Jan, 2019
The preventDefault() method is used to prevent the browser from executing the default action of the selected element. It can prevent the user from processing the request by clicking the link.Syntax:
event.preventDefault()
Parameters: It does not accept any parameter.The event is used to denote the event or action by the user in the response of which the method works.
<html> <head> <title>GEEKSFORGEEKS ARTICLE<title/> <!-- INCLUDE THE JQUERY CDN --> <script src="https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("a").click(function(event) { event.preventDefault(); alert("prevented"); }); }); </script> </head> <body> <p>Click the link:</p> <a href="https://www.google.com">GOOGLE</a> </body></html>
Output:It shows the output like given below-Code #2:This code will prevent the browser from redirecting the page to another PHP file.
<html> <head> <title>GEEKSFORGEEKS ARTICLE<title/> <script src="https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#submit").click(function(event) { event.preventDefault(); alert("ACTION IS PREVENTED"); }); }); </script> </head> <body> <form action="submit.php"> <input type="text" placeholder="enter username"> <input id="submit" type="submit" name="submit"> </form> </body></html>
Output:It shows the output like given below-
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
How to Dynamically Add/Remove Table Rows using jQuery ?
|
[
{
"code": null,
"e": 26354,
"s": 26326,
"text": "\n18 Jan, 2019"
},
{
"code": null,
"e": 26553,
"s": 26354,
"text": "The preventDefault() method is used to prevent the browser from executing the default action of the selected element. It can prevent the user from processing the request by clicking the link.Syntax:"
},
{
"code": null,
"e": 26576,
"s": 26553,
"text": "event.preventDefault()"
},
{
"code": null,
"e": 26724,
"s": 26576,
"text": "Parameters: It does not accept any parameter.The event is used to denote the event or action by the user in the response of which the method works."
},
{
"code": "<html> <head> <title>GEEKSFORGEEKS ARTICLE<title/> <!-- INCLUDE THE JQUERY CDN --> <script src=\"https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js\"></script> <script type=\"text/javascript\"> $(document).ready(function() { $(\"a\").click(function(event) { event.preventDefault(); alert(\"prevented\"); }); }); </script> </head> <body> <p>Click the link:</p> <a href=\"https://www.google.com\">GOOGLE</a> </body></html>",
"e": 27391,
"s": 26724,
"text": null
},
{
"code": null,
"e": 27525,
"s": 27391,
"text": "Output:It shows the output like given below-Code #2:This code will prevent the browser from redirecting the page to another PHP file."
},
{
"code": "<html> <head> <title>GEEKSFORGEEKS ARTICLE<title/> <script src=\"https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js\"></script> <script type=\"text/javascript\"> $(document).ready(function() { $(\"#submit\").click(function(event) { event.preventDefault(); alert(\"ACTION IS PREVENTED\"); }); }); </script> </head> <body> <form action=\"submit.php\"> <input type=\"text\" placeholder=\"enter username\"> <input id=\"submit\" type=\"submit\" name=\"submit\"> </form> </body></html>",
"e": 28233,
"s": 27525,
"text": null
},
{
"code": null,
"e": 28278,
"s": 28233,
"text": "Output:It shows the output like given below-"
},
{
"code": null,
"e": 28289,
"s": 28278,
"text": "JavaScript"
},
{
"code": null,
"e": 28296,
"s": 28289,
"text": "JQuery"
},
{
"code": null,
"e": 28394,
"s": 28296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28434,
"s": 28394,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28479,
"s": 28434,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28540,
"s": 28479,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28612,
"s": 28540,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28664,
"s": 28612,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28710,
"s": 28664,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 28739,
"s": 28710,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28816,
"s": 28739,
"text": "How to change the background color after clicking the button in JavaScript ?"
},
{
"code": null,
"e": 28890,
"s": 28816,
"text": "How to fetch data from JSON file and display in HTML table using jQuery ?"
}
] |
Java program to find the 3rd largest number in an array
|
To find the third largest number of the given array, first of all, sort the array.
Compare the first two elements of the array
If the first element is greater than the second swap them.
Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.
Repeat this till the end of the array.
After sorting an array print the third element from the end of the array.
Live Demo
public class ThirdLargestNumberInAnArray {
public static void main(String args[]){
int temp, size;
int array[] = {10, 20, 25, 63, 96, 57};
size = array.length;
for(int i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(array[i]>array[j]){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("Third largest number is:: "+array[size-3]);
}
}
Third largest number is:: 57
You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the third element from the end of the array.
Live Demo
import java.util.Arrays;
public class LargestNumberSample {
public static void main(String args[]){
int array[] = {10, 20, 25, 63, 96, 57};
int size = array.length;
Arrays.sort(array);
System.out.println("sorted Array ::"+Arrays.toString(array));
int max = array[size-3];
System.out.println("3rd largest element is :"+max);
}
}
sorted Array ::[10, 20, 25, 57, 63, 96]
3rd largest element is :57
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To find the third largest number of the given array, first of all, sort the array."
},
{
"code": null,
"e": 1189,
"s": 1145,
"text": "Compare the first two elements of the array"
},
{
"code": null,
"e": 1248,
"s": 1189,
"text": "If the first element is greater than the second swap them."
},
{
"code": null,
"e": 1340,
"s": 1248,
"text": "Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them."
},
{
"code": null,
"e": 1379,
"s": 1340,
"text": "Repeat this till the end of the array."
},
{
"code": null,
"e": 1453,
"s": 1379,
"text": "After sorting an array print the third element from the end of the array."
},
{
"code": null,
"e": 1463,
"s": 1453,
"text": "Live Demo"
},
{
"code": null,
"e": 1930,
"s": 1463,
"text": "public class ThirdLargestNumberInAnArray {\n public static void main(String args[]){\n int temp, size;\n int array[] = {10, 20, 25, 63, 96, 57};\n size = array.length;\n \n for(int i = 0; i<size; i++ ){\n for(int j = i+1; j<size; j++){\n if(array[i]>array[j]){\n temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n }\n }\n System.out.println(\"Third largest number is:: \"+array[size-3]);\n }\n}"
},
{
"code": null,
"e": 1959,
"s": 1930,
"text": "Third largest number is:: 57"
},
{
"code": null,
"e": 2118,
"s": 1959,
"text": "You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the third element from the end of the array."
},
{
"code": null,
"e": 2128,
"s": 2118,
"text": "Live Demo"
},
{
"code": null,
"e": 2498,
"s": 2128,
"text": "import java.util.Arrays;\npublic class LargestNumberSample {\n public static void main(String args[]){\n int array[] = {10, 20, 25, 63, 96, 57};\n int size = array.length;\n Arrays.sort(array);\n System.out.println(\"sorted Array ::\"+Arrays.toString(array));\n int max = array[size-3];\n System.out.println(\"3rd largest element is :\"+max);\n }\n}"
},
{
"code": null,
"e": 2565,
"s": 2498,
"text": "sorted Array ::[10, 20, 25, 57, 63, 96]\n3rd largest element is :57"
}
] |
Why do we need to change the delimiter for creating a trigger?
|
As we know that in MySQL we use the delimiter semicolon (;) to end each statement. The semicolon is the by default delimiter in MySQL. We need to change the delimiter, while creating a trigger, to tell MySQL that this is not the end of our trigger statement because we can use multiple statements in the trigger. We can change the delimiter temporarily by DELIMITER // statement to change the delimiter from Semicolon (;) to two back-slash (//). After this MySQL would know that the triggering statement only ends when it encounters a two back-slash (//). Following is an example of changing the delimiter −
mysql> DELIMITER //
Now to end the MySQL statements, the delimiter would be a two back-slash (//). And to change it again to a semicolon(;), we can use the following statement −
mysql> DELIMITER ;
Remember that there must be a space between the keyword DELIMITER and the symbol which we want to use as a delimiter.
|
[
{
"code": null,
"e": 1670,
"s": 1062,
"text": "As we know that in MySQL we use the delimiter semicolon (;) to end each statement. The semicolon is the by default delimiter in MySQL. We need to change the delimiter, while creating a trigger, to tell MySQL that this is not the end of our trigger statement because we can use multiple statements in the trigger. We can change the delimiter temporarily by DELIMITER // statement to change the delimiter from Semicolon (;) to two back-slash (//). After this MySQL would know that the triggering statement only ends when it encounters a two back-slash (//). Following is an example of changing the delimiter −"
},
{
"code": null,
"e": 1690,
"s": 1670,
"text": "mysql> DELIMITER //"
},
{
"code": null,
"e": 1848,
"s": 1690,
"text": "Now to end the MySQL statements, the delimiter would be a two back-slash (//). And to change it again to a semicolon(;), we can use the following statement −"
},
{
"code": null,
"e": 1867,
"s": 1848,
"text": "mysql> DELIMITER ;"
},
{
"code": null,
"e": 1985,
"s": 1867,
"text": "Remember that there must be a space between the keyword DELIMITER and the symbol which we want to use as a delimiter."
}
] |
Python - Chart Styling
|
The charts created in python can have further styling by using some appropriate methods from the libraries used for charting. In this lesson we will see
the implementation of Annotation, legends and chart background. We will continue to use the code from the last chapter and modify it to add these styles to the chart.
Many times, we need to annotate the chart by highlighting the specific locations of the chart. In the below example we indicate the sharp change in values in the chart by adding annotations at those points.
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0,10)
y = x ^ 2
z = x ^ 3
t = x ^ 4
# Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
plt.plot(x,y)
#Annotate
plt.annotate(xy=[2,1], s='Second Entry')
plt.annotate(xy=[4,6], s='Third Entry')
Its output is as follows −
We sometimes need a chart with multiple lines being plotted. Use of legend represents the meaning associated with each line. In the below chart we have 3 lines with appropriate legends.
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0,10)
y = x ^ 2
z = x ^ 3
t = x ^ 4
# Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
plt.plot(x,y)
#Annotate
plt.annotate(xy=[2,1], s='Second Entry')
plt.annotate(xy=[4,6], s='Third Entry')
# Adding Legends
plt.plot(x,z)
plt.plot(x,t)
plt.legend(['Race1', 'Race2','Race3'], loc=4)
Its output is as follows −
We can modify the presentation style of the chart by using different methods from the style package.
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0,10)
y = x ^ 2
z = x ^ 3
t = x ^ 4
# Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
plt.plot(x,y)
#Annotate
plt.annotate(xy=[2,1], s='Second Entry')
plt.annotate(xy=[4,6], s='Third Entry')
# Adding Legends
plt.plot(x,z)
plt.plot(x,t)
plt.legend(['Race1', 'Race2','Race3'], loc=4)
#Style the background
plt.style.use('fast')
plt.plot(x,z)
Its output is as follows −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2849,
"s": 2529,
"text": "The charts created in python can have further styling by using some appropriate methods from the libraries used for charting. In this lesson we will see\nthe implementation of Annotation, legends and chart background. We will continue to use the code from the last chapter and modify it to add these styles to the chart."
},
{
"code": null,
"e": 3056,
"s": 2849,
"text": "Many times, we need to annotate the chart by highlighting the specific locations of the chart. In the below example we indicate the sharp change in values in the chart by adding annotations at those points."
},
{
"code": null,
"e": 3378,
"s": 3056,
"text": "import numpy as np \nfrom matplotlib import pyplot as plt \n\nx = np.arange(0,10) \ny = x ^ 2 \nz = x ^ 3\nt = x ^ 4 \n# Labeling the Axes and Title\nplt.title(\"Graph Drawing\") \nplt.xlabel(\"Time\") \nplt.ylabel(\"Distance\") \nplt.plot(x,y)\n\n#Annotate\nplt.annotate(xy=[2,1], s='Second Entry') \nplt.annotate(xy=[4,6], s='Third Entry') "
},
{
"code": null,
"e": 3405,
"s": 3378,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3591,
"s": 3405,
"text": "We sometimes need a chart with multiple lines being plotted. Use of legend represents the meaning associated with each line. In the below chart we have 3 lines with appropriate legends."
},
{
"code": null,
"e": 4005,
"s": 3591,
"text": "import numpy as np \nfrom matplotlib import pyplot as plt \n\nx = np.arange(0,10) \ny = x ^ 2 \nz = x ^ 3\nt = x ^ 4 \n# Labeling the Axes and Title\nplt.title(\"Graph Drawing\") \nplt.xlabel(\"Time\") \nplt.ylabel(\"Distance\") \nplt.plot(x,y)\n\n#Annotate\nplt.annotate(xy=[2,1], s='Second Entry') \nplt.annotate(xy=[4,6], s='Third Entry') \n# Adding Legends\nplt.plot(x,z)\nplt.plot(x,t)\nplt.legend(['Race1', 'Race2','Race3'], loc=4) "
},
{
"code": null,
"e": 4032,
"s": 4005,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4133,
"s": 4032,
"text": "We can modify the presentation style of the chart by using different methods from the style package."
},
{
"code": null,
"e": 4606,
"s": 4133,
"text": "import numpy as np \nfrom matplotlib import pyplot as plt \n\nx = np.arange(0,10) \ny = x ^ 2 \nz = x ^ 3\nt = x ^ 4 \n# Labeling the Axes and Title\nplt.title(\"Graph Drawing\") \nplt.xlabel(\"Time\") \nplt.ylabel(\"Distance\") \nplt.plot(x,y)\n\n#Annotate\nplt.annotate(xy=[2,1], s='Second Entry') \nplt.annotate(xy=[4,6], s='Third Entry') \n# Adding Legends\nplt.plot(x,z)\nplt.plot(x,t)\nplt.legend(['Race1', 'Race2','Race3'], loc=4) \n\n#Style the background\nplt.style.use('fast')\nplt.plot(x,z)"
},
{
"code": null,
"e": 4633,
"s": 4606,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4670,
"s": 4633,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4686,
"s": 4670,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4719,
"s": 4686,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4738,
"s": 4719,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4773,
"s": 4738,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4795,
"s": 4773,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4829,
"s": 4795,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4857,
"s": 4829,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4892,
"s": 4857,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4906,
"s": 4892,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4939,
"s": 4906,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4956,
"s": 4939,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4963,
"s": 4956,
"text": " Print"
},
{
"code": null,
"e": 4974,
"s": 4963,
"text": " Add Notes"
}
] |
Creating Photo Mosaics Using Python | by Cody Glickman, PhD | Towards Data Science
|
Code updated December 8th 2021
Image_Tester.py no longer necessary
Thanks to Dan Black, Johannes la Pourte, and Jordan Maurice edits and comments
Photo mosaics are an image composed of many smaller images. The smaller images possess a similar color and brightness as a position in the original image making the original image visible from a distance similar to a Claude Monet painting. There exist many online tools (paid software) to create photo mosaics, however, I decided to implement a photo mosaic creator in python3 and share it with the community. My wife is creating a new lifestyle blog and I thought what better way to help her project than by creating a beautiful image from our wedding a little over a year ago. The source code is freely available on at the Data Dolittle GitHub. Let’s begin by setting up the environment necessary to run the scripts.
The photo mosaic program requires Pillow and numpy to process the images and matrix manipulation respectively. Follow the instructions from the text hyperlinks above to install both packages.
Do you have an image in mind that you would like to make a photo mosaic? Great! How about the images to comprise the smaller images? The more background images, the better the mosaic will appear. If you want to download a lot of images quickly I recommend using a chrome extension to download photos directly from google images. There exist other bulk image downloaders in Firefox. Place all the background images in the same folder. Keep your foreground image outside this folder. All your photos should be 3 channel images like jpeg or jpg. Be sure to run the Image_Tester.py script to check for 3 channel images in your background images folder. Remove any .png, .tiffs, or .gifs prior to creating a photo mosaic. The script will move images into a folder titled unusable images.
python Image_Tester.py --images [Background_Images_Folder]
Now that you have installed the necessary tools and have the photos, you are ready to create your photo mosaic. The required inputs include the target foreground image, the background images folder, and the size of the grid with two integers separated by a space. An optional parameter is the output flag to save the mosaic image as any name your desire.
python Mosaic_Creator.py --target [Input_Image] --images [Background_Images_Folder] --grid 50 50 --output [Output_Name]
This section contains the details of the creation engine so for those bored by pseudo-code scroll to the bottom to see the final product of my demo. The full code is available on GitHub.
The Image Directory: The background images are loaded into memory, reshaped, and processed. The processing involves acquiring the average red, blue, and green channels in the image. This average is what is used to place the background images into the grid.
The Target Image: The target image is broken into a grid defined by the user input. The cell dimensions are a product of the original image size and the number of splits due to the grid size. The average red, green, and blue values of each cell is calculated. The best match between the cell average and the background image average is used to place a background image into the cell. All cells are filled with background images and the resulting mosaic is saved to a file.
After running the script using our wedding photos, the following mosaic was created.
The mosaic looks like the original, only darker. Our wedding occurred at sunset, so many of the photos have dark backgrounds leading to a darkening of the mosaic image. Increasing the number of photos will provide more detail and having brightened photos will increase the overall brightness. This article detailed the tools and process to create a photo mosaic in python using the scripts available on GitHub. You are able to create your own photo mosaics using anything! My name is Cody Glickman and I can be found on LinkedIn. Be sure to check out some other articles below.
|
[
{
"code": null,
"e": 203,
"s": 172,
"text": "Code updated December 8th 2021"
},
{
"code": null,
"e": 239,
"s": 203,
"text": "Image_Tester.py no longer necessary"
},
{
"code": null,
"e": 318,
"s": 239,
"text": "Thanks to Dan Black, Johannes la Pourte, and Jordan Maurice edits and comments"
},
{
"code": null,
"e": 1037,
"s": 318,
"text": "Photo mosaics are an image composed of many smaller images. The smaller images possess a similar color and brightness as a position in the original image making the original image visible from a distance similar to a Claude Monet painting. There exist many online tools (paid software) to create photo mosaics, however, I decided to implement a photo mosaic creator in python3 and share it with the community. My wife is creating a new lifestyle blog and I thought what better way to help her project than by creating a beautiful image from our wedding a little over a year ago. The source code is freely available on at the Data Dolittle GitHub. Let’s begin by setting up the environment necessary to run the scripts."
},
{
"code": null,
"e": 1229,
"s": 1037,
"text": "The photo mosaic program requires Pillow and numpy to process the images and matrix manipulation respectively. Follow the instructions from the text hyperlinks above to install both packages."
},
{
"code": null,
"e": 2012,
"s": 1229,
"text": "Do you have an image in mind that you would like to make a photo mosaic? Great! How about the images to comprise the smaller images? The more background images, the better the mosaic will appear. If you want to download a lot of images quickly I recommend using a chrome extension to download photos directly from google images. There exist other bulk image downloaders in Firefox. Place all the background images in the same folder. Keep your foreground image outside this folder. All your photos should be 3 channel images like jpeg or jpg. Be sure to run the Image_Tester.py script to check for 3 channel images in your background images folder. Remove any .png, .tiffs, or .gifs prior to creating a photo mosaic. The script will move images into a folder titled unusable images."
},
{
"code": null,
"e": 2071,
"s": 2012,
"text": "python Image_Tester.py --images [Background_Images_Folder]"
},
{
"code": null,
"e": 2426,
"s": 2071,
"text": "Now that you have installed the necessary tools and have the photos, you are ready to create your photo mosaic. The required inputs include the target foreground image, the background images folder, and the size of the grid with two integers separated by a space. An optional parameter is the output flag to save the mosaic image as any name your desire."
},
{
"code": null,
"e": 2546,
"s": 2426,
"text": "python Mosaic_Creator.py --target [Input_Image] --images [Background_Images_Folder] --grid 50 50 --output [Output_Name]"
},
{
"code": null,
"e": 2733,
"s": 2546,
"text": "This section contains the details of the creation engine so for those bored by pseudo-code scroll to the bottom to see the final product of my demo. The full code is available on GitHub."
},
{
"code": null,
"e": 2990,
"s": 2733,
"text": "The Image Directory: The background images are loaded into memory, reshaped, and processed. The processing involves acquiring the average red, blue, and green channels in the image. This average is what is used to place the background images into the grid."
},
{
"code": null,
"e": 3463,
"s": 2990,
"text": "The Target Image: The target image is broken into a grid defined by the user input. The cell dimensions are a product of the original image size and the number of splits due to the grid size. The average red, green, and blue values of each cell is calculated. The best match between the cell average and the background image average is used to place a background image into the cell. All cells are filled with background images and the resulting mosaic is saved to a file."
},
{
"code": null,
"e": 3548,
"s": 3463,
"text": "After running the script using our wedding photos, the following mosaic was created."
}
] |
Stop using SMOTE to handle all your Imbalanced Data | by Satyam Kumar | Towards Data Science
|
In classification tasks, one may encounter a situation where the target class label is not equally distributed. Such a dataset can be termed Imbalanced data. Imbalance in data can be a blocker to train a data science model. In case of imbalance class problems, the model is trained mainly on the majority class and the model becomes biased towards the majority class prediction.
Hence handling of imbalance class is essential before proceeding to the modeling pipeline. There are various class balancing techniques that solve the problem of class imbalance by either generating a new sampling of the minority class or removing some majority class samples. Handling class balancing techniques can be broadly classified into two categories:
Over-sampling techniques: Oversampling techniques refer to create artificial minority class points. Some oversampling techniques are Random Over Sampling, ADASYN, SMOTE, etc.
Under-sampling techniques: Undersampling techniques refer to remove majority class points. Some oversampling techniques are ENN, Random Under Sampling, TomekLinks, etc.
Read the below-mentioned article to know 7 oversampling techniques to handle the problem of class imbalance.
towardsdatascience.com
A disadvantage of using undersampling techniques is that we are losing out a lot of majority class data points in order to balance the class. Oversampling techniques cover this disadvantage but creating multiple samples within the minority class may result in overfitting of the model.
SMOTE is one of the popular and famous oversampling techniques among the data scientist community that create artificial minority data points within the cluster of minority class samples. The idea is to combine the oversampling and undersampling techniques and together it may be considered as another sampling technique to handle imbalanced class data.
SMOTE is one of the famous oversampling techniques and is very effective in handling class imbalance. The idea is to combine SMOTE with some undersampling techniques (ENN, Tomek) to increase the effectiveness of handling the imbalanced class.
Two examples of the combination of SMOTE and undersampling techniques are:
SMOTE with ENN
SMOTE with Tomek
Before proceeding to the combination of SMOTE with undersampling techniques, let's discuss what is SMOTE and how does it work under the hood.
SMOTE stands for Synthetic Minority Oversampling Technique, is an oversampling technique that creates synthetic minority class data points to balance the dataset.
SMOTE works using a k-nearest neighbor algorithm to create synthetic data points. The steps of SMOTE algorithm is:
Identify the minority class vector.Decide the number of nearest numbers (k), to consider.Compute a line between the minority data points and any of its neighbors and place a synthetic point.Repeat step 3 for all minority data points and their k neighbors, till the data is balanced.
Identify the minority class vector.
Decide the number of nearest numbers (k), to consider.
Compute a line between the minority data points and any of its neighbors and place a synthetic point.
Repeat step 3 for all minority data points and their k neighbors, till the data is balanced.
The combination of SMOTE and some undersampling techniques are proven effective and together can be considered as a new sampling technique.
Tomek Links is an undersampling heuristic approach that identifies all the pairs of data points that are nearest to each other but belong to different classes, and these pairs (suppose a and b) are termed as Tomek links. Tomek Links follows these conditions:
a and b are nearest neighbors of each other
a and b belong to two different classes
Heuristically, these Tomek links points (a, b) are present on the boundary of separation of the two classes. So removing the majority class of Tomek links points increases the class separation, and also reduces the number of majority class samples along the boundary of the majority cluster.
SMOTE is an oversampling technique and creates new minority class synthetic samples, and Tomek Links is an undersampling technique.
For an imbalanced dataset, first SMOTE is applied to create new synthetic minority samples to get a balanced distribution. Further, Tomek Links is used in removing the samples close to the boundary of the two classes, to increase the separation between the two classes.
The Imblearn package comes with the implementation of the combination of SMOTE and Tomek Links.
You can install the library from PyPl using pip install imblearn
from imblearn.combine import SMOTETomeksmt = SMOTETomek(random_state=42)X, y = smt.fit_sample(X, y)
ENN (Edited Nearest Neighbour) is an undersampling technique that removes the instances of majority class on the border or boundary whose predictions made by the KNN algorithm are different from the other majority class points.
Similar to SMOTETomek, first SMOTE is applied to create synthetic data points of minority class samples, then using ENN the data points on the border or boundary are removed to increase the separation of the two classes.
A combination of SMOTE with ENN algorithm also comes in the imblearn package.
from imblearn.combine import SMOTEENNsmt = SMOTEENN(random_state=42)X, y = smt.fit_sample(X, y)
The combination of SMOTE and undersampling techniques (ENN and Tomek Links) are proven effective. SMOTE is basically used to create synthetic class samples of minority class to balance the distribution then undersampling technique (ENN or Tomek Links) is used for cleaning irrelevant points in the boundary of the two classes to increase the separation between the two classes.
Imblean package comes with the implementation of SMOTETomek and SMOTEENN. There is a thumb rule about which works the best. One can write manual Python code to combine one oversampling technique proceeded by an undersampling technique to get the best results.
You can also read the below-mentioned article to know 7 oversampling techniques to handle class imbalance.
towardsdatascience.com
[1] Imbalance Learn API documentation: http://glemaitre.github.io/imbalanced-learn/api.html
Thank You for Reading
|
[
{
"code": null,
"e": 550,
"s": 171,
"text": "In classification tasks, one may encounter a situation where the target class label is not equally distributed. Such a dataset can be termed Imbalanced data. Imbalance in data can be a blocker to train a data science model. In case of imbalance class problems, the model is trained mainly on the majority class and the model becomes biased towards the majority class prediction."
},
{
"code": null,
"e": 910,
"s": 550,
"text": "Hence handling of imbalance class is essential before proceeding to the modeling pipeline. There are various class balancing techniques that solve the problem of class imbalance by either generating a new sampling of the minority class or removing some majority class samples. Handling class balancing techniques can be broadly classified into two categories:"
},
{
"code": null,
"e": 1085,
"s": 910,
"text": "Over-sampling techniques: Oversampling techniques refer to create artificial minority class points. Some oversampling techniques are Random Over Sampling, ADASYN, SMOTE, etc."
},
{
"code": null,
"e": 1254,
"s": 1085,
"text": "Under-sampling techniques: Undersampling techniques refer to remove majority class points. Some oversampling techniques are ENN, Random Under Sampling, TomekLinks, etc."
},
{
"code": null,
"e": 1363,
"s": 1254,
"text": "Read the below-mentioned article to know 7 oversampling techniques to handle the problem of class imbalance."
},
{
"code": null,
"e": 1386,
"s": 1363,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1672,
"s": 1386,
"text": "A disadvantage of using undersampling techniques is that we are losing out a lot of majority class data points in order to balance the class. Oversampling techniques cover this disadvantage but creating multiple samples within the minority class may result in overfitting of the model."
},
{
"code": null,
"e": 2026,
"s": 1672,
"text": "SMOTE is one of the popular and famous oversampling techniques among the data scientist community that create artificial minority data points within the cluster of minority class samples. The idea is to combine the oversampling and undersampling techniques and together it may be considered as another sampling technique to handle imbalanced class data."
},
{
"code": null,
"e": 2269,
"s": 2026,
"text": "SMOTE is one of the famous oversampling techniques and is very effective in handling class imbalance. The idea is to combine SMOTE with some undersampling techniques (ENN, Tomek) to increase the effectiveness of handling the imbalanced class."
},
{
"code": null,
"e": 2344,
"s": 2269,
"text": "Two examples of the combination of SMOTE and undersampling techniques are:"
},
{
"code": null,
"e": 2359,
"s": 2344,
"text": "SMOTE with ENN"
},
{
"code": null,
"e": 2376,
"s": 2359,
"text": "SMOTE with Tomek"
},
{
"code": null,
"e": 2518,
"s": 2376,
"text": "Before proceeding to the combination of SMOTE with undersampling techniques, let's discuss what is SMOTE and how does it work under the hood."
},
{
"code": null,
"e": 2681,
"s": 2518,
"text": "SMOTE stands for Synthetic Minority Oversampling Technique, is an oversampling technique that creates synthetic minority class data points to balance the dataset."
},
{
"code": null,
"e": 2796,
"s": 2681,
"text": "SMOTE works using a k-nearest neighbor algorithm to create synthetic data points. The steps of SMOTE algorithm is:"
},
{
"code": null,
"e": 3079,
"s": 2796,
"text": "Identify the minority class vector.Decide the number of nearest numbers (k), to consider.Compute a line between the minority data points and any of its neighbors and place a synthetic point.Repeat step 3 for all minority data points and their k neighbors, till the data is balanced."
},
{
"code": null,
"e": 3115,
"s": 3079,
"text": "Identify the minority class vector."
},
{
"code": null,
"e": 3170,
"s": 3115,
"text": "Decide the number of nearest numbers (k), to consider."
},
{
"code": null,
"e": 3272,
"s": 3170,
"text": "Compute a line between the minority data points and any of its neighbors and place a synthetic point."
},
{
"code": null,
"e": 3365,
"s": 3272,
"text": "Repeat step 3 for all minority data points and their k neighbors, till the data is balanced."
},
{
"code": null,
"e": 3505,
"s": 3365,
"text": "The combination of SMOTE and some undersampling techniques are proven effective and together can be considered as a new sampling technique."
},
{
"code": null,
"e": 3764,
"s": 3505,
"text": "Tomek Links is an undersampling heuristic approach that identifies all the pairs of data points that are nearest to each other but belong to different classes, and these pairs (suppose a and b) are termed as Tomek links. Tomek Links follows these conditions:"
},
{
"code": null,
"e": 3808,
"s": 3764,
"text": "a and b are nearest neighbors of each other"
},
{
"code": null,
"e": 3848,
"s": 3808,
"text": "a and b belong to two different classes"
},
{
"code": null,
"e": 4140,
"s": 3848,
"text": "Heuristically, these Tomek links points (a, b) are present on the boundary of separation of the two classes. So removing the majority class of Tomek links points increases the class separation, and also reduces the number of majority class samples along the boundary of the majority cluster."
},
{
"code": null,
"e": 4272,
"s": 4140,
"text": "SMOTE is an oversampling technique and creates new minority class synthetic samples, and Tomek Links is an undersampling technique."
},
{
"code": null,
"e": 4542,
"s": 4272,
"text": "For an imbalanced dataset, first SMOTE is applied to create new synthetic minority samples to get a balanced distribution. Further, Tomek Links is used in removing the samples close to the boundary of the two classes, to increase the separation between the two classes."
},
{
"code": null,
"e": 4638,
"s": 4542,
"text": "The Imblearn package comes with the implementation of the combination of SMOTE and Tomek Links."
},
{
"code": null,
"e": 4703,
"s": 4638,
"text": "You can install the library from PyPl using pip install imblearn"
},
{
"code": null,
"e": 4803,
"s": 4703,
"text": "from imblearn.combine import SMOTETomeksmt = SMOTETomek(random_state=42)X, y = smt.fit_sample(X, y)"
},
{
"code": null,
"e": 5031,
"s": 4803,
"text": "ENN (Edited Nearest Neighbour) is an undersampling technique that removes the instances of majority class on the border or boundary whose predictions made by the KNN algorithm are different from the other majority class points."
},
{
"code": null,
"e": 5252,
"s": 5031,
"text": "Similar to SMOTETomek, first SMOTE is applied to create synthetic data points of minority class samples, then using ENN the data points on the border or boundary are removed to increase the separation of the two classes."
},
{
"code": null,
"e": 5330,
"s": 5252,
"text": "A combination of SMOTE with ENN algorithm also comes in the imblearn package."
},
{
"code": null,
"e": 5426,
"s": 5330,
"text": "from imblearn.combine import SMOTEENNsmt = SMOTEENN(random_state=42)X, y = smt.fit_sample(X, y)"
},
{
"code": null,
"e": 5804,
"s": 5426,
"text": "The combination of SMOTE and undersampling techniques (ENN and Tomek Links) are proven effective. SMOTE is basically used to create synthetic class samples of minority class to balance the distribution then undersampling technique (ENN or Tomek Links) is used for cleaning irrelevant points in the boundary of the two classes to increase the separation between the two classes."
},
{
"code": null,
"e": 6064,
"s": 5804,
"text": "Imblean package comes with the implementation of SMOTETomek and SMOTEENN. There is a thumb rule about which works the best. One can write manual Python code to combine one oversampling technique proceeded by an undersampling technique to get the best results."
},
{
"code": null,
"e": 6171,
"s": 6064,
"text": "You can also read the below-mentioned article to know 7 oversampling techniques to handle class imbalance."
},
{
"code": null,
"e": 6194,
"s": 6171,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6286,
"s": 6194,
"text": "[1] Imbalance Learn API documentation: http://glemaitre.github.io/imbalanced-learn/api.html"
}
] |
How to Find Sum of Natural Numbers Using Recursion in Python?
|
If a function calls itself, it is called a recursive function. In order to prevent it from falling in infinite loop, recursive call is place in a conditional statement.
Following program accepts a number as input from user and sends it as argument to rsum() function. It recursively calls itself by decrementing the argument each time till it reaches 1.
def rsum(n):
if n <= 1:
return n
else:
return n + rsum(n-1)
num = int(input("Enter a number: "))
ttl=rsum(num)
print("The sum is",ttl)
Sample run of above program prints sum o natural numbers upto input number
Enter a number: 10
The sum is 55
|
[
{
"code": null,
"e": 1231,
"s": 1062,
"text": "If a function calls itself, it is called a recursive function. In order to prevent it from falling in infinite loop, recursive call is place in a conditional statement."
},
{
"code": null,
"e": 1416,
"s": 1231,
"text": "Following program accepts a number as input from user and sends it as argument to rsum() function. It recursively calls itself by decrementing the argument each time till it reaches 1."
},
{
"code": null,
"e": 1576,
"s": 1416,
"text": "def rsum(n):\n if n <= 1:\n return n\n else:\n return n + rsum(n-1)\n\nnum = int(input(\"Enter a number: \"))\nttl=rsum(num)\nprint(\"The sum is\",ttl)"
},
{
"code": null,
"e": 1651,
"s": 1576,
"text": "Sample run of above program prints sum o natural numbers upto input number"
},
{
"code": null,
"e": 1684,
"s": 1651,
"text": "Enter a number: 10\nThe sum is 55"
}
] |
Constructors in Java
|
Constructors are similar to methods and are different in the following sense.
They do not have any return type.
They do not have any return type.
The name of the constructor is the same as the name of the class.
The name of the constructor is the same as the name of the class.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked.
Each time a new object is created, at least one constructor will be invoked.
A class can have more than one constructor.
A class can have more than one constructor.
class A {
public int a;
//default constructor
public A() {
this(-1);
}
//parameterized constructor
public A(int a) {
this.a = a;
}
}
public class Tester {
public static void main(String[] args) {
//new object created using default constructor
A a1 = new A();
System.out.println(a1.a);
//new object created using parameterized constructor
A a2 = new A(1);
System.out.println(a2.a);
}
}
-1
1
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "Constructors are similar to methods and are different in the following sense."
},
{
"code": null,
"e": 1174,
"s": 1140,
"text": "They do not have any return type."
},
{
"code": null,
"e": 1208,
"s": 1174,
"text": "They do not have any return type."
},
{
"code": null,
"e": 1274,
"s": 1208,
"text": "The name of the constructor is the same as the name of the class."
},
{
"code": null,
"e": 1340,
"s": 1274,
"text": "The name of the constructor is the same as the name of the class."
},
{
"code": null,
"e": 1491,
"s": 1340,
"text": "Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class."
},
{
"code": null,
"e": 1642,
"s": 1491,
"text": "Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class."
},
{
"code": null,
"e": 1719,
"s": 1642,
"text": "Each time a new object is created, at least one constructor will be invoked."
},
{
"code": null,
"e": 1796,
"s": 1719,
"text": "Each time a new object is created, at least one constructor will be invoked."
},
{
"code": null,
"e": 1840,
"s": 1796,
"text": "A class can have more than one constructor."
},
{
"code": null,
"e": 1884,
"s": 1840,
"text": "A class can have more than one constructor."
},
{
"code": null,
"e": 2363,
"s": 1884,
"text": "class A {\n public int a;\n //default constructor\n public A() {\n this(-1);\n }\n\n //parameterized constructor\n public A(int a) {\n this.a = a;\n }\n}\n\npublic class Tester {\n public static void main(String[] args) {\n //new object created using default constructor\n A a1 = new A(); \n System.out.println(a1.a);\n\n //new object created using parameterized constructor\n A a2 = new A(1); \n System.out.println(a2.a);\n }\n}"
},
{
"code": null,
"e": 2368,
"s": 2363,
"text": "-1\n1"
}
] |
Remove comments in a string using C++
|
Given a C++ program as input, remove the comments from it. ‘source’ is a vector where the i-th line of the source code is the source[i]. This represents the result of splitting the source code string by the newline character \n. In C++, we can create two types of comments, i.e., Line Comments, Block Comments.
The string ‘\\’ denotes the line comment, which means the string next to it on the right will be ignored by the program.
The string ‘\* and *\’ is a multiline comment representing the string starting from ‘\* till the *\’ will be ignored.
The first useful comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored. If a certain line of code is empty after removing comments, you must not output that line − each string in the answer list will be non-empty.
For Example −
Input-1 −
source = ["/*Test program */", "int main()", "{ ", " // variable
declaration ", "int a, b, c;", "/* This is a test", " multiline ", "
comment for ", " testing */", "a = b + c;", "}"]
The line by line code is as follows:
/*Test program */
int main(){
// variable declaration
int a, b, c;
/* This is a test multiline comment for testing */
a = b + c;
}
Output −
["int main()","{ "," ","int a, b, c;","a = b + c;","}"]The line by line
code is as follows:
int main() /// Main Function
{
int a, b, c;
a = b + c;
}
Explanation − The string /* means a multiline comment, including lines 1 and lines 6-9. The string // denotes line 4 as comments.
We will parse the string line by line as an ideal compiler does. We will ignore all the characters between and after these block quotes when we encounter// or ‘/* /*.’
We will parse the string line by line as an ideal compiler does. We will ignore all the characters between and after these block quotes when we encounter// or ‘/* /*.’
A function removeString(vector<string>&source) takes a source code as an input and returns the code after removing its comments.
A function removeString(vector<string>&source) takes a source code as an input and returns the code after removing its comments.
A Boolean variable comment is initialized as false, which will check whether the particular block of string or character is a comment or not.
A Boolean variable comment is initialized as false, which will check whether the particular block of string or character is a comment or not.
If we start a block comment and we are not in a block, then we will skip over the next two characters and change our state in that particular block.
If we start a block comment and we are not in a block, then we will skip over the next two characters and change our state in that particular block.
If we end a block comment and we are in a block, we will skip over the next two characters and change our state to not be in a block.
If we end a block comment and we are in a block, we will skip over the next two characters and change our state to not be in a block.
If we start a line comment and aren't in a block, we will ignore the rest of the line.
If we start a line comment and aren't in a block, we will ignore the rest of the line.
If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
If we aren't in a block at the end of each line, we will record the line.
If we aren't in a block at the end of each line, we will record the line.
The algorithm runs in O(source) time complexity. The source is the input string.
The algorithm runs in O(source) time complexity. The source is the input string.
#include<bits/stdc++.h>
using namespace std;
vector<string>removeComments(vector<string>&source){
vector<string>ans;
string s;
bool comment= false;
for(int i = 0; i < source.size(); i++) {
for(int j = 0; j < source[i].size(); j++) {
if(!comment && j + 1 < source[i].size() && source[i][j] == '/' && source[i][j+1]=='/')
break;
else if(!comment && j + 1 < source[i].size() && source[i][j] == '/' && source[i][j+1]=='*')
comment = true;
j++;
else if(comment && j + 1 < source[i].size() && source[i][j] == '*' && source[i][j+1]=='/')
comment = false;
j++;
else if(!comment)
s.push_back(source[i][j]);
}
if(!comment && s.size()) ans.push_back(s), s.clear();
}
return ans;
}
int main(){
vector<string>source
(“ source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]
The formatted code can be interpreted as -
/*Test program */
int main() // Main function{
int a, b, c; // variable declaration
/* This is a test multiline comment for testing */
a = b + c;
}”);
vector<string>res= removeComments(source);
for(auto x:res){
cout<<x;
}
return 0;
}
["int main()","{ "," ","int a, b, c;","a = b + c;","}"]The line by line
code is visualized as below:
int main(){
int a, b, c;
a = b + c;
}
|
[
{
"code": null,
"e": 1373,
"s": 1062,
"text": "Given a C++ program as input, remove the comments from it. ‘source’ is a vector where the i-th line of the source code is the source[i]. This represents the result of splitting the source code string by the newline character \\n. In C++, we can create two types of comments, i.e., Line Comments, Block Comments."
},
{
"code": null,
"e": 1494,
"s": 1373,
"text": "The string ‘\\\\’ denotes the line comment, which means the string next to it on the right will be ignored by the program."
},
{
"code": null,
"e": 1612,
"s": 1494,
"text": "The string ‘\\* and *\\’ is a multiline comment representing the string starting from ‘\\* till the *\\’ will be ignored."
},
{
"code": null,
"e": 1951,
"s": 1612,
"text": "The first useful comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored. If a certain line of code is empty after removing comments, you must not output that line − each string in the answer list will be non-empty."
},
{
"code": null,
"e": 1965,
"s": 1951,
"text": "For Example −"
},
{
"code": null,
"e": 1975,
"s": 1965,
"text": "Input-1 −"
},
{
"code": null,
"e": 2338,
"s": 1975,
"text": "source = [\"/*Test program */\", \"int main()\", \"{ \", \" // variable\ndeclaration \", \"int a, b, c;\", \"/* This is a test\", \" multiline \", \"\ncomment for \", \" testing */\", \"a = b + c;\", \"}\"]\nThe line by line code is as follows:\n/*Test program */\nint main(){\n // variable declaration\n int a, b, c;\n /* This is a test multiline comment for testing */\n a = b + c;\n}"
},
{
"code": null,
"e": 2347,
"s": 2338,
"text": "Output −"
},
{
"code": null,
"e": 2502,
"s": 2347,
"text": "[\"int main()\",\"{ \",\" \",\"int a, b, c;\",\"a = b + c;\",\"}\"]The line by line\ncode is as follows:\nint main() /// Main Function\n{\n int a, b, c;\n a = b + c;\n}"
},
{
"code": null,
"e": 2632,
"s": 2502,
"text": "Explanation − The string /* means a multiline comment, including lines 1 and lines 6-9. The string // denotes line 4 as comments."
},
{
"code": null,
"e": 2800,
"s": 2632,
"text": "We will parse the string line by line as an ideal compiler does. We will ignore all the characters between and after these block quotes when we encounter// or ‘/* /*.’"
},
{
"code": null,
"e": 2968,
"s": 2800,
"text": "We will parse the string line by line as an ideal compiler does. We will ignore all the characters between and after these block quotes when we encounter// or ‘/* /*.’"
},
{
"code": null,
"e": 3097,
"s": 2968,
"text": "A function removeString(vector<string>&source) takes a source code as an input and returns the code after removing its comments."
},
{
"code": null,
"e": 3226,
"s": 3097,
"text": "A function removeString(vector<string>&source) takes a source code as an input and returns the code after removing its comments."
},
{
"code": null,
"e": 3368,
"s": 3226,
"text": "A Boolean variable comment is initialized as false, which will check whether the particular block of string or character is a comment or not."
},
{
"code": null,
"e": 3510,
"s": 3368,
"text": "A Boolean variable comment is initialized as false, which will check whether the particular block of string or character is a comment or not."
},
{
"code": null,
"e": 3659,
"s": 3510,
"text": "If we start a block comment and we are not in a block, then we will skip over the next two characters and change our state in that particular block."
},
{
"code": null,
"e": 3808,
"s": 3659,
"text": "If we start a block comment and we are not in a block, then we will skip over the next two characters and change our state in that particular block."
},
{
"code": null,
"e": 3942,
"s": 3808,
"text": "If we end a block comment and we are in a block, we will skip over the next two characters and change our state to not be in a block."
},
{
"code": null,
"e": 4076,
"s": 3942,
"text": "If we end a block comment and we are in a block, we will skip over the next two characters and change our state to not be in a block."
},
{
"code": null,
"e": 4163,
"s": 4076,
"text": "If we start a line comment and aren't in a block, we will ignore the rest of the line."
},
{
"code": null,
"e": 4250,
"s": 4163,
"text": "If we start a line comment and aren't in a block, we will ignore the rest of the line."
},
{
"code": null,
"e": 4362,
"s": 4250,
"text": "If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at."
},
{
"code": null,
"e": 4474,
"s": 4362,
"text": "If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at."
},
{
"code": null,
"e": 4548,
"s": 4474,
"text": "If we aren't in a block at the end of each line, we will record the line."
},
{
"code": null,
"e": 4622,
"s": 4548,
"text": "If we aren't in a block at the end of each line, we will record the line."
},
{
"code": null,
"e": 4703,
"s": 4622,
"text": "The algorithm runs in O(source) time complexity. The source is the input string."
},
{
"code": null,
"e": 4784,
"s": 4703,
"text": "The algorithm runs in O(source) time complexity. The source is the input string."
},
{
"code": null,
"e": 6124,
"s": 4784,
"text": "#include<bits/stdc++.h>\nusing namespace std;\nvector<string>removeComments(vector<string>&source){\n vector<string>ans;\n string s;\n bool comment= false;\n for(int i = 0; i < source.size(); i++) {\n for(int j = 0; j < source[i].size(); j++) {\n if(!comment && j + 1 < source[i].size() && source[i][j] == '/' && source[i][j+1]=='/')\n break;\n else if(!comment && j + 1 < source[i].size() && source[i][j] == '/' && source[i][j+1]=='*')\ncomment = true;\n j++;\n else if(comment && j + 1 < source[i].size() && source[i][j] == '*' && source[i][j+1]=='/')\ncomment = false;\n j++;\n else if(!comment)\n s.push_back(source[i][j]);\n }\n if(!comment && s.size()) ans.push_back(s), s.clear();\n }\n return ans;\n}\nint main(){\n vector<string>source\n (“ source = [\"/*Test program */\", \"int main()\", \"{ \", \" // variable declaration \", \"int a, b, c;\", \"/* This is a test\", \" multiline \", \" comment for \", \" testing */\", \"a = b + c;\", \"}\"]\n The formatted code can be interpreted as -\n /*Test program */\n int main() // Main function{\n int a, b, c; // variable declaration\n /* This is a test multiline comment for testing */\n a = b + c;\n }”);\n vector<string>res= removeComments(source);\n for(auto x:res){\n cout<<x;\n }\n return 0;\n}"
},
{
"code": null,
"e": 6269,
"s": 6124,
"text": "[\"int main()\",\"{ \",\" \",\"int a, b, c;\",\"a = b + c;\",\"}\"]The line by line\ncode is visualized as below:\nint main(){\n int a, b, c;\n a = b + c;\n}"
}
] |
C library Macro - EDOM
|
As mentioned above, the C library macro EDOM represents a domain error, which occurs if an input argument is outside the domain, over which the mathematical function is defined and errno is set to EDOM.
Following is the declaration for EDOM Macro.
#define EDOM some_value
NA
NA
NA
NA
The following example shows the usage of EDOM Macro.
#include <stdio.h>
#include <errno.h>
#include <math.h>
int main () {
double val;
errno = 0;
val = sqrt(-10);
if(errno == EDOM) {
printf("Invalid value \n");
} else {
printf("Valid value\n");
}
errno = 0;
val = sqrt(10);
if(errno == EDOM) {
printf("Invalid value\n");
} else {
printf("Valid value\n");
}
return(0);
}
Let us compile and run the above program that will produce the following result −
|
[
{
"code": null,
"e": 2344,
"s": 2141,
"text": "As mentioned above, the C library macro EDOM represents a domain error, which occurs if an input argument is outside the domain, over which the mathematical function is defined and errno is set to EDOM."
},
{
"code": null,
"e": 2389,
"s": 2344,
"text": "Following is the declaration for EDOM Macro."
},
{
"code": null,
"e": 2413,
"s": 2389,
"text": "#define EDOM some_value"
},
{
"code": null,
"e": 2416,
"s": 2413,
"text": "NA"
},
{
"code": null,
"e": 2419,
"s": 2416,
"text": "NA"
},
{
"code": null,
"e": 2422,
"s": 2419,
"text": "NA"
},
{
"code": null,
"e": 2425,
"s": 2422,
"text": "NA"
},
{
"code": null,
"e": 2478,
"s": 2425,
"text": "The following example shows the usage of EDOM Macro."
},
{
"code": null,
"e": 2873,
"s": 2478,
"text": "#include <stdio.h>\n#include <errno.h>\n#include <math.h>\n\nint main () {\n double val;\n\n errno = 0;\n val = sqrt(-10);\n \n if(errno == EDOM) {\n printf(\"Invalid value \\n\");\n } else {\n printf(\"Valid value\\n\");\n }\n \n errno = 0;\n val = sqrt(10);\n \n if(errno == EDOM) {\n printf(\"Invalid value\\n\");\n } else {\n printf(\"Valid value\\n\");\n }\n \n return(0);\n}"
}
] |
Count the number of ways to tile the floor of size n x m using 1 x m size tiles
|
22 Apr, 2022
Given a floor of size n x m and tiles of size 1 x m. The problem is to count the number of ways to tile the given floor using 1 x m tiles. A tile can either be placed horizontally or vertically. Both n and m are positive integers and 2 < = m.Examples:
Input : n = 2, m = 3
Output : 1
Only one combination to place
two tiles of size 1 x 3 horizontally
on the floor of size 2 x 3.
Input : n = 4, m = 4
Output : 2
1st combination:
All tiles are placed horizontally
2nd combination:
All tiles are placed vertically.
This problem is mainly a more generalized approach to the Tiling Problem. Approach: For a given value of n and m, the number of ways to tile the floor can be obtained from the following relation.
| 1, 1 < = n < m
count(n) = | 2, n = m
| count(n-1) + count(n-m), m < n
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to count number of ways to// tile a floor of size n x m using 1 x m tiles#include <bits/stdc++.h> using namespace std; // function to count the total number of waysint countWays(int n, int m){ // table to store values // of subproblems int count[n + 1]; count[0] = 0; // Fill the table upto value n for (int i = 1; i <= n; i++) { // recurrence relation if (i > m) count[i] = count[i - 1] + count[i - m]; // base cases and for i = m = 1 else if (i < m || i == 1) count[i] = 1; // i = = m else count[i] = 2; } // required number of ways return count[n];} // Driver program to test aboveint main(){ int n = 7, m = 4; cout << "Number of ways = " << countWays(n, m); return 0;}
// Java implementation to count number// of ways to tile a floor of size// n x m using 1 x m tilesimport java.io.*; class GFG { // function to count the total number of ways static int countWays(int n, int m) { // table to store values // of subproblems int count[] = new int[n + 1]; count[0] = 0; // Fill the table upto value n int i; for (i = 1; i <= n; i++) { // recurrence relation if (i > m) count[i] = count[i - 1] + count[i - m]; // base cases else if (i < m || i == 1) count[i] = 1; // i = = m else count[i] = 2; } // required number of ways return count[n]; } // Driver program public static void main(String[] args) { int n = 7; int m = 4; System.out.println("Number of ways = " + countWays(n, m)); }} // This code is contributed by vt_m.
# Python implementation to# count number of ways to# tile a floor of size n x m# using 1 x m tiles def countWays(n, m): # table to store values # of subproblems count =[] for i in range(n + 2): count.append(0) count[0] = 0 # Fill the table upto value n for i in range(1, n + 1): # recurrence relation if (i > m): count[i] = count[i-1] + count[i-m] # base cases elif (i < m or i == 1): count[i] = 1 # i = = m else: count[i] = 2 # required number of ways return count[n] # Driver code n = 7m = 4 print("Number of ways = ", countWays(n, m)) # This code is contributed# by Anant Agarwal.
// C# implementation to count number// of ways to tile a floor of size// n x m using 1 x m tilesusing System; class GFG { // function to count the total // number of ways static int countWays(int n, int m) { // table to store values // of subproblems int[] count = new int[n + 1]; count[0] = 0; // Fill the table upto value n int i; for (i = 1; i <= n; i++) { // recurrence relation if (i > m) count[i] = count[i - 1] + count[i - m]; // base cases and i = m = 1 else if (i < m || i == 1) count[i] = 1; // i = = m else count[i] = 2; } // required number of ways return count[n]; } // Driver program public static void Main() { int n = 7; int m = 4; Console.Write("Number of ways = " + countWays(n, m)); }} // This code is contributed by parashar.
<?php// PHP implementation to count// number of ways to tile a// floor of size n x m using// 1 x m tiles // function to count the// total number of waysfunction countWays($n, $m){ // table to store values // of subproblems $count[0] = 0; // Fill the table // upto value n for ($i = 1; $i <= $n; $i++) { // recurrence relation if ($i > $m) $count[$i] = $count[$i - 1] + $count[$i - $m]; // base cases else if ($i < $m or $i == 1) $count[$i] = 1; // i = = m else $count[$i] = 2; } // required number of ways return $count[$n];} // Driver Code $n = 7; $m = 4; echo "Number of ways = ", countWays($n, $m); // This code is contributed by ajit?>
<script> // Javascript implementation to count number // of ways to tile a floor of size // n x m using 1 x m tiles // function to count the total // number of ways function countWays(n, m) { // table to store values // of subproblems let count = new Array(n + 1); count[0] = 0; // Fill the table upto value n let i; for (i = 1; i <= n; i++) { // recurrence relation if (i > m) count[i] = count[i - 1] + count[i - m]; // base cases and i = m = 1 else if (i < m || i == 1) count[i] = 1; // i = = m else count[i] = 2; } // required number of ways return count[n]; } let n = 7; let m = 4; document.write("Number of ways = " + countWays(n, m)); // This code is contributed by rameshtravel07.</script>
Output:
Number of ways = 5
Time Complexity: O(n) Auxiliary Space: O(n)This article is contributed by Ayush Jauhari. 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.
parashar
jit_t
AnindyaSen
rameshtravel07
simmytarika5
morjariyajigar45
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in an undirected graph
Floyd Warshall Algorithm | DP-16
Bellman–Ford Algorithm | DP-23
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Sieve of Eratosthenes
Minimum number of jumps to reach end
Tabulation vs Memoization
Count number of binary strings without consecutive 1's
Longest Common Substring | DP-29
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 308,
"s": 54,
"text": "Given a floor of size n x m and tiles of size 1 x m. The problem is to count the number of ways to tile the given floor using 1 x m tiles. A tile can either be placed horizontally or vertically. Both n and m are positive integers and 2 < = m.Examples: "
},
{
"code": null,
"e": 572,
"s": 308,
"text": "Input : n = 2, m = 3\nOutput : 1\nOnly one combination to place \ntwo tiles of size 1 x 3 horizontally\non the floor of size 2 x 3. \n\nInput : n = 4, m = 4\nOutput : 2\n1st combination:\nAll tiles are placed horizontally\n2nd combination:\nAll tiles are placed vertically."
},
{
"code": null,
"e": 772,
"s": 574,
"text": "This problem is mainly a more generalized approach to the Tiling Problem. Approach: For a given value of n and m, the number of ways to tile the floor can be obtained from the following relation. "
},
{
"code": null,
"e": 885,
"s": 772,
"text": " | 1, 1 < = n < m\n count(n) = | 2, n = m\n | count(n-1) + count(n-m), m < n\n "
},
{
"code": null,
"e": 891,
"s": 887,
"text": "C++"
},
{
"code": null,
"e": 896,
"s": 891,
"text": "Java"
},
{
"code": null,
"e": 904,
"s": 896,
"text": "Python3"
},
{
"code": null,
"e": 907,
"s": 904,
"text": "C#"
},
{
"code": null,
"e": 911,
"s": 907,
"text": "PHP"
},
{
"code": null,
"e": 922,
"s": 911,
"text": "Javascript"
},
{
"code": "// C++ implementation to count number of ways to// tile a floor of size n x m using 1 x m tiles#include <bits/stdc++.h> using namespace std; // function to count the total number of waysint countWays(int n, int m){ // table to store values // of subproblems int count[n + 1]; count[0] = 0; // Fill the table upto value n for (int i = 1; i <= n; i++) { // recurrence relation if (i > m) count[i] = count[i - 1] + count[i - m]; // base cases and for i = m = 1 else if (i < m || i == 1) count[i] = 1; // i = = m else count[i] = 2; } // required number of ways return count[n];} // Driver program to test aboveint main(){ int n = 7, m = 4; cout << \"Number of ways = \" << countWays(n, m); return 0;}",
"e": 1742,
"s": 922,
"text": null
},
{
"code": "// Java implementation to count number// of ways to tile a floor of size// n x m using 1 x m tilesimport java.io.*; class GFG { // function to count the total number of ways static int countWays(int n, int m) { // table to store values // of subproblems int count[] = new int[n + 1]; count[0] = 0; // Fill the table upto value n int i; for (i = 1; i <= n; i++) { // recurrence relation if (i > m) count[i] = count[i - 1] + count[i - m]; // base cases else if (i < m || i == 1) count[i] = 1; // i = = m else count[i] = 2; } // required number of ways return count[n]; } // Driver program public static void main(String[] args) { int n = 7; int m = 4; System.out.println(\"Number of ways = \" + countWays(n, m)); }} // This code is contributed by vt_m.",
"e": 2750,
"s": 1742,
"text": null
},
{
"code": "# Python implementation to# count number of ways to# tile a floor of size n x m# using 1 x m tiles def countWays(n, m): # table to store values # of subproblems count =[] for i in range(n + 2): count.append(0) count[0] = 0 # Fill the table upto value n for i in range(1, n + 1): # recurrence relation if (i > m): count[i] = count[i-1] + count[i-m] # base cases elif (i < m or i == 1): count[i] = 1 # i = = m else: count[i] = 2 # required number of ways return count[n] # Driver code n = 7m = 4 print(\"Number of ways = \", countWays(n, m)) # This code is contributed# by Anant Agarwal.",
"e": 3479,
"s": 2750,
"text": null
},
{
"code": "// C# implementation to count number// of ways to tile a floor of size// n x m using 1 x m tilesusing System; class GFG { // function to count the total // number of ways static int countWays(int n, int m) { // table to store values // of subproblems int[] count = new int[n + 1]; count[0] = 0; // Fill the table upto value n int i; for (i = 1; i <= n; i++) { // recurrence relation if (i > m) count[i] = count[i - 1] + count[i - m]; // base cases and i = m = 1 else if (i < m || i == 1) count[i] = 1; // i = = m else count[i] = 2; } // required number of ways return count[n]; } // Driver program public static void Main() { int n = 7; int m = 4; Console.Write(\"Number of ways = \" + countWays(n, m)); }} // This code is contributed by parashar.",
"e": 4510,
"s": 3479,
"text": null
},
{
"code": "<?php// PHP implementation to count// number of ways to tile a// floor of size n x m using// 1 x m tiles // function to count the// total number of waysfunction countWays($n, $m){ // table to store values // of subproblems $count[0] = 0; // Fill the table // upto value n for ($i = 1; $i <= $n; $i++) { // recurrence relation if ($i > $m) $count[$i] = $count[$i - 1] + $count[$i - $m]; // base cases else if ($i < $m or $i == 1) $count[$i] = 1; // i = = m else $count[$i] = 2; } // required number of ways return $count[$n];} // Driver Code $n = 7; $m = 4; echo \"Number of ways = \", countWays($n, $m); // This code is contributed by ajit?>",
"e": 5326,
"s": 4510,
"text": null
},
{
"code": "<script> // Javascript implementation to count number // of ways to tile a floor of size // n x m using 1 x m tiles // function to count the total // number of ways function countWays(n, m) { // table to store values // of subproblems let count = new Array(n + 1); count[0] = 0; // Fill the table upto value n let i; for (i = 1; i <= n; i++) { // recurrence relation if (i > m) count[i] = count[i - 1] + count[i - m]; // base cases and i = m = 1 else if (i < m || i == 1) count[i] = 1; // i = = m else count[i] = 2; } // required number of ways return count[n]; } let n = 7; let m = 4; document.write(\"Number of ways = \" + countWays(n, m)); // This code is contributed by rameshtravel07.</script>",
"e": 6268,
"s": 5326,
"text": null
},
{
"code": null,
"e": 6278,
"s": 6268,
"text": "Output: "
},
{
"code": null,
"e": 6297,
"s": 6278,
"text": "Number of ways = 5"
},
{
"code": null,
"e": 6762,
"s": 6297,
"text": "Time Complexity: O(n) Auxiliary Space: O(n)This article is contributed by Ayush Jauhari. 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. "
},
{
"code": null,
"e": 6771,
"s": 6762,
"text": "parashar"
},
{
"code": null,
"e": 6777,
"s": 6771,
"text": "jit_t"
},
{
"code": null,
"e": 6788,
"s": 6777,
"text": "AnindyaSen"
},
{
"code": null,
"e": 6803,
"s": 6788,
"text": "rameshtravel07"
},
{
"code": null,
"e": 6816,
"s": 6803,
"text": "simmytarika5"
},
{
"code": null,
"e": 6833,
"s": 6816,
"text": "morjariyajigar45"
},
{
"code": null,
"e": 6853,
"s": 6833,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 6873,
"s": 6853,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 6971,
"s": 6873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7039,
"s": 6971,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 7072,
"s": 7039,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 7103,
"s": 7072,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 7138,
"s": 7103,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 7206,
"s": 7138,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 7228,
"s": 7206,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 7265,
"s": 7228,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 7291,
"s": 7265,
"text": "Tabulation vs Memoization"
},
{
"code": null,
"e": 7346,
"s": 7291,
"text": "Count number of binary strings without consecutive 1's"
}
] |
Scala | Preconditions(assert, assume, require, ensuring)
|
29 Dec, 2019
Preconditions refer to some conditions in Scala that need to be fulfilled before going further with any code or program. In Scala, the process of Designing by Contract(DbC), a software designing process gives significance and meaning to Scala preconditions. The above approach was given by Betrand Mayer and it offers some post conditions and preconditions to a code block which if not satisfied, throws an exception.
Scala preconditions are a set of major functions that have different conditions a programmer must follow while designing a software. These functions come in Predef.scala package and one does not have to import any separate package.The methods are :
Assert – For general assertionsAssume – Stating an AxiomRequire – Specifically checking inputsEnsuring – is a post condition that has also been covered.
Assert – For general assertions
Assume – Stating an Axiom
Require – Specifically checking inputs
Ensuring – is a post condition that has also been covered.
AssertAssert method puts a necessity for a condition to be satisfied while performing a certain action. If this condition is satisfied, then the code works fine, otherwise it throws an exception. The exceptions are checked at run time. The assert() method is thus a way to dynamically check the invariants. The above method takes a Boolean statement as a parameter and checks throughout the program if anywhere it is violated. it throws out an exception or an assertion error.Consider the following program as a part of Driver’s license approval of application process. It produces error if the applicant age is not equal to or more than 18.// Code to check the age of the applicantval applicant_age = 16 // assert method callingassert(applicant_age>17)If the age is past the require minimum, the process is moved forward, otherwise, the program throws an Exception as below:Exception in thread "main" java.lang.AssertionError: assertion failedLooking up for the code for the same in Predef.scala, one would find a similar code like above:def assert(assertion: Boolean) { if (!assertion) throw new java.lang.AssertionError("assertion failed") }
Assert method puts a necessity for a condition to be satisfied while performing a certain action. If this condition is satisfied, then the code works fine, otherwise it throws an exception. The exceptions are checked at run time. The assert() method is thus a way to dynamically check the invariants. The above method takes a Boolean statement as a parameter and checks throughout the program if anywhere it is violated. it throws out an exception or an assertion error.
Consider the following program as a part of Driver’s license approval of application process. It produces error if the applicant age is not equal to or more than 18.
// Code to check the age of the applicantval applicant_age = 16 // assert method callingassert(applicant_age>17)
If the age is past the require minimum, the process is moved forward, otherwise, the program throws an Exception as below:
Exception in thread "main" java.lang.AssertionError: assertion failed
Looking up for the code for the same in Predef.scala, one would find a similar code like above:
def assert(assertion: Boolean) { if (!assertion) throw new java.lang.AssertionError("assertion failed") }
AssumeAssume method is expected to be consumed by static analysis tools. It is supposed to limit down the number of conditions that have to be checked for execution of a program. If the assume condition is violated, the checker, silently leaves the path and doesn’t allow the program to go much deeper. The assume() method has the same syntax as the previously mentioned assert(), the only difference being its execution.The following example talks about a program that executes assuming that the age of the applicant is in any case greater than or equal to 18. The main code had been avoided and only the code containing the call to assume() is incorporated.// Code to check the age of the applicantlicense_approval(17) // Method to approve the License applicationdef license_approval(applicant_age:Int) { assume(applicant_age>=18)//...............//............//............//The main code for checking the other details of the applicant. //...............//............//............}The assume() method gives the static checker an axiom that it could rely upon. This reduces the burden on the checker. The program runs deeper into the code if the Boolean condition of the assume() parameter is satisfied, otherwise, it throws an exception:Exception in thread "main" java.lang.AssertionError: assumption failedThe similar code can be found inside the Predef.scala package:def assume(assumption: Boolean) { if (!assumption) throw new java.lang.AssertionError("assumption failed") } While assert() is a method of asserting a condition in all execution paths or to check an invariant condition throughout the program, assume(), on the other hand, is used to reduce the load on the static analyser. It works locally to develop a divide-and-rule mechanism to help the analyzers to assume a condition and go through checking the code.
Assume method is expected to be consumed by static analysis tools. It is supposed to limit down the number of conditions that have to be checked for execution of a program. If the assume condition is violated, the checker, silently leaves the path and doesn’t allow the program to go much deeper. The assume() method has the same syntax as the previously mentioned assert(), the only difference being its execution.
The following example talks about a program that executes assuming that the age of the applicant is in any case greater than or equal to 18. The main code had been avoided and only the code containing the call to assume() is incorporated.
// Code to check the age of the applicantlicense_approval(17) // Method to approve the License applicationdef license_approval(applicant_age:Int) { assume(applicant_age>=18)//...............//............//............//The main code for checking the other details of the applicant. //...............//............//............}
The assume() method gives the static checker an axiom that it could rely upon. This reduces the burden on the checker. The program runs deeper into the code if the Boolean condition of the assume() parameter is satisfied, otherwise, it throws an exception:
Exception in thread "main" java.lang.AssertionError: assumption failed
The similar code can be found inside the Predef.scala package:
def assume(assumption: Boolean) { if (!assumption) throw new java.lang.AssertionError("assumption failed") }
While assert() is a method of asserting a condition in all execution paths or to check an invariant condition throughout the program, assume(), on the other hand, is used to reduce the load on the static analyser. It works locally to develop a divide-and-rule mechanism to help the analyzers to assume a condition and go through checking the code.
Require:This method has an innovative mode of dealing with the problem. It usually blames the method caller if a certain condition is not satisfied. If the condition is satisfied, the program goes on executing, if it does not, it throws an exception. The syntax is the same as before for assert() and assume() following a Boolean condition as the parameter. The working of the require() function can be shown with an example:The following example shown a method to double any odd number. If the number passed in the function is odd, it works smoothly, if not, then an exception is thrown.// Code to double the odd numbersdef double_odd_numbers(number:Int) : Int = { require(number%2==1) // Checking if the number is odd using assume method number * 2; } // Calling functiondouble_odd_numbers(13)If the condition is not satisfied, the following exception is thrown:Exception in thread "main" java.lang.IllegalArgumentException: requirement failedLooking up for the code for exception in Predef.scala, we come across the following code:def require(requirement: Boolean) { if (!requirement) throw new IllegalArgumentException("requirement failed") }
This method has an innovative mode of dealing with the problem. It usually blames the method caller if a certain condition is not satisfied. If the condition is satisfied, the program goes on executing, if it does not, it throws an exception. The syntax is the same as before for assert() and assume() following a Boolean condition as the parameter. The working of the require() function can be shown with an example:The following example shown a method to double any odd number. If the number passed in the function is odd, it works smoothly, if not, then an exception is thrown.
// Code to double the odd numbersdef double_odd_numbers(number:Int) : Int = { require(number%2==1) // Checking if the number is odd using assume method number * 2; } // Calling functiondouble_odd_numbers(13)
If the condition is not satisfied, the following exception is thrown:
Exception in thread "main" java.lang.IllegalArgumentException: requirement failed
Looking up for the code for exception in Predef.scala, we come across the following code:
def require(requirement: Boolean) { if (!requirement) throw new IllegalArgumentException("requirement failed") }
Ensure:Ensure is a post-condition unlike the others. This method is usually applied along with the require() method to make a workable program. Considering the above example itself, we can modify the code by adding an ensure condition which requires the input number to be less than a certain limit.// Code to double the odd numbersdef double_odd_numbers(number:Int, lmt:Int) : Int = { require(number%2==1) // Checking if the number is odd using assume method number * 2; } ensuring(number * 2 < lmt) // Ensuring that the number produced is less than the limit. // Calling function// The method also requires a limit [parameter to be passed. double_odd_numbers(13, 100)The assert() method thus requires that the checker must prove the condition that follows as a parameter, assume(), on the other hand, helps checker to reduce the burden by assuming that a certain condition holds true. While, the require() method specifies the condition that has to be followed by the caller of the function.If the programmer seeks to remove the exceptions generated by the assume() and assert() methods, one can use the -Xdisable-assertions command to do so.
Ensure is a post-condition unlike the others. This method is usually applied along with the require() method to make a workable program. Considering the above example itself, we can modify the code by adding an ensure condition which requires the input number to be less than a certain limit.
// Code to double the odd numbersdef double_odd_numbers(number:Int, lmt:Int) : Int = { require(number%2==1) // Checking if the number is odd using assume method number * 2; } ensuring(number * 2 < lmt) // Ensuring that the number produced is less than the limit. // Calling function// The method also requires a limit [parameter to be passed. double_odd_numbers(13, 100)
The assert() method thus requires that the checker must prove the condition that follows as a parameter, assume(), on the other hand, helps checker to reduce the burden by assuming that a certain condition holds true. While, the require() method specifies the condition that has to be followed by the caller of the function.
If the programmer seeks to remove the exceptions generated by the assume() and assert() methods, one can use the -Xdisable-assertions command to do so.
Picked
Scala
scala-exception
Scala
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
How to Install Scala with VSCode?
Scala | Option
Hello World in Scala
Scala ListBuffer
Scala | Traits
Introduction to Scala
Implicit Parameters In Scala
Scala | Functions - Basics
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2019"
},
{
"code": null,
"e": 446,
"s": 28,
"text": "Preconditions refer to some conditions in Scala that need to be fulfilled before going further with any code or program. In Scala, the process of Designing by Contract(DbC), a software designing process gives significance and meaning to Scala preconditions. The above approach was given by Betrand Mayer and it offers some post conditions and preconditions to a code block which if not satisfied, throws an exception."
},
{
"code": null,
"e": 695,
"s": 446,
"text": "Scala preconditions are a set of major functions that have different conditions a programmer must follow while designing a software. These functions come in Predef.scala package and one does not have to import any separate package.The methods are :"
},
{
"code": null,
"e": 848,
"s": 695,
"text": "Assert – For general assertionsAssume – Stating an AxiomRequire – Specifically checking inputsEnsuring – is a post condition that has also been covered."
},
{
"code": null,
"e": 880,
"s": 848,
"text": "Assert – For general assertions"
},
{
"code": null,
"e": 906,
"s": 880,
"text": "Assume – Stating an Axiom"
},
{
"code": null,
"e": 945,
"s": 906,
"text": "Require – Specifically checking inputs"
},
{
"code": null,
"e": 1004,
"s": 945,
"text": "Ensuring – is a post condition that has also been covered."
},
{
"code": null,
"e": 2157,
"s": 1004,
"text": "AssertAssert method puts a necessity for a condition to be satisfied while performing a certain action. If this condition is satisfied, then the code works fine, otherwise it throws an exception. The exceptions are checked at run time. The assert() method is thus a way to dynamically check the invariants. The above method takes a Boolean statement as a parameter and checks throughout the program if anywhere it is violated. it throws out an exception or an assertion error.Consider the following program as a part of Driver’s license approval of application process. It produces error if the applicant age is not equal to or more than 18.// Code to check the age of the applicantval applicant_age = 16 // assert method callingassert(applicant_age>17)If the age is past the require minimum, the process is moved forward, otherwise, the program throws an Exception as below:Exception in thread \"main\" java.lang.AssertionError: assertion failedLooking up for the code for the same in Predef.scala, one would find a similar code like above:def assert(assertion: Boolean) { if (!assertion) throw new java.lang.AssertionError(\"assertion failed\") } "
},
{
"code": null,
"e": 2628,
"s": 2157,
"text": "Assert method puts a necessity for a condition to be satisfied while performing a certain action. If this condition is satisfied, then the code works fine, otherwise it throws an exception. The exceptions are checked at run time. The assert() method is thus a way to dynamically check the invariants. The above method takes a Boolean statement as a parameter and checks throughout the program if anywhere it is violated. it throws out an exception or an assertion error."
},
{
"code": null,
"e": 2794,
"s": 2628,
"text": "Consider the following program as a part of Driver’s license approval of application process. It produces error if the applicant age is not equal to or more than 18."
},
{
"code": "// Code to check the age of the applicantval applicant_age = 16 // assert method callingassert(applicant_age>17)",
"e": 2908,
"s": 2794,
"text": null
},
{
"code": null,
"e": 3031,
"s": 2908,
"text": "If the age is past the require minimum, the process is moved forward, otherwise, the program throws an Exception as below:"
},
{
"code": null,
"e": 3101,
"s": 3031,
"text": "Exception in thread \"main\" java.lang.AssertionError: assertion failed"
},
{
"code": null,
"e": 3197,
"s": 3101,
"text": "Looking up for the code for the same in Predef.scala, one would find a similar code like above:"
},
{
"code": "def assert(assertion: Boolean) { if (!assertion) throw new java.lang.AssertionError(\"assertion failed\") } ",
"e": 3310,
"s": 3197,
"text": null
},
{
"code": null,
"e": 5153,
"s": 3310,
"text": "AssumeAssume method is expected to be consumed by static analysis tools. It is supposed to limit down the number of conditions that have to be checked for execution of a program. If the assume condition is violated, the checker, silently leaves the path and doesn’t allow the program to go much deeper. The assume() method has the same syntax as the previously mentioned assert(), the only difference being its execution.The following example talks about a program that executes assuming that the age of the applicant is in any case greater than or equal to 18. The main code had been avoided and only the code containing the call to assume() is incorporated.// Code to check the age of the applicantlicense_approval(17) // Method to approve the License applicationdef license_approval(applicant_age:Int) { assume(applicant_age>=18)//...............//............//............//The main code for checking the other details of the applicant. //...............//............//............}The assume() method gives the static checker an axiom that it could rely upon. This reduces the burden on the checker. The program runs deeper into the code if the Boolean condition of the assume() parameter is satisfied, otherwise, it throws an exception:Exception in thread \"main\" java.lang.AssertionError: assumption failedThe similar code can be found inside the Predef.scala package:def assume(assumption: Boolean) { if (!assumption) throw new java.lang.AssertionError(\"assumption failed\") } While assert() is a method of asserting a condition in all execution paths or to check an invariant condition throughout the program, assume(), on the other hand, is used to reduce the load on the static analyser. It works locally to develop a divide-and-rule mechanism to help the analyzers to assume a condition and go through checking the code."
},
{
"code": null,
"e": 5569,
"s": 5153,
"text": "Assume method is expected to be consumed by static analysis tools. It is supposed to limit down the number of conditions that have to be checked for execution of a program. If the assume condition is violated, the checker, silently leaves the path and doesn’t allow the program to go much deeper. The assume() method has the same syntax as the previously mentioned assert(), the only difference being its execution."
},
{
"code": null,
"e": 5808,
"s": 5569,
"text": "The following example talks about a program that executes assuming that the age of the applicant is in any case greater than or equal to 18. The main code had been avoided and only the code containing the call to assume() is incorporated."
},
{
"code": "// Code to check the age of the applicantlicense_approval(17) // Method to approve the License applicationdef license_approval(applicant_age:Int) { assume(applicant_age>=18)//...............//............//............//The main code for checking the other details of the applicant. //...............//............//............}",
"e": 6142,
"s": 5808,
"text": null
},
{
"code": null,
"e": 6399,
"s": 6142,
"text": "The assume() method gives the static checker an axiom that it could rely upon. This reduces the burden on the checker. The program runs deeper into the code if the Boolean condition of the assume() parameter is satisfied, otherwise, it throws an exception:"
},
{
"code": null,
"e": 6470,
"s": 6399,
"text": "Exception in thread \"main\" java.lang.AssertionError: assumption failed"
},
{
"code": null,
"e": 6533,
"s": 6470,
"text": "The similar code can be found inside the Predef.scala package:"
},
{
"code": "def assume(assumption: Boolean) { if (!assumption) throw new java.lang.AssertionError(\"assumption failed\") } ",
"e": 6649,
"s": 6533,
"text": null
},
{
"code": null,
"e": 6997,
"s": 6649,
"text": "While assert() is a method of asserting a condition in all execution paths or to check an invariant condition throughout the program, assume(), on the other hand, is used to reduce the load on the static analyser. It works locally to develop a divide-and-rule mechanism to help the analyzers to assume a condition and go through checking the code."
},
{
"code": null,
"e": 8162,
"s": 6997,
"text": "Require:This method has an innovative mode of dealing with the problem. It usually blames the method caller if a certain condition is not satisfied. If the condition is satisfied, the program goes on executing, if it does not, it throws an exception. The syntax is the same as before for assert() and assume() following a Boolean condition as the parameter. The working of the require() function can be shown with an example:The following example shown a method to double any odd number. If the number passed in the function is odd, it works smoothly, if not, then an exception is thrown.// Code to double the odd numbersdef double_odd_numbers(number:Int) : Int = { require(number%2==1) // Checking if the number is odd using assume method number * 2; } // Calling functiondouble_odd_numbers(13)If the condition is not satisfied, the following exception is thrown:Exception in thread \"main\" java.lang.IllegalArgumentException: requirement failedLooking up for the code for exception in Predef.scala, we come across the following code:def require(requirement: Boolean) { if (!requirement) throw new IllegalArgumentException(\"requirement failed\") } "
},
{
"code": null,
"e": 8743,
"s": 8162,
"text": "This method has an innovative mode of dealing with the problem. It usually blames the method caller if a certain condition is not satisfied. If the condition is satisfied, the program goes on executing, if it does not, it throws an exception. The syntax is the same as before for assert() and assume() following a Boolean condition as the parameter. The working of the require() function can be shown with an example:The following example shown a method to double any odd number. If the number passed in the function is odd, it works smoothly, if not, then an exception is thrown."
},
{
"code": "// Code to double the odd numbersdef double_odd_numbers(number:Int) : Int = { require(number%2==1) // Checking if the number is odd using assume method number * 2; } // Calling functiondouble_odd_numbers(13)",
"e": 8962,
"s": 8743,
"text": null
},
{
"code": null,
"e": 9032,
"s": 8962,
"text": "If the condition is not satisfied, the following exception is thrown:"
},
{
"code": null,
"e": 9114,
"s": 9032,
"text": "Exception in thread \"main\" java.lang.IllegalArgumentException: requirement failed"
},
{
"code": null,
"e": 9204,
"s": 9114,
"text": "Looking up for the code for exception in Predef.scala, we come across the following code:"
},
{
"code": "def require(requirement: Boolean) { if (!requirement) throw new IllegalArgumentException(\"requirement failed\") } ",
"e": 9324,
"s": 9204,
"text": null
},
{
"code": null,
"e": 10482,
"s": 9324,
"text": "Ensure:Ensure is a post-condition unlike the others. This method is usually applied along with the require() method to make a workable program. Considering the above example itself, we can modify the code by adding an ensure condition which requires the input number to be less than a certain limit.// Code to double the odd numbersdef double_odd_numbers(number:Int, lmt:Int) : Int = { require(number%2==1) // Checking if the number is odd using assume method number * 2; } ensuring(number * 2 < lmt) // Ensuring that the number produced is less than the limit. // Calling function// The method also requires a limit [parameter to be passed. double_odd_numbers(13, 100)The assert() method thus requires that the checker must prove the condition that follows as a parameter, assume(), on the other hand, helps checker to reduce the burden by assuming that a certain condition holds true. While, the require() method specifies the condition that has to be followed by the caller of the function.If the programmer seeks to remove the exceptions generated by the assume() and assert() methods, one can use the -Xdisable-assertions command to do so."
},
{
"code": null,
"e": 10775,
"s": 10482,
"text": "Ensure is a post-condition unlike the others. This method is usually applied along with the require() method to make a workable program. Considering the above example itself, we can modify the code by adding an ensure condition which requires the input number to be less than a certain limit."
},
{
"code": "// Code to double the odd numbersdef double_odd_numbers(number:Int, lmt:Int) : Int = { require(number%2==1) // Checking if the number is odd using assume method number * 2; } ensuring(number * 2 < lmt) // Ensuring that the number produced is less than the limit. // Calling function// The method also requires a limit [parameter to be passed. double_odd_numbers(13, 100)",
"e": 11159,
"s": 10775,
"text": null
},
{
"code": null,
"e": 11484,
"s": 11159,
"text": "The assert() method thus requires that the checker must prove the condition that follows as a parameter, assume(), on the other hand, helps checker to reduce the burden by assuming that a certain condition holds true. While, the require() method specifies the condition that has to be followed by the caller of the function."
},
{
"code": null,
"e": 11636,
"s": 11484,
"text": "If the programmer seeks to remove the exceptions generated by the assume() and assert() methods, one can use the -Xdisable-assertions command to do so."
},
{
"code": null,
"e": 11643,
"s": 11636,
"text": "Picked"
},
{
"code": null,
"e": 11649,
"s": 11643,
"text": "Scala"
},
{
"code": null,
"e": 11665,
"s": 11649,
"text": "scala-exception"
},
{
"code": null,
"e": 11671,
"s": 11665,
"text": "Scala"
},
{
"code": null,
"e": 11690,
"s": 11671,
"text": "Technical Scripter"
},
{
"code": null,
"e": 11788,
"s": 11690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11809,
"s": 11788,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 11843,
"s": 11809,
"text": "How to Install Scala with VSCode?"
},
{
"code": null,
"e": 11858,
"s": 11843,
"text": "Scala | Option"
},
{
"code": null,
"e": 11879,
"s": 11858,
"text": "Hello World in Scala"
},
{
"code": null,
"e": 11896,
"s": 11879,
"text": "Scala ListBuffer"
},
{
"code": null,
"e": 11911,
"s": 11896,
"text": "Scala | Traits"
},
{
"code": null,
"e": 11933,
"s": 11911,
"text": "Introduction to Scala"
},
{
"code": null,
"e": 11962,
"s": 11933,
"text": "Implicit Parameters In Scala"
}
] |
Trape – Free GUI Based Phishing or Tracking Tool
|
18 Jul, 2021
Trape is a tool written in Python which can be used to lure the victim in phishing or redirecting him to another website etc. So when a victim gets lure into the phishing attack, the tool captures the victim’s IP address, location, and sessions, etc. The captured results can be seen in the dashboard in a web browser. It can also be said that it is an OSINT research tool, which allows people to track and execute social engineering attacks in real-time.
Easy to use.
Traces the path between you and the target.
Easy to install.
It can manage social engineering attacks in the target’s browser.
First clone the tool from the Github repo using the following commands.
git clone https://github.com/boxug/trape.git
Change directory by,
cd trape
Now we need to install some requirements before running trape.
pip install -r requirements.txt
Fig 1: Cloning Trape from GitHub Repository.
Run the tool by entering python trape.py -h to check the options it provides.
Fig 2: Trape tool.
Enter the URL on which you want the victim to be redirected when he clicks on it say, we want the victim to be redirected to google.com. So the command will be:
python trape.py -u https://google.com -p 8080.
Fig 3: Waiting for victim to click on the url.
In the meantime, open the control panel by copying the control panel link in your web browser and sign in with the access key you have been provided.
Fig 4: Control Panel.
Now in the dashboard, we can see, that the victim has clicked on the URL and we can see his public IP, what browser he is using. Click on details on the bottom right to know other things about the victim like his location etc.
FIg 5: Victim’s Report.
Here we can see both the public IP and the local IP of the victim, his operating system, browser, which country and city he resides in.
FIg 6: Victim’s detailed information.
We can also perform social engineering attacks using trape tools like we can generate an alert.
Fig 7: Alert generated.
We can send a file.
Fig 8: Sending file to victim.
We can also redirect him to a phishing page.
Fig 9: Victim redirected to phishing page.
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
Array Basics in Shell Scripting | Set 1
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 510,
"s": 54,
"text": "Trape is a tool written in Python which can be used to lure the victim in phishing or redirecting him to another website etc. So when a victim gets lure into the phishing attack, the tool captures the victim’s IP address, location, and sessions, etc. The captured results can be seen in the dashboard in a web browser. It can also be said that it is an OSINT research tool, which allows people to track and execute social engineering attacks in real-time."
},
{
"code": null,
"e": 523,
"s": 510,
"text": "Easy to use."
},
{
"code": null,
"e": 567,
"s": 523,
"text": "Traces the path between you and the target."
},
{
"code": null,
"e": 584,
"s": 567,
"text": "Easy to install."
},
{
"code": null,
"e": 650,
"s": 584,
"text": "It can manage social engineering attacks in the target’s browser."
},
{
"code": null,
"e": 722,
"s": 650,
"text": "First clone the tool from the Github repo using the following commands."
},
{
"code": null,
"e": 767,
"s": 722,
"text": "git clone https://github.com/boxug/trape.git"
},
{
"code": null,
"e": 788,
"s": 767,
"text": "Change directory by,"
},
{
"code": null,
"e": 797,
"s": 788,
"text": "cd trape"
},
{
"code": null,
"e": 860,
"s": 797,
"text": "Now we need to install some requirements before running trape."
},
{
"code": null,
"e": 892,
"s": 860,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 937,
"s": 892,
"text": "Fig 1: Cloning Trape from GitHub Repository."
},
{
"code": null,
"e": 1015,
"s": 937,
"text": "Run the tool by entering python trape.py -h to check the options it provides."
},
{
"code": null,
"e": 1034,
"s": 1015,
"text": "Fig 2: Trape tool."
},
{
"code": null,
"e": 1195,
"s": 1034,
"text": "Enter the URL on which you want the victim to be redirected when he clicks on it say, we want the victim to be redirected to google.com. So the command will be:"
},
{
"code": null,
"e": 1242,
"s": 1195,
"text": "python trape.py -u https://google.com -p 8080."
},
{
"code": null,
"e": 1289,
"s": 1242,
"text": "Fig 3: Waiting for victim to click on the url."
},
{
"code": null,
"e": 1439,
"s": 1289,
"text": "In the meantime, open the control panel by copying the control panel link in your web browser and sign in with the access key you have been provided."
},
{
"code": null,
"e": 1461,
"s": 1439,
"text": "Fig 4: Control Panel."
},
{
"code": null,
"e": 1688,
"s": 1461,
"text": "Now in the dashboard, we can see, that the victim has clicked on the URL and we can see his public IP, what browser he is using. Click on details on the bottom right to know other things about the victim like his location etc."
},
{
"code": null,
"e": 1712,
"s": 1688,
"text": "FIg 5: Victim’s Report."
},
{
"code": null,
"e": 1848,
"s": 1712,
"text": "Here we can see both the public IP and the local IP of the victim, his operating system, browser, which country and city he resides in."
},
{
"code": null,
"e": 1886,
"s": 1848,
"text": "FIg 6: Victim’s detailed information."
},
{
"code": null,
"e": 1982,
"s": 1886,
"text": "We can also perform social engineering attacks using trape tools like we can generate an alert."
},
{
"code": null,
"e": 2006,
"s": 1982,
"text": "Fig 7: Alert generated."
},
{
"code": null,
"e": 2026,
"s": 2006,
"text": "We can send a file."
},
{
"code": null,
"e": 2057,
"s": 2026,
"text": "Fig 8: Sending file to victim."
},
{
"code": null,
"e": 2102,
"s": 2057,
"text": "We can also redirect him to a phishing page."
},
{
"code": null,
"e": 2145,
"s": 2102,
"text": "Fig 9: Victim redirected to phishing page."
},
{
"code": null,
"e": 2157,
"s": 2145,
"text": "Linux-Tools"
},
{
"code": null,
"e": 2168,
"s": 2157,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2266,
"s": 2168,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2292,
"s": 2266,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2327,
"s": 2292,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2364,
"s": 2327,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2403,
"s": 2364,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2432,
"s": 2403,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2472,
"s": 2432,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2509,
"s": 2472,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2546,
"s": 2509,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2580,
"s": 2546,
"text": "mv command in Linux with examples"
}
] |
Poisson Functions in R Programming
|
05 Oct, 2021
The Poisson distribution represents the probability of a provided number of cases happening in a set period of space or time if these cases happen with an identified constant mean rate (free of the period since the ultimate event). Poisson distribution has been named after Siméon Denis Poisson(French Mathematician). Many probability distributions can be easily implemented in R language with the help of R’s inbuilt functions.There are four Poisson functions available in R:
dpois
ppois
qpois
rpois
Consider a Random Variable X with Poisson distribution given as The mean of this distribution is given by The variance of such a distribution is So if there are ‘n’ which happened out of which the only k were successful when the probability of success is very less then the probability of success becomes
This function is used for illustration of Poisson density in an R plot. The function dpois() calculates the probability of a random variable that is available within a certain range.Syntax: where,
K: number of successful events happened in an interval mean per interval log: If TRUE then the function returns probability in form of log
Example:
Python3
dpois(2, 3)dpois(6, 6)
Output:
[1] 0.2240418
[1] 0.1606231
This function is used for the illustration of cumulative probability function in an R plot. The function ppois() calculates the probability of a random variable that will be equal to or less than a number.Syntax: where,
K: number of successful events happened in an interval mean per interval lower.tail: If TRUE then left tail is considered otherwise if the FALSE right tail is considered log: If TRUE then the function returns probability in form of log
Example:
Python3
ppois(2, 3) ppois(6, 6)
Output:
[1] 0.4231901
[1] 0.6063028
The function rpois() is used for generating random numbers from a given Poisson’s distribution.Syntax: where,
q: number of random numbers needed mean per interval
Example:
Python3
rpois(2, 3)rpois(6, 6)
Output:
[1] 2 3
[1] 6 7 6 10 9 4
The function qpois() is used for generating quantile of a given Poisson’s distribution. In probability, quantiles are marked points that divide the graph of a probability distribution into intervals (continuous ) which have equal probabilities.Syntax: where,
K: number of successful events happened in an interval mean per interval lower.tail: If TRUE then left tail is considered otherwise if the FALSE right tail is considered log: If TRUE then the function returns probability in form of log
Example:
Python3
y <- c(.01, .05, .1, .2)qpois(y, 2)qpois(y, 6)
Output:
[1] 0 0 0 1
[1] 1 2 3 4
kashishsoda
R Machine-Learning
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 508,
"s": 28,
"text": "The Poisson distribution represents the probability of a provided number of cases happening in a set period of space or time if these cases happen with an identified constant mean rate (free of the period since the ultimate event). Poisson distribution has been named after Siméon Denis Poisson(French Mathematician). Many probability distributions can be easily implemented in R language with the help of R’s inbuilt functions.There are four Poisson functions available in R: "
},
{
"code": null,
"e": 514,
"s": 508,
"text": "dpois"
},
{
"code": null,
"e": 520,
"s": 514,
"text": "ppois"
},
{
"code": null,
"e": 526,
"s": 520,
"text": "qpois"
},
{
"code": null,
"e": 532,
"s": 526,
"text": "rpois"
},
{
"code": null,
"e": 838,
"s": 532,
"text": "Consider a Random Variable X with Poisson distribution given as The mean of this distribution is given by The variance of such a distribution is So if there are ‘n’ which happened out of which the only k were successful when the probability of success is very less then the probability of success becomes "
},
{
"code": null,
"e": 1037,
"s": 838,
"text": "This function is used for illustration of Poisson density in an R plot. The function dpois() calculates the probability of a random variable that is available within a certain range.Syntax: where, "
},
{
"code": null,
"e": 1176,
"s": 1037,
"text": "K: number of successful events happened in an interval mean per interval log: If TRUE then the function returns probability in form of log"
},
{
"code": null,
"e": 1187,
"s": 1176,
"text": "Example: "
},
{
"code": null,
"e": 1195,
"s": 1187,
"text": "Python3"
},
{
"code": "dpois(2, 3)dpois(6, 6)",
"e": 1218,
"s": 1195,
"text": null
},
{
"code": null,
"e": 1228,
"s": 1218,
"text": "Output: "
},
{
"code": null,
"e": 1257,
"s": 1228,
"text": "[1] 0.2240418\n\n[1] 0.1606231"
},
{
"code": null,
"e": 1481,
"s": 1259,
"text": "This function is used for the illustration of cumulative probability function in an R plot. The function ppois() calculates the probability of a random variable that will be equal to or less than a number.Syntax: where, "
},
{
"code": null,
"e": 1717,
"s": 1481,
"text": "K: number of successful events happened in an interval mean per interval lower.tail: If TRUE then left tail is considered otherwise if the FALSE right tail is considered log: If TRUE then the function returns probability in form of log"
},
{
"code": null,
"e": 1728,
"s": 1717,
"text": "Example: "
},
{
"code": null,
"e": 1736,
"s": 1728,
"text": "Python3"
},
{
"code": "ppois(2, 3) ppois(6, 6)",
"e": 1760,
"s": 1736,
"text": null
},
{
"code": null,
"e": 1770,
"s": 1760,
"text": "Output: "
},
{
"code": null,
"e": 1798,
"s": 1770,
"text": "[1] 0.4231901\n[1] 0.6063028"
},
{
"code": null,
"e": 1912,
"s": 1800,
"text": "The function rpois() is used for generating random numbers from a given Poisson’s distribution.Syntax: where, "
},
{
"code": null,
"e": 1965,
"s": 1912,
"text": "q: number of random numbers needed mean per interval"
},
{
"code": null,
"e": 1976,
"s": 1965,
"text": "Example: "
},
{
"code": null,
"e": 1984,
"s": 1976,
"text": "Python3"
},
{
"code": "rpois(2, 3)rpois(6, 6)",
"e": 2007,
"s": 1984,
"text": null
},
{
"code": null,
"e": 2017,
"s": 2007,
"text": "Output: "
},
{
"code": null,
"e": 2047,
"s": 2017,
"text": "[1] 2 3\n[1] 6 7 6 10 9 4"
},
{
"code": null,
"e": 2310,
"s": 2049,
"text": "The function qpois() is used for generating quantile of a given Poisson’s distribution. In probability, quantiles are marked points that divide the graph of a probability distribution into intervals (continuous ) which have equal probabilities.Syntax: where, "
},
{
"code": null,
"e": 2546,
"s": 2310,
"text": "K: number of successful events happened in an interval mean per interval lower.tail: If TRUE then left tail is considered otherwise if the FALSE right tail is considered log: If TRUE then the function returns probability in form of log"
},
{
"code": null,
"e": 2557,
"s": 2546,
"text": "Example: "
},
{
"code": null,
"e": 2565,
"s": 2557,
"text": "Python3"
},
{
"code": "y <- c(.01, .05, .1, .2)qpois(y, 2)qpois(y, 6)",
"e": 2612,
"s": 2565,
"text": null
},
{
"code": null,
"e": 2622,
"s": 2612,
"text": "Output: "
},
{
"code": null,
"e": 2646,
"s": 2622,
"text": "[1] 0 0 0 1\n[1] 1 2 3 4"
},
{
"code": null,
"e": 2660,
"s": 2648,
"text": "kashishsoda"
},
{
"code": null,
"e": 2679,
"s": 2660,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 2691,
"s": 2679,
"text": "R-Functions"
},
{
"code": null,
"e": 2702,
"s": 2691,
"text": "R Language"
}
] |
How to Get the Id of a Current Running Thread in Java?
|
11 Nov, 2020
The getId() method of Thread class returns the identifier of the invoked thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.
Java allows concurrent execution of different parts of a program with the help of threads. Multithreading in Java is achieved by extending the Thread class or implementing the Runnable Interface. Since multiple inheritance is not allowed in Java it is recommended to implement the Runnable interface for thread creation so that if required the class implementing the Runnable interface can extend some other class. In this article, we have demonstrated both the methods of creating a thread. The first approach shows thread creation by extending the Thread class and the second approach shows thread creation by implementing the Runnable Interface.
Declaration
public long getId()
Return value: This method returns the ID of a thread.
Approach 1: Following are the steps to create a thread by extending the Thread class.
ThreadDemo1 class extends the Thread class and overrides the run() method of Thread class.In the run() method, we use the currentThread().getName() method to get the name of the current thread that has invoked the run() method.We use the currentThread().getId() method to get the id of the current thread that has invoked the run() method.Within the main() method, two instances of the ThreadDemo1 class is created.t1 and t2 are two threads which invoke the start() method.Invoking the start() method basically invokes the run() method by default.join() method is used to prevent t2 from running before the completion of t1.As soon as t1 completes t2 begins execution.
ThreadDemo1 class extends the Thread class and overrides the run() method of Thread class.
In the run() method, we use the currentThread().getName() method to get the name of the current thread that has invoked the run() method.
We use the currentThread().getId() method to get the id of the current thread that has invoked the run() method.
Within the main() method, two instances of the ThreadDemo1 class is created.
t1 and t2 are two threads which invoke the start() method.
Invoking the start() method basically invokes the run() method by default.
join() method is used to prevent t2 from running before the completion of t1.
As soon as t1 completes t2 begins execution.
Example:
Java
// Java program to get the id of a // thread import java.util.*;public class ThreadDemo1 extends Thread { public void run() { // gets the name of current thread System.out.println( "Current Thread Name: " + Thread.currentThread().getName()); // gets the ID of the current thread System.out.println( "Current Thread ID: " + Thread.currentThread().getId()); } public static void main(String[] args) throws InterruptedException { Scanner s = new Scanner(System.in); // creating first thread ThreadDemo1 t1 = new ThreadDemo1(); // creating second thread ThreadDemo1 t2 = new ThreadDemo1(); // Starting the thread t1.start(); t2.start(); // t2 does not start execution until t1 completes // execution t1.join(); }}
Current Thread Name: Thread-0
Current Thread Name: Thread-1
Current Thread ID: 11
Current Thread ID: 12
Approach 2: In the second approach, the thread is created by implementing the Runnable Interface.
ThreadDemo2 class implements the Runnable interface and overrides the run() method.A runnable instance of ThreadDemo2 class t is created.Two instances of the Thread class are created by passing the runnable instance as the first parameter and the name of the thread as the second parameterstart() method is invoked on both the threadsstart() method invokes the run() method by default
ThreadDemo2 class implements the Runnable interface and overrides the run() method.
A runnable instance of ThreadDemo2 class t is created.
Two instances of the Thread class are created by passing the runnable instance as the first parameter and the name of the thread as the second parameter
start() method is invoked on both the threads
start() method invokes the run() method by default
Example:
Java
// Java program to get the id of a // thread public class ThreadDemo2 implements Runnable { public void run() { // gets the name of current thread System.out.println( "Current Thread Name: " + Thread.currentThread().getName()); // gets the ID of the current thread System.out.println( "Current Thread ID: " + Thread.currentThread().getId()); } public static void main(String[] args) { // Runnable target ThreadDemo2 t = new ThreadDemo2(); // create threads Thread t1 = new Thread(t, "First Thread"); Thread t2 = new Thread(t, "Second Thread"); // start threads t1.start(); t2.start(); }}
Current Thread Name: First Thread
Current Thread Name: Second Thread
Current Thread ID: 11
Current Thread ID: 12
Note: The output may vary for the second approach as it is not synchronized and the threads execute concurrently. So the order in which the thread name or thread id is printed may vary. To prevent this problem we used join() method in the first approach. If the order of the printed output is to be maintained then the user can use the join() method.
Java-Multithreading
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Nov, 2020"
},
{
"code": null,
"e": 339,
"s": 52,
"text": "The getId() method of Thread class returns the identifier of the invoked thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused."
},
{
"code": null,
"e": 988,
"s": 339,
"text": "Java allows concurrent execution of different parts of a program with the help of threads. Multithreading in Java is achieved by extending the Thread class or implementing the Runnable Interface. Since multiple inheritance is not allowed in Java it is recommended to implement the Runnable interface for thread creation so that if required the class implementing the Runnable interface can extend some other class. In this article, we have demonstrated both the methods of creating a thread. The first approach shows thread creation by extending the Thread class and the second approach shows thread creation by implementing the Runnable Interface."
},
{
"code": null,
"e": 1000,
"s": 988,
"text": "Declaration"
},
{
"code": null,
"e": 1021,
"s": 1000,
"text": "public long getId()\n"
},
{
"code": null,
"e": 1075,
"s": 1021,
"text": "Return value: This method returns the ID of a thread."
},
{
"code": null,
"e": 1161,
"s": 1075,
"text": "Approach 1: Following are the steps to create a thread by extending the Thread class."
},
{
"code": null,
"e": 1830,
"s": 1161,
"text": "ThreadDemo1 class extends the Thread class and overrides the run() method of Thread class.In the run() method, we use the currentThread().getName() method to get the name of the current thread that has invoked the run() method.We use the currentThread().getId() method to get the id of the current thread that has invoked the run() method.Within the main() method, two instances of the ThreadDemo1 class is created.t1 and t2 are two threads which invoke the start() method.Invoking the start() method basically invokes the run() method by default.join() method is used to prevent t2 from running before the completion of t1.As soon as t1 completes t2 begins execution."
},
{
"code": null,
"e": 1921,
"s": 1830,
"text": "ThreadDemo1 class extends the Thread class and overrides the run() method of Thread class."
},
{
"code": null,
"e": 2059,
"s": 1921,
"text": "In the run() method, we use the currentThread().getName() method to get the name of the current thread that has invoked the run() method."
},
{
"code": null,
"e": 2172,
"s": 2059,
"text": "We use the currentThread().getId() method to get the id of the current thread that has invoked the run() method."
},
{
"code": null,
"e": 2249,
"s": 2172,
"text": "Within the main() method, two instances of the ThreadDemo1 class is created."
},
{
"code": null,
"e": 2308,
"s": 2249,
"text": "t1 and t2 are two threads which invoke the start() method."
},
{
"code": null,
"e": 2383,
"s": 2308,
"text": "Invoking the start() method basically invokes the run() method by default."
},
{
"code": null,
"e": 2461,
"s": 2383,
"text": "join() method is used to prevent t2 from running before the completion of t1."
},
{
"code": null,
"e": 2506,
"s": 2461,
"text": "As soon as t1 completes t2 begins execution."
},
{
"code": null,
"e": 2515,
"s": 2506,
"text": "Example:"
},
{
"code": null,
"e": 2520,
"s": 2515,
"text": "Java"
},
{
"code": "// Java program to get the id of a // thread import java.util.*;public class ThreadDemo1 extends Thread { public void run() { // gets the name of current thread System.out.println( \"Current Thread Name: \" + Thread.currentThread().getName()); // gets the ID of the current thread System.out.println( \"Current Thread ID: \" + Thread.currentThread().getId()); } public static void main(String[] args) throws InterruptedException { Scanner s = new Scanner(System.in); // creating first thread ThreadDemo1 t1 = new ThreadDemo1(); // creating second thread ThreadDemo1 t2 = new ThreadDemo1(); // Starting the thread t1.start(); t2.start(); // t2 does not start execution until t1 completes // execution t1.join(); }}",
"e": 3445,
"s": 2520,
"text": null
},
{
"code": null,
"e": 3550,
"s": 3445,
"text": "Current Thread Name: Thread-0\nCurrent Thread Name: Thread-1\nCurrent Thread ID: 11\nCurrent Thread ID: 12\n"
},
{
"code": null,
"e": 3648,
"s": 3550,
"text": "Approach 2: In the second approach, the thread is created by implementing the Runnable Interface."
},
{
"code": null,
"e": 4033,
"s": 3648,
"text": "ThreadDemo2 class implements the Runnable interface and overrides the run() method.A runnable instance of ThreadDemo2 class t is created.Two instances of the Thread class are created by passing the runnable instance as the first parameter and the name of the thread as the second parameterstart() method is invoked on both the threadsstart() method invokes the run() method by default"
},
{
"code": null,
"e": 4117,
"s": 4033,
"text": "ThreadDemo2 class implements the Runnable interface and overrides the run() method."
},
{
"code": null,
"e": 4172,
"s": 4117,
"text": "A runnable instance of ThreadDemo2 class t is created."
},
{
"code": null,
"e": 4325,
"s": 4172,
"text": "Two instances of the Thread class are created by passing the runnable instance as the first parameter and the name of the thread as the second parameter"
},
{
"code": null,
"e": 4371,
"s": 4325,
"text": "start() method is invoked on both the threads"
},
{
"code": null,
"e": 4422,
"s": 4371,
"text": "start() method invokes the run() method by default"
},
{
"code": null,
"e": 4431,
"s": 4422,
"text": "Example:"
},
{
"code": null,
"e": 4436,
"s": 4431,
"text": "Java"
},
{
"code": "// Java program to get the id of a // thread public class ThreadDemo2 implements Runnable { public void run() { // gets the name of current thread System.out.println( \"Current Thread Name: \" + Thread.currentThread().getName()); // gets the ID of the current thread System.out.println( \"Current Thread ID: \" + Thread.currentThread().getId()); } public static void main(String[] args) { // Runnable target ThreadDemo2 t = new ThreadDemo2(); // create threads Thread t1 = new Thread(t, \"First Thread\"); Thread t2 = new Thread(t, \"Second Thread\"); // start threads t1.start(); t2.start(); }}",
"e": 5205,
"s": 4436,
"text": null
},
{
"code": null,
"e": 5319,
"s": 5205,
"text": "Current Thread Name: First Thread\nCurrent Thread Name: Second Thread\nCurrent Thread ID: 11\nCurrent Thread ID: 12\n"
},
{
"code": null,
"e": 5670,
"s": 5319,
"text": "Note: The output may vary for the second approach as it is not synchronized and the threads execute concurrently. So the order in which the thread name or thread id is printed may vary. To prevent this problem we used join() method in the first approach. If the order of the printed output is to be maintained then the user can use the join() method."
},
{
"code": null,
"e": 5690,
"s": 5670,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 5714,
"s": 5690,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5719,
"s": 5714,
"text": "Java"
},
{
"code": null,
"e": 5733,
"s": 5719,
"text": "Java Programs"
},
{
"code": null,
"e": 5752,
"s": 5733,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5757,
"s": 5752,
"text": "Java"
},
{
"code": null,
"e": 5855,
"s": 5757,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5870,
"s": 5855,
"text": "Stream In Java"
},
{
"code": null,
"e": 5891,
"s": 5870,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5912,
"s": 5891,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5931,
"s": 5912,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5948,
"s": 5931,
"text": "Generics in Java"
},
{
"code": null,
"e": 5974,
"s": 5948,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 6008,
"s": 5974,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 6055,
"s": 6008,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 6093,
"s": 6055,
"text": "Factory method design pattern in Java"
}
] |
Find most used colors in image using Python
|
16 Oct, 2021
Prerequisite: PIL
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy-to-use library developed by Alex Clark and other contributors. We’ll be working with Pillow.
Let’s understand with step-by-step implementation:
1. Read an image
For reading the image in PIL, we use Image method.
# Read an Image
img = Image.open('File Name')
2. Convert into RGB image
img.convert('RGB')
3. Get Width and Height of Image
width, height = img.size
4. Iterate through all pixels of Image and get R, G, B value from that pixel
for x in range(0, width):
for y in range(0, height):
r, g, b = img.getpixel((x,y))
print(img.getpixel((x,y)))
Output:
(155, 173, 151), (155, 173, 151), (155, 173, 151), (155, 173, 151), (155, 173, 151) ...
5. Initialize three variable
r_total = 0
g_total = 0
b_total = 0
Iterate through all pixel and add each color to different Initialized variable.
r_total = 0
g_total = 0
b_total = 0
for x in range(0, width):
for y in range(0, height):
r, g, b = img.getpixel((x,y))
r_total += r
g_total += g
b_total += b
print(r_total, g_total, b_total)
Output:
(29821623, 32659007, 33290689)
As we can R, G & B value is very large, here we will use count variable
Initialize One More variable
count = 0
Divide total color value by count
Below is the Implementation:
Image Used –
Python3
# Import Modulefrom PIL import Image def most_common_used_color(img): # Get width and height of Image width, height = img.size # Initialize Variable r_total = 0 g_total = 0 b_total = 0 count = 0 # Iterate through each pixel for x in range(0, width): for y in range(0, height): # r,g,b value of pixel r, g, b = img.getpixel((x, y)) r_total += r g_total += g b_total += b count += 1 return (r_total/count, g_total/count, b_total/count) # Read Imageimg = Image.open(r'C:\Users\HP\Desktop\New folder\mix_color.png') # Convert Image into RGBimg = img.convert('RGB') # call functioncommon_color = most_common_used_color(img) print(common_color)# Output is (R, G, B)
Output:
# Most Used color is Blue
(179.6483313253012, 196.74100602409638, 200.54631927710844)
ruhelaa48
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
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": 28,
"s": 0,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 46,
"s": 28,
"text": "Prerequisite: PIL"
},
{
"code": null,
"e": 354,
"s": 46,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy-to-use library developed by Alex Clark and other contributors. We’ll be working with Pillow."
},
{
"code": null,
"e": 405,
"s": 354,
"text": "Let’s understand with step-by-step implementation:"
},
{
"code": null,
"e": 422,
"s": 405,
"text": "1. Read an image"
},
{
"code": null,
"e": 473,
"s": 422,
"text": "For reading the image in PIL, we use Image method."
},
{
"code": null,
"e": 519,
"s": 473,
"text": "# Read an Image\nimg = Image.open('File Name')"
},
{
"code": null,
"e": 545,
"s": 519,
"text": "2. Convert into RGB image"
},
{
"code": null,
"e": 564,
"s": 545,
"text": "img.convert('RGB')"
},
{
"code": null,
"e": 597,
"s": 564,
"text": "3. Get Width and Height of Image"
},
{
"code": null,
"e": 622,
"s": 597,
"text": "width, height = img.size"
},
{
"code": null,
"e": 699,
"s": 622,
"text": "4. Iterate through all pixels of Image and get R, G, B value from that pixel"
},
{
"code": null,
"e": 829,
"s": 699,
"text": "for x in range(0, width):\n for y in range(0, height):\n r, g, b = img.getpixel((x,y))\n print(img.getpixel((x,y)))"
},
{
"code": null,
"e": 837,
"s": 829,
"text": "Output:"
},
{
"code": null,
"e": 925,
"s": 837,
"text": "(155, 173, 151), (155, 173, 151), (155, 173, 151), (155, 173, 151), (155, 173, 151) ..."
},
{
"code": null,
"e": 954,
"s": 925,
"text": "5. Initialize three variable"
},
{
"code": null,
"e": 966,
"s": 954,
"text": "r_total = 0"
},
{
"code": null,
"e": 978,
"s": 966,
"text": "g_total = 0"
},
{
"code": null,
"e": 990,
"s": 978,
"text": "b_total = 0"
},
{
"code": null,
"e": 1070,
"s": 990,
"text": "Iterate through all pixel and add each color to different Initialized variable."
},
{
"code": null,
"e": 1298,
"s": 1070,
"text": "r_total = 0\ng_total = 0\nb_total = 0\n\nfor x in range(0, width):\n for y in range(0, height):\n r, g, b = img.getpixel((x,y))\n r_total += r\n g_total += g\n b_total += b\nprint(r_total, g_total, b_total)"
},
{
"code": null,
"e": 1306,
"s": 1298,
"text": "Output:"
},
{
"code": null,
"e": 1337,
"s": 1306,
"text": "(29821623, 32659007, 33290689)"
},
{
"code": null,
"e": 1409,
"s": 1337,
"text": "As we can R, G & B value is very large, here we will use count variable"
},
{
"code": null,
"e": 1438,
"s": 1409,
"text": "Initialize One More variable"
},
{
"code": null,
"e": 1448,
"s": 1438,
"text": "count = 0"
},
{
"code": null,
"e": 1482,
"s": 1448,
"text": "Divide total color value by count"
},
{
"code": null,
"e": 1511,
"s": 1482,
"text": "Below is the Implementation:"
},
{
"code": null,
"e": 1525,
"s": 1511,
"text": "Image Used – "
},
{
"code": null,
"e": 1533,
"s": 1525,
"text": "Python3"
},
{
"code": "# Import Modulefrom PIL import Image def most_common_used_color(img): # Get width and height of Image width, height = img.size # Initialize Variable r_total = 0 g_total = 0 b_total = 0 count = 0 # Iterate through each pixel for x in range(0, width): for y in range(0, height): # r,g,b value of pixel r, g, b = img.getpixel((x, y)) r_total += r g_total += g b_total += b count += 1 return (r_total/count, g_total/count, b_total/count) # Read Imageimg = Image.open(r'C:\\Users\\HP\\Desktop\\New folder\\mix_color.png') # Convert Image into RGBimg = img.convert('RGB') # call functioncommon_color = most_common_used_color(img) print(common_color)# Output is (R, G, B)",
"e": 2301,
"s": 1533,
"text": null
},
{
"code": null,
"e": 2309,
"s": 2301,
"text": "Output:"
},
{
"code": null,
"e": 2395,
"s": 2309,
"text": "# Most Used color is Blue\n(179.6483313253012, 196.74100602409638, 200.54631927710844)"
},
{
"code": null,
"e": 2405,
"s": 2395,
"text": "ruhelaa48"
},
{
"code": null,
"e": 2416,
"s": 2405,
"text": "Python-pil"
},
{
"code": null,
"e": 2423,
"s": 2416,
"text": "Python"
},
{
"code": null,
"e": 2521,
"s": 2423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2553,
"s": 2521,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2580,
"s": 2553,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2601,
"s": 2580,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2624,
"s": 2601,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2680,
"s": 2624,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2711,
"s": 2680,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2753,
"s": 2711,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2795,
"s": 2753,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2834,
"s": 2795,
"text": "Python | datetime.timedelta() function"
}
] |
KDE Plot Visualization with Pandas and Seaborn
|
06 May, 2019
KDE Plot described as Kernel Density Estimate is used for visualizing the Probability Density of a continuous variable. It depicts the probability density at different values in a continuous variable. We can also plot a single graph for multiple samples which helps in more efficient data visualization.
In this article, we will be using Iris Dataset and KDE Plot to visualize the insights of the dataset.
About the Iris Dataset –
Attributes : Petal_Length (cm), Petal_Width (cm), Sepal_Length (cm), Sepal_Width(cm)Target : Iris_Virginica, Iris_Setosa, Iris_VercicolorNumber of Instances : 150
Attributes : Petal_Length (cm), Petal_Width (cm), Sepal_Length (cm), Sepal_Width(cm)
Target : Iris_Virginica, Iris_Setosa, Iris_Vercicolor
Number of Instances : 150
One-Dimensional KDE Plot :
We can visualize the probability distribution of a sample against a single continuous attribute.
# importing the required librariesfrom sklearn import datasetsimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline # Setting up the Data Frameiris = datasets.load_iris() iris_df = pd.DataFrame(iris.data, columns=['Sepal_Length', 'Sepal_Width', 'Patal_Length', 'Petal_Width']) iris_df['Target'] = iris.target iris_df['Target'].replace([0], 'Iris_Setosa', inplace=True)iris_df['Target'].replace([1], 'Iris_Vercicolor', inplace=True)iris_df['Target'].replace([2], 'Iris_Virginica', inplace=True) # Plotting the KDE Plotsns.kdeplot(iris_df.loc[(iris_df['Target']=='Iris_Virginica'), 'Sepal_Length'], color='b', shade=True, Label='Iris_Virginica') # Setting the X and Y Labelplt.xlabel('Sepal Length')plt.ylabel('Probability Density')
Output:
We can also visualize the probability distribution of multiple samples in a single plot.
# Plotting the KDE Plotsns.kdeplot(iris_df.loc[(iris_df['Target']=='Iris_Setosa'), 'Sepal_Length'], color='r', shade=True, Label='Iris_Setosa') sns.kdeplot(iris_df.loc[(iris_df['Target']=='Iris_Virginica'), 'Sepal_Length'], color='b', shade=True, Label='Iris_Virginica') plt.xlabel('Sepal Length')plt.ylabel('Probability Density')
Output: Two-Dimensional KDE Plot :
We can visualize the probability distribution of a sample against multiple continuous attributes.
# Setting up the samplesiris_setosa = iris_df.query("Target=='Iris_Setosa'")iris_virginica = iris_df.query("Target=='Iris_Virginica'") # Plotting the KDE Plotsns.kdeplot(iris_setosa['Sepal_Length'], iris_setosa['Sepal_Width'], color='r', shade=True, Label='Iris_Setosa', cmap="Reds", shade_lowest=False)
Output:
We can also visualize the probability distribution of multiple samples in a single plot.
# Plotting the KDE Plotsns.kdeplot(iris_setosa['Sepal_Length'], iris_setosa['Sepal_Width'], color='r', shade=True, Label='Iris_Setosa', cmap="Reds", shade_lowest=False) sns.kdeplot(iris_virginica['Sepal_Length'], iris_virginica['Sepal_Width'], color='b', shade=True, Label='Iris_Virginica', cmap="Blues", shade_lowest=False)
Output:
data-science
Python-pandas
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Naive Bayes Classifiers
ML | Linear Regression
Linear Regression (Python Implementation)
Decision Tree
Reinforcement learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 May, 2019"
},
{
"code": null,
"e": 358,
"s": 54,
"text": "KDE Plot described as Kernel Density Estimate is used for visualizing the Probability Density of a continuous variable. It depicts the probability density at different values in a continuous variable. We can also plot a single graph for multiple samples which helps in more efficient data visualization."
},
{
"code": null,
"e": 460,
"s": 358,
"text": "In this article, we will be using Iris Dataset and KDE Plot to visualize the insights of the dataset."
},
{
"code": null,
"e": 485,
"s": 460,
"text": "About the Iris Dataset –"
},
{
"code": null,
"e": 648,
"s": 485,
"text": "Attributes : Petal_Length (cm), Petal_Width (cm), Sepal_Length (cm), Sepal_Width(cm)Target : Iris_Virginica, Iris_Setosa, Iris_VercicolorNumber of Instances : 150"
},
{
"code": null,
"e": 733,
"s": 648,
"text": "Attributes : Petal_Length (cm), Petal_Width (cm), Sepal_Length (cm), Sepal_Width(cm)"
},
{
"code": null,
"e": 787,
"s": 733,
"text": "Target : Iris_Virginica, Iris_Setosa, Iris_Vercicolor"
},
{
"code": null,
"e": 813,
"s": 787,
"text": "Number of Instances : 150"
},
{
"code": null,
"e": 840,
"s": 813,
"text": "One-Dimensional KDE Plot :"
},
{
"code": null,
"e": 937,
"s": 840,
"text": "We can visualize the probability distribution of a sample against a single continuous attribute."
},
{
"code": "# importing the required librariesfrom sklearn import datasetsimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline # Setting up the Data Frameiris = datasets.load_iris() iris_df = pd.DataFrame(iris.data, columns=['Sepal_Length', 'Sepal_Width', 'Patal_Length', 'Petal_Width']) iris_df['Target'] = iris.target iris_df['Target'].replace([0], 'Iris_Setosa', inplace=True)iris_df['Target'].replace([1], 'Iris_Vercicolor', inplace=True)iris_df['Target'].replace([2], 'Iris_Virginica', inplace=True) # Plotting the KDE Plotsns.kdeplot(iris_df.loc[(iris_df['Target']=='Iris_Virginica'), 'Sepal_Length'], color='b', shade=True, Label='Iris_Virginica') # Setting the X and Y Labelplt.xlabel('Sepal Length')plt.ylabel('Probability Density')",
"e": 1742,
"s": 937,
"text": null
},
{
"code": null,
"e": 1750,
"s": 1742,
"text": "Output:"
},
{
"code": null,
"e": 1839,
"s": 1750,
"text": "We can also visualize the probability distribution of multiple samples in a single plot."
},
{
"code": "# Plotting the KDE Plotsns.kdeplot(iris_df.loc[(iris_df['Target']=='Iris_Setosa'), 'Sepal_Length'], color='r', shade=True, Label='Iris_Setosa') sns.kdeplot(iris_df.loc[(iris_df['Target']=='Iris_Virginica'), 'Sepal_Length'], color='b', shade=True, Label='Iris_Virginica') plt.xlabel('Sepal Length')plt.ylabel('Probability Density')",
"e": 2195,
"s": 1839,
"text": null
},
{
"code": null,
"e": 2230,
"s": 2195,
"text": "Output: Two-Dimensional KDE Plot :"
},
{
"code": null,
"e": 2328,
"s": 2230,
"text": "We can visualize the probability distribution of a sample against multiple continuous attributes."
},
{
"code": "# Setting up the samplesiris_setosa = iris_df.query(\"Target=='Iris_Setosa'\")iris_virginica = iris_df.query(\"Target=='Iris_Virginica'\") # Plotting the KDE Plotsns.kdeplot(iris_setosa['Sepal_Length'], iris_setosa['Sepal_Width'], color='r', shade=True, Label='Iris_Setosa', cmap=\"Reds\", shade_lowest=False)",
"e": 2667,
"s": 2328,
"text": null
},
{
"code": null,
"e": 2675,
"s": 2667,
"text": "Output:"
},
{
"code": null,
"e": 2764,
"s": 2675,
"text": "We can also visualize the probability distribution of multiple samples in a single plot."
},
{
"code": "# Plotting the KDE Plotsns.kdeplot(iris_setosa['Sepal_Length'], iris_setosa['Sepal_Width'], color='r', shade=True, Label='Iris_Setosa', cmap=\"Reds\", shade_lowest=False) sns.kdeplot(iris_virginica['Sepal_Length'], iris_virginica['Sepal_Width'], color='b', shade=True, Label='Iris_Virginica', cmap=\"Blues\", shade_lowest=False)",
"e": 3157,
"s": 2764,
"text": null
},
{
"code": null,
"e": 3165,
"s": 3157,
"text": "Output:"
},
{
"code": null,
"e": 3178,
"s": 3165,
"text": "data-science"
},
{
"code": null,
"e": 3192,
"s": 3178,
"text": "Python-pandas"
},
{
"code": null,
"e": 3209,
"s": 3192,
"text": "Machine Learning"
},
{
"code": null,
"e": 3216,
"s": 3209,
"text": "Python"
},
{
"code": null,
"e": 3233,
"s": 3216,
"text": "Machine Learning"
},
{
"code": null,
"e": 3331,
"s": 3233,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3355,
"s": 3331,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 3378,
"s": 3355,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 3420,
"s": 3378,
"text": "Linear Regression (Python Implementation)"
},
{
"code": null,
"e": 3434,
"s": 3420,
"text": "Decision Tree"
},
{
"code": null,
"e": 3457,
"s": 3434,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 3485,
"s": 3457,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3535,
"s": 3485,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3557,
"s": 3535,
"text": "Python map() function"
}
] |
Generate all binary strings without consecutive 1’s
|
06 Jul, 2022
Given an integer K. Task is Print All binary string of size K (Given number).
Examples:
Input : K = 3
Output : 000 , 001 , 010 , 100 , 101
Input : K = 4
Output :0000 0001 0010 0100 0101 1000 1001 1010
Idea behind that is IF string ends with ‘1’ then we put only ‘0’ at the end. IF string ends with ‘0’ then we put both ‘0’ and ‘1’ at the end of string for generating new string.
Below is algorithm
K : size of string
First We Generate All string starts with '0'
initialize n = 1 .
GenerateALLString ( K , Str , n )
a. IF n == K
PRINT str.
b. IF previous character is '1' :: str[n-1] == '1'
put str[n] = '0'
GenerateAllString ( K , str , n+1 )
c. IF previous character is '0' :: str[n-1] == '0'
First We Put zero at end and call function
PUT str[n] = '0'
GenerateAllString ( K , str , n+1 )
PUT str[n] = '1'
GenerateAllString ( K , str , n+1 )
Second Generate all binary string starts with '1'
DO THE SAME PROCESS
Below is the recursive implementation:
C++
Java
Python3
C#
Javascript
// C++ program to Generate// all binary string without// consecutive 1's of size K#include<bits/stdc++.h>using namespace std ; // A utility function generate all string without// consecutive 1'sof size Kvoid generateAllStringsUtil(int K, char str[], int n){ // Print binary string without consecutive 1's if (n == K) { // Terminate binary string str[n] = '\0' ; cout << str << " "; return ; } // If previous character is '1' then we put // only 0 at end of string //example str = "01" then new string be "010" if (str[n-1] == '1') { str[n] = '0'; generateAllStringsUtil (K , str , n+1); } // If previous character is '0' than we put // both '1' and '0' at end of string // example str = "00" then // new string "001" and "000" if (str[n-1] == '0') { str[n] = '0'; generateAllStringsUtil(K, str, n+1); str[n] = '1'; generateAllStringsUtil(K, str, n+1) ; }} // Function generate all binary string without// consecutive 1'svoid generateAllStrings(int K ){ // Base case if (K <= 0) return ; // One by one stores every // binary string of length K char str[K]; // Generate all Binary string // starts with '0' str[0] = '0' ; generateAllStringsUtil ( K , str , 1 ) ; // Generate all Binary string // starts with '1' str[0] = '1' ; generateAllStringsUtil ( K , str , 1 );} // Driver program to test above functionint main(){ int K = 3; generateAllStrings (K) ; return 0;}
// Java program to Generate all binary string without// consecutive 1's of size Kimport java.util.*;import java.lang.*; public class BinaryS { // Array conversion to String-- public static String toString(char[] a) { String string = new String(a); return string; } static void generate(int k, char[] ch, int n) { // Base Condition when we // reached at the end of Array** if (n == k) { // Printing the Generated String** // Return to the previous case* System.out.print(toString(ch)+" "); return; } // If the first Character is //Zero then adding** if (ch[n - 1] == '0') { ch[n] = '0'; generate(k, ch, n + 1); ch[n] = '1'; generate(k, ch, n + 1); } // If the Character is One // then add Zero to next** if (ch[n - 1] == '1') { ch[n] = '0'; // Calling Recursively for the // next value of Array generate(k, ch, n + 1); } } static void fun(int k) { if (k <= 0) { return; } char[] ch = new char[k]; // Initializing first character to Zero ch[0] = '0'; // Generating Strings starting with Zero-- generate(k, ch, 1); // Initialized first Character to one-- ch[0] = '1'; generate(k, ch, 1); } public static void main(String args[]) { int k = 3; //Calling function fun with argument k fun(k); //This code is Contributed by Praveen Tiwari }}
# Python3 program to Generate all binary string# without consecutive 1's of size K # A utility function generate all string without# consecutive 1'sof size Kdef generateAllStringsUtil(K, str, n): # print binary string without consecutive 1's if (n == K): # terminate binary string print(*str[:n], sep = "", end = " ") return # if previous character is '1' then we put # only 0 at end of string # example str = "01" then new string be "000" if (str[n-1] == '1'): str[n] = '0' generateAllStringsUtil (K, str, n + 1) # if previous character is '0' than we put # both '1' and '0' at end of string # example str = "00" then new string "001" and "000" if (str[n-1] == '0'): str[n] = '0' generateAllStringsUtil(K, str, n + 1) str[n] = '1' generateAllStringsUtil(K, str, n + 1) # function generate all binary string without# consecutive 1'sdef generateAllStrings(K): # Base case if (K <= 0): return # One by one stores every # binary string of length K str = [0] * K # Generate all Binary string starts with '0' str[0] = '0' generateAllStringsUtil (K, str, 1) # Generate all Binary string starts with '1' str[0] = '1' generateAllStringsUtil (K, str, 1) # Driver codeK = 3generateAllStrings (K) # This code is contributed by SHUBHAMSINGH10
// C# program to Generate// all binary string without// consecutive 1's of size Kusing System;class GFG { // Array conversion to String-- static string toString(char[] a) { string String = new string(a); return String; } static void generate(int k, char[] ch, int n) { // Base Condition when we // reached at the end of Array** if (n == k) { // Printing the Generated String** // Return to the previous case* Console.Write(toString(ch)+" "); return; } // If the first Character is //Zero then adding** if (ch[n - 1] == '0') { ch[n] = '0'; generate(k, ch, n + 1); ch[n] = '1'; generate(k, ch, n + 1); } // If the Character is One // then add Zero to next** if (ch[n - 1] == '1') { ch[n] = '0'; // Calling Recursively for the // next value of Array generate(k, ch, n + 1); } } static void fun(int k) { if (k <= 0) { return; } char[] ch = new char[k]; // Initializing first character to Zero ch[0] = '0'; // Generating Strings starting with Zero-- generate(k, ch, 1); // Initialized first Character to one-- ch[0] = '1'; generate(k, ch, 1); } // Driver code static void Main() { int k = 3; //Calling function fun with argument k fun(k); }} // This code is contributed by divyeshrabadiya07.
<script>// Javascript implementation // A utility function generate all string without// consecutive 1'sof size Kfunction generateAllStringsUtil(K, str, n){ // Print binary string without consecutive 1's if (n == K) { // Terminate binary string str[n] = '\0' ; document.write(str.join("") + " "); return ; } // If previous character is '1' then we put // only 0 at end of string //example str = "01" then new string be "010" if (str[n-1] == '1') { str[n] = '0'; generateAllStringsUtil (K , str , n+1); } // If previous character is '0' than we put // both '1' and '0' at end of string // example str = "00" then // new string "001" and "000" if (str[n-1] == '0') { str[n] = '0'; generateAllStringsUtil(K, str, n+1); str[n] = '1'; generateAllStringsUtil(K, str, n+1) ; }} // Function generate all binary string without// consecutive 1'sfunction generateAllStrings(K ){ // Base case if (K <= 0) return ; // One by one stores every // binary string of length K var str = new Array(K); // Generate all Binary string // starts with '0' str[0] = '0' ; generateAllStringsUtil ( K , str , 1 ) ; // Generate all Binary string // starts with '1' str[0] = '1' ; generateAllStringsUtil ( K , str , 1 );} /* Driver code */var K = 3;generateAllStrings(K); // This is code is contributed// by shivani</script>
000 001 010 100 101
This problem is solved by using a recursion tree having two possibilities 0 or 1 just like selecting elements in a subsequence.
So we can also implement above approach using boolean array as well.
C++14
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; void All_Binary_Strings(bool arr[],int num,int r){ if(r==num) { for(int i=0;i<num;i++) cout<<arr[i]; cout<<" "; return; } else if(arr[r-1]) { arr[r]=0; All_Binary_Strings(arr,num,r+1); } else { arr[r]=0; All_Binary_Strings(arr,num,r+1); arr[r]=1; All_Binary_Strings(arr,num,r+1); }} void print(bool a[],int& num){ a[0]=0; All_Binary_Strings(a,num,1); a[0]=1; All_Binary_Strings(a,num,1);} //driver's codeint main(){ int n=2; bool a[n]; print(a,n); return 0;}
/*package whatever //do not write package name here */ import java.io.*; class GFG { static void All_Binary_Strings(int arr[],int num,int r){ if(r == num) { for(int i = 0; i < num; i++) System.out.print(arr[i]); System.out.print(" "); return; } else if(arr[r-1] == 1) { arr[r] = 0; All_Binary_Strings(arr,num,r+1); } else { arr[r] = 0; All_Binary_Strings(arr,num,r+1); arr[r] = 1; All_Binary_Strings(arr,num,r+1); }} static void print(int a[],int num){ a[0] = 0; All_Binary_Strings(a,num,1); a[0] = 1; All_Binary_Strings(a,num,1);} // Driver codepublic static void main(String args[]){ int n = 2; int a[] = new int[n]; print(a,n);}} // This code is contributed by shinjanpatra.
def All_Binary_Strings(arr,num,r): if(r == num): for i in range(num): print(arr[i],end="") print(end=" ") return elif(arr[r-1]): arr[r] = 0 All_Binary_Strings(arr, num, r + 1) else: arr[r] = 0 All_Binary_Strings(arr,num,r+1) arr[r] = 1 All_Binary_Strings(arr,num,r+1) def Print(a,num): a[0] = 0 All_Binary_Strings(a,num,1) a[0] = 1 All_Binary_Strings(a,num,1) # driver's code n = 2a = [False for i in range(n)]Print(a,n) # This code is contributed by shinjanpatra
// C# program to Generate// all binary string withoutusing System; public static class GFG { public static void All_Binary_Strings(int[] arr, int num, int r) { if (r == num) { for (int i = 0; i < num; i++) { Console.Write(arr[i]); } Console.Write(" "); return; } else if (arr[r - 1] == 1) { arr[r] = 0; All_Binary_Strings(arr, num, r + 1); } else { arr[r] = 0; All_Binary_Strings(arr, num, r + 1); arr[r] = 1; All_Binary_Strings(arr, num, r + 1); } } public static void print(int[] a, ref int num) { a[0] = 0; All_Binary_Strings(a, num, 1); a[0] = 1; All_Binary_Strings(a, num, 1); } // driver's code public static void Main() { int n = 2; int[] a = new int[n]; print(a, ref n); }} // This code is contributed by Aarti_Rathi
<script> function All_Binary_Strings(arr,num,r){ if(r == num) { for(let i = 0; i < num; i++) document.write(arr[i]); document.write(" "); return; } else if(arr[r-1]) { arr[r] = 0; All_Binary_Strings(arr, num, r + 1); } else { arr[r] = 0; All_Binary_Strings(arr,num,r+1); arr[r] = 1; All_Binary_Strings(arr,num,r+1); }} function print(a,num){ a[0] = 0; All_Binary_Strings(a,num,1); a[0] = 1; All_Binary_Strings(a,num,1);} // driver's code let n=2;let a = new Array(n).fill(false);print(a,n); // This code is contributed by shinjanpatra</script>
00 01 10
The above approach can also be solved using string. It does not have any effect on complexity but string handling, printing and operating is easy.
C++14
Python3
Javascript
#include <bits/stdc++.h>using namespace std; void All_Binary_Strings(string str,int num){ int len=str.length(); if(len==num) { cout<<str<<" "; return; } else if(str[len-1]=='1') All_Binary_Strings(str+'0',num); else { All_Binary_Strings(str+'0',num); All_Binary_Strings(str+'1',num); }} void print(int& num){ string word; word.push_back('0'); All_Binary_Strings(word,num); word[0]='1'; All_Binary_Strings(word,num);} //driver's codeint main(){ int n=4; print(n); return 0;}
def All_Binary_Strings(str,num): Len = len(str) if(Len == num): print(str,end = " ") return elif(str[Len - 1]=='1'): All_Binary_Strings(str+'0',num) else: All_Binary_Strings(str+'0',num) All_Binary_Strings(str+'1',num) def Print(num): word = "" word += '0' All_Binary_Strings(word,num) word = '1' All_Binary_Strings(word,num) # Driver's coden = 4Print(n) # This code is contributed by shinjanpatra.
<script> function All_Binary_Strings(str,num){ let len = str.length; if(len == num) { document.write(str," "); return; } else if(str[len - 1]=='1') All_Binary_Strings(str+'0',num); else { All_Binary_Strings(str+'0',num); All_Binary_Strings(str+'1',num); }} function print(num){ let word = ""; word += '0'; All_Binary_Strings(word,num); word = '1'; All_Binary_Strings(word,num);} // driver's code let n = 4;print(n); // This code is contributed by shinjanpatra.</script>
0000 0001 0010 0100 0101 1000 1001 1010
Time Complexity: O(2^n)Auxiliary Space: O(n)
This article is contributed by Nishant Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
SHUBHAMSINGH10
atharvakango
praveentiwari27
divyeshrabadiya07
shivanisinghss2110
arorakashish0911
prophet1999
shinjanpatra
_shinchancode
hardikkoriintern
Recursion
Strings
Strings
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
Print all subsequences of a string
Recursive Practice Problems with Solutions
Reverse a stack using recursion
Write a program to reverse digits of a number
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Different Methods to Reverse a String in C++
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 132,
"s": 54,
"text": "Given an integer K. Task is Print All binary string of size K (Given number)."
},
{
"code": null,
"e": 143,
"s": 132,
"text": "Examples: "
},
{
"code": null,
"e": 262,
"s": 143,
"text": "Input : K = 3 \nOutput : 000 , 001 , 010 , 100 , 101 \n\nInput : K = 4 \nOutput :0000 0001 0010 0100 0101 1000 1001 1010"
},
{
"code": null,
"e": 440,
"s": 262,
"text": "Idea behind that is IF string ends with ‘1’ then we put only ‘0’ at the end. IF string ends with ‘0’ then we put both ‘0’ and ‘1’ at the end of string for generating new string."
},
{
"code": null,
"e": 461,
"s": 440,
"text": "Below is algorithm "
},
{
"code": null,
"e": 1046,
"s": 461,
"text": "K : size of string \nFirst We Generate All string starts with '0'\ninitialize n = 1 . \nGenerateALLString ( K , Str , n )\n a. IF n == K \n PRINT str.\n b. IF previous character is '1' :: str[n-1] == '1'\n put str[n] = '0'\n GenerateAllString ( K , str , n+1 )\n c. IF previous character is '0' :: str[n-1] == '0'\n First We Put zero at end and call function \n PUT str[n] = '0'\n GenerateAllString ( K , str , n+1 ) \n PUT str[n] = '1'\n GenerateAllString ( K , str , n+1 )\n\nSecond Generate all binary string starts with '1'\nDO THE SAME PROCESS"
},
{
"code": null,
"e": 1086,
"s": 1046,
"text": "Below is the recursive implementation: "
},
{
"code": null,
"e": 1090,
"s": 1086,
"text": "C++"
},
{
"code": null,
"e": 1095,
"s": 1090,
"text": "Java"
},
{
"code": null,
"e": 1103,
"s": 1095,
"text": "Python3"
},
{
"code": null,
"e": 1106,
"s": 1103,
"text": "C#"
},
{
"code": null,
"e": 1117,
"s": 1106,
"text": "Javascript"
},
{
"code": "// C++ program to Generate// all binary string without// consecutive 1's of size K#include<bits/stdc++.h>using namespace std ; // A utility function generate all string without// consecutive 1'sof size Kvoid generateAllStringsUtil(int K, char str[], int n){ // Print binary string without consecutive 1's if (n == K) { // Terminate binary string str[n] = '\\0' ; cout << str << \" \"; return ; } // If previous character is '1' then we put // only 0 at end of string //example str = \"01\" then new string be \"010\" if (str[n-1] == '1') { str[n] = '0'; generateAllStringsUtil (K , str , n+1); } // If previous character is '0' than we put // both '1' and '0' at end of string // example str = \"00\" then // new string \"001\" and \"000\" if (str[n-1] == '0') { str[n] = '0'; generateAllStringsUtil(K, str, n+1); str[n] = '1'; generateAllStringsUtil(K, str, n+1) ; }} // Function generate all binary string without// consecutive 1'svoid generateAllStrings(int K ){ // Base case if (K <= 0) return ; // One by one stores every // binary string of length K char str[K]; // Generate all Binary string // starts with '0' str[0] = '0' ; generateAllStringsUtil ( K , str , 1 ) ; // Generate all Binary string // starts with '1' str[0] = '1' ; generateAllStringsUtil ( K , str , 1 );} // Driver program to test above functionint main(){ int K = 3; generateAllStrings (K) ; return 0;}",
"e": 2678,
"s": 1117,
"text": null
},
{
"code": "// Java program to Generate all binary string without// consecutive 1's of size Kimport java.util.*;import java.lang.*; public class BinaryS { // Array conversion to String-- public static String toString(char[] a) { String string = new String(a); return string; } static void generate(int k, char[] ch, int n) { // Base Condition when we // reached at the end of Array** if (n == k) { // Printing the Generated String** // Return to the previous case* System.out.print(toString(ch)+\" \"); return; } // If the first Character is //Zero then adding** if (ch[n - 1] == '0') { ch[n] = '0'; generate(k, ch, n + 1); ch[n] = '1'; generate(k, ch, n + 1); } // If the Character is One // then add Zero to next** if (ch[n - 1] == '1') { ch[n] = '0'; // Calling Recursively for the // next value of Array generate(k, ch, n + 1); } } static void fun(int k) { if (k <= 0) { return; } char[] ch = new char[k]; // Initializing first character to Zero ch[0] = '0'; // Generating Strings starting with Zero-- generate(k, ch, 1); // Initialized first Character to one-- ch[0] = '1'; generate(k, ch, 1); } public static void main(String args[]) { int k = 3; //Calling function fun with argument k fun(k); //This code is Contributed by Praveen Tiwari }}",
"e": 4361,
"s": 2678,
"text": null
},
{
"code": "# Python3 program to Generate all binary string# without consecutive 1's of size K # A utility function generate all string without# consecutive 1'sof size Kdef generateAllStringsUtil(K, str, n): # print binary string without consecutive 1's if (n == K): # terminate binary string print(*str[:n], sep = \"\", end = \" \") return # if previous character is '1' then we put # only 0 at end of string # example str = \"01\" then new string be \"000\" if (str[n-1] == '1'): str[n] = '0' generateAllStringsUtil (K, str, n + 1) # if previous character is '0' than we put # both '1' and '0' at end of string # example str = \"00\" then new string \"001\" and \"000\" if (str[n-1] == '0'): str[n] = '0' generateAllStringsUtil(K, str, n + 1) str[n] = '1' generateAllStringsUtil(K, str, n + 1) # function generate all binary string without# consecutive 1'sdef generateAllStrings(K): # Base case if (K <= 0): return # One by one stores every # binary string of length K str = [0] * K # Generate all Binary string starts with '0' str[0] = '0' generateAllStringsUtil (K, str, 1) # Generate all Binary string starts with '1' str[0] = '1' generateAllStringsUtil (K, str, 1) # Driver codeK = 3generateAllStrings (K) # This code is contributed by SHUBHAMSINGH10",
"e": 5781,
"s": 4361,
"text": null
},
{
"code": "// C# program to Generate// all binary string without// consecutive 1's of size Kusing System;class GFG { // Array conversion to String-- static string toString(char[] a) { string String = new string(a); return String; } static void generate(int k, char[] ch, int n) { // Base Condition when we // reached at the end of Array** if (n == k) { // Printing the Generated String** // Return to the previous case* Console.Write(toString(ch)+\" \"); return; } // If the first Character is //Zero then adding** if (ch[n - 1] == '0') { ch[n] = '0'; generate(k, ch, n + 1); ch[n] = '1'; generate(k, ch, n + 1); } // If the Character is One // then add Zero to next** if (ch[n - 1] == '1') { ch[n] = '0'; // Calling Recursively for the // next value of Array generate(k, ch, n + 1); } } static void fun(int k) { if (k <= 0) { return; } char[] ch = new char[k]; // Initializing first character to Zero ch[0] = '0'; // Generating Strings starting with Zero-- generate(k, ch, 1); // Initialized first Character to one-- ch[0] = '1'; generate(k, ch, 1); } // Driver code static void Main() { int k = 3; //Calling function fun with argument k fun(k); }} // This code is contributed by divyeshrabadiya07.",
"e": 7146,
"s": 5781,
"text": null
},
{
"code": "<script>// Javascript implementation // A utility function generate all string without// consecutive 1'sof size Kfunction generateAllStringsUtil(K, str, n){ // Print binary string without consecutive 1's if (n == K) { // Terminate binary string str[n] = '\\0' ; document.write(str.join(\"\") + \" \"); return ; } // If previous character is '1' then we put // only 0 at end of string //example str = \"01\" then new string be \"010\" if (str[n-1] == '1') { str[n] = '0'; generateAllStringsUtil (K , str , n+1); } // If previous character is '0' than we put // both '1' and '0' at end of string // example str = \"00\" then // new string \"001\" and \"000\" if (str[n-1] == '0') { str[n] = '0'; generateAllStringsUtil(K, str, n+1); str[n] = '1'; generateAllStringsUtil(K, str, n+1) ; }} // Function generate all binary string without// consecutive 1'sfunction generateAllStrings(K ){ // Base case if (K <= 0) return ; // One by one stores every // binary string of length K var str = new Array(K); // Generate all Binary string // starts with '0' str[0] = '0' ; generateAllStringsUtil ( K , str , 1 ) ; // Generate all Binary string // starts with '1' str[0] = '1' ; generateAllStringsUtil ( K , str , 1 );} /* Driver code */var K = 3;generateAllStrings(K); // This is code is contributed// by shivani</script>",
"e": 8636,
"s": 7146,
"text": null
},
{
"code": null,
"e": 8657,
"s": 8636,
"text": "000 001 010 100 101 "
},
{
"code": null,
"e": 8785,
"s": 8657,
"text": "This problem is solved by using a recursion tree having two possibilities 0 or 1 just like selecting elements in a subsequence."
},
{
"code": null,
"e": 8854,
"s": 8785,
"text": "So we can also implement above approach using boolean array as well."
},
{
"code": null,
"e": 8860,
"s": 8854,
"text": "C++14"
},
{
"code": null,
"e": 8865,
"s": 8860,
"text": "Java"
},
{
"code": null,
"e": 8873,
"s": 8865,
"text": "Python3"
},
{
"code": null,
"e": 8876,
"s": 8873,
"text": "C#"
},
{
"code": null,
"e": 8887,
"s": 8876,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void All_Binary_Strings(bool arr[],int num,int r){ if(r==num) { for(int i=0;i<num;i++) cout<<arr[i]; cout<<\" \"; return; } else if(arr[r-1]) { arr[r]=0; All_Binary_Strings(arr,num,r+1); } else { arr[r]=0; All_Binary_Strings(arr,num,r+1); arr[r]=1; All_Binary_Strings(arr,num,r+1); }} void print(bool a[],int& num){ a[0]=0; All_Binary_Strings(a,num,1); a[0]=1; All_Binary_Strings(a,num,1);} //driver's codeint main(){ int n=2; bool a[n]; print(a,n); return 0;}",
"e": 9514,
"s": 8887,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { static void All_Binary_Strings(int arr[],int num,int r){ if(r == num) { for(int i = 0; i < num; i++) System.out.print(arr[i]); System.out.print(\" \"); return; } else if(arr[r-1] == 1) { arr[r] = 0; All_Binary_Strings(arr,num,r+1); } else { arr[r] = 0; All_Binary_Strings(arr,num,r+1); arr[r] = 1; All_Binary_Strings(arr,num,r+1); }} static void print(int a[],int num){ a[0] = 0; All_Binary_Strings(a,num,1); a[0] = 1; All_Binary_Strings(a,num,1);} // Driver codepublic static void main(String args[]){ int n = 2; int a[] = new int[n]; print(a,n);}} // This code is contributed by shinjanpatra.",
"e": 10330,
"s": 9514,
"text": null
},
{
"code": "def All_Binary_Strings(arr,num,r): if(r == num): for i in range(num): print(arr[i],end=\"\") print(end=\" \") return elif(arr[r-1]): arr[r] = 0 All_Binary_Strings(arr, num, r + 1) else: arr[r] = 0 All_Binary_Strings(arr,num,r+1) arr[r] = 1 All_Binary_Strings(arr,num,r+1) def Print(a,num): a[0] = 0 All_Binary_Strings(a,num,1) a[0] = 1 All_Binary_Strings(a,num,1) # driver's code n = 2a = [False for i in range(n)]Print(a,n) # This code is contributed by shinjanpatra",
"e": 10905,
"s": 10330,
"text": null
},
{
"code": "// C# program to Generate// all binary string withoutusing System; public static class GFG { public static void All_Binary_Strings(int[] arr, int num, int r) { if (r == num) { for (int i = 0; i < num; i++) { Console.Write(arr[i]); } Console.Write(\" \"); return; } else if (arr[r - 1] == 1) { arr[r] = 0; All_Binary_Strings(arr, num, r + 1); } else { arr[r] = 0; All_Binary_Strings(arr, num, r + 1); arr[r] = 1; All_Binary_Strings(arr, num, r + 1); } } public static void print(int[] a, ref int num) { a[0] = 0; All_Binary_Strings(a, num, 1); a[0] = 1; All_Binary_Strings(a, num, 1); } // driver's code public static void Main() { int n = 2; int[] a = new int[n]; print(a, ref n); }} // This code is contributed by Aarti_Rathi",
"e": 11920,
"s": 10905,
"text": null
},
{
"code": "<script> function All_Binary_Strings(arr,num,r){ if(r == num) { for(let i = 0; i < num; i++) document.write(arr[i]); document.write(\" \"); return; } else if(arr[r-1]) { arr[r] = 0; All_Binary_Strings(arr, num, r + 1); } else { arr[r] = 0; All_Binary_Strings(arr,num,r+1); arr[r] = 1; All_Binary_Strings(arr,num,r+1); }} function print(a,num){ a[0] = 0; All_Binary_Strings(a,num,1); a[0] = 1; All_Binary_Strings(a,num,1);} // driver's code let n=2;let a = new Array(n).fill(false);print(a,n); // This code is contributed by shinjanpatra</script>",
"e": 12575,
"s": 11920,
"text": null
},
{
"code": null,
"e": 12585,
"s": 12575,
"text": "00 01 10 "
},
{
"code": null,
"e": 12732,
"s": 12585,
"text": "The above approach can also be solved using string. It does not have any effect on complexity but string handling, printing and operating is easy."
},
{
"code": null,
"e": 12738,
"s": 12732,
"text": "C++14"
},
{
"code": null,
"e": 12746,
"s": 12738,
"text": "Python3"
},
{
"code": null,
"e": 12757,
"s": 12746,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void All_Binary_Strings(string str,int num){ int len=str.length(); if(len==num) { cout<<str<<\" \"; return; } else if(str[len-1]=='1') All_Binary_Strings(str+'0',num); else { All_Binary_Strings(str+'0',num); All_Binary_Strings(str+'1',num); }} void print(int& num){ string word; word.push_back('0'); All_Binary_Strings(word,num); word[0]='1'; All_Binary_Strings(word,num);} //driver's codeint main(){ int n=4; print(n); return 0;}",
"e": 13314,
"s": 12757,
"text": null
},
{
"code": "def All_Binary_Strings(str,num): Len = len(str) if(Len == num): print(str,end = \" \") return elif(str[Len - 1]=='1'): All_Binary_Strings(str+'0',num) else: All_Binary_Strings(str+'0',num) All_Binary_Strings(str+'1',num) def Print(num): word = \"\" word += '0' All_Binary_Strings(word,num) word = '1' All_Binary_Strings(word,num) # Driver's coden = 4Print(n) # This code is contributed by shinjanpatra.",
"e": 13778,
"s": 13314,
"text": null
},
{
"code": "<script> function All_Binary_Strings(str,num){ let len = str.length; if(len == num) { document.write(str,\" \"); return; } else if(str[len - 1]=='1') All_Binary_Strings(str+'0',num); else { All_Binary_Strings(str+'0',num); All_Binary_Strings(str+'1',num); }} function print(num){ let word = \"\"; word += '0'; All_Binary_Strings(word,num); word = '1'; All_Binary_Strings(word,num);} // driver's code let n = 4;print(n); // This code is contributed by shinjanpatra.</script>",
"e": 14322,
"s": 13778,
"text": null
},
{
"code": null,
"e": 14363,
"s": 14322,
"text": "0000 0001 0010 0100 0101 1000 1001 1010 "
},
{
"code": null,
"e": 14408,
"s": 14363,
"text": "Time Complexity: O(2^n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 14706,
"s": 14408,
"text": "This article is contributed by Nishant Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 14721,
"s": 14706,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 14734,
"s": 14721,
"text": "atharvakango"
},
{
"code": null,
"e": 14750,
"s": 14734,
"text": "praveentiwari27"
},
{
"code": null,
"e": 14768,
"s": 14750,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 14787,
"s": 14768,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 14804,
"s": 14787,
"text": "arorakashish0911"
},
{
"code": null,
"e": 14816,
"s": 14804,
"text": "prophet1999"
},
{
"code": null,
"e": 14829,
"s": 14816,
"text": "shinjanpatra"
},
{
"code": null,
"e": 14843,
"s": 14829,
"text": "_shinchancode"
},
{
"code": null,
"e": 14860,
"s": 14843,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 14870,
"s": 14860,
"text": "Recursion"
},
{
"code": null,
"e": 14878,
"s": 14870,
"text": "Strings"
},
{
"code": null,
"e": 14886,
"s": 14878,
"text": "Strings"
},
{
"code": null,
"e": 14896,
"s": 14886,
"text": "Recursion"
},
{
"code": null,
"e": 14994,
"s": 14896,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15022,
"s": 14994,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 15057,
"s": 15022,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 15100,
"s": 15057,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 15132,
"s": 15100,
"text": "Reverse a stack using recursion"
},
{
"code": null,
"e": 15178,
"s": 15132,
"text": "Write a program to reverse digits of a number"
},
{
"code": null,
"e": 15224,
"s": 15178,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 15249,
"s": 15224,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 15264,
"s": 15249,
"text": "C++ Data Types"
},
{
"code": null,
"e": 15309,
"s": 15264,
"text": "Different Methods to Reverse a String in C++"
}
] |
Cross-Site Request Forgery(CSRF)
|
A CSRF attack forces an authenticated user (victim) to send a forged HTTP request, including the victim's session cookie to a vulnerable web application, which allows the attacker to force the victim's browser to generate request such that the vulnerable app perceives as legitimate requests from the victim.
Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram.
Here is a classic example of CSRF −
Step 1 − Let us say, the vulnerable application sends a state changing request as a plain text without any encryption.
http://bankx.com/app?action=transferFund&amount=3500&destinationAccount=4673243243
Step 2 − Now the hacker constructs a request that transfers money from the victim's account to the attacker's account by embedding the request in an image that is stored on various sites under the attacker's control −
<img src = "http://bankx.com/app?action=transferFunds&amount=14000&destinationAccount=attackersAcct#"
width = "0" height = "0" />
Step 1 − Let us perform a CSRF forgery by embedding a Java script into an image. The snapshot of the problem is listed below.
Step 2 − Now we need to mock up the transfer into a 1x1 image and make the victim to click on the same.
Step 3 − Upon submitting the message, the message is displayed as highlighted below.
Step 4 − Now if the victim clicks the following URL, the transfer is executed, which can be found intercepting the user action using burp suite. We are able to see the transfer by spotting it in Get message as shown below −
Step 5 − Now upon clicking refresh, the lesson completion mark is shown.
CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure.
CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure.
Forcing the user to re-authenticate or proving that they are users in order to protect CSRF. For example, CAPTCHA.
Forcing the user to re-authenticate or proving that they are users in order to protect CSRF. For example, CAPTCHA.
|
[
{
"code": null,
"e": 2883,
"s": 2574,
"text": "A CSRF attack forces an authenticated user (victim) to send a forged HTTP request, including the victim's session cookie to a vulnerable web application, which allows the attacker to force the victim's browser to generate request such that the vulnerable app perceives as legitimate requests from the victim."
},
{
"code": null,
"e": 3035,
"s": 2883,
"text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram."
},
{
"code": null,
"e": 3071,
"s": 3035,
"text": "Here is a classic example of CSRF −"
},
{
"code": null,
"e": 3190,
"s": 3071,
"text": "Step 1 − Let us say, the vulnerable application sends a state changing request as a plain text without any encryption."
},
{
"code": null,
"e": 3274,
"s": 3190,
"text": "http://bankx.com/app?action=transferFund&amount=3500&destinationAccount=4673243243\n"
},
{
"code": null,
"e": 3492,
"s": 3274,
"text": "Step 2 − Now the hacker constructs a request that transfers money from the victim's account to the attacker's account by embedding the request in an image that is stored on various sites under the attacker's control −"
},
{
"code": null,
"e": 3626,
"s": 3492,
"text": "<img src = \"http://bankx.com/app?action=transferFunds&amount=14000&destinationAccount=attackersAcct#\" \n width = \"0\" height = \"0\" />"
},
{
"code": null,
"e": 3752,
"s": 3626,
"text": "Step 1 − Let us perform a CSRF forgery by embedding a Java script into an image. The snapshot of the problem is listed below."
},
{
"code": null,
"e": 3856,
"s": 3752,
"text": "Step 2 − Now we need to mock up the transfer into a 1x1 image and make the victim to click on the same."
},
{
"code": null,
"e": 3941,
"s": 3856,
"text": "Step 3 − Upon submitting the message, the message is displayed as highlighted below."
},
{
"code": null,
"e": 4165,
"s": 3941,
"text": "Step 4 − Now if the victim clicks the following URL, the transfer is executed, which can be found intercepting the user action using burp suite. We are able to see the transfer by spotting it in Get message as shown below −"
},
{
"code": null,
"e": 4238,
"s": 4165,
"text": "Step 5 − Now upon clicking refresh, the lesson completion mark is shown."
},
{
"code": null,
"e": 4411,
"s": 4238,
"text": "CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure."
},
{
"code": null,
"e": 4584,
"s": 4411,
"text": "CSRF can be avoided by creating a unique token in a hidden field which would be sent in the body of the HTTP request rather than in an URL, which is more prone to exposure."
},
{
"code": null,
"e": 4699,
"s": 4584,
"text": "Forcing the user to re-authenticate or proving that they are users in order to protect CSRF. For example, CAPTCHA."
}
] |
Variance in Java
|
10 Jun, 2021
Variance refers to how subtyping between more complex types relates to subtyping between their components. “More complex types” here refers to higher-level structures like containers and functions. So, variance is about the assignment compatibility between containers and functions composed of parameters that are connected via a Type Hierarchy. It allows the safe integration of parametric and subtype polymorphism.
In java, variance is defined at the use-site.
Types of variance: There are 4 kinds of variance which are as follows. A type constructor is of the following types:
Invariance in Java: The use-site must have no open bounds on the type parameter. If A is a supertype of B, then GenericType<A> is not a Supertype of GenericType<B> and vice versa. This means these two types have no relation to each other and neither can be exchanged for the other under any circumstance.
Type 1: Invariant Containers
In java, invariants are likely the first examples of generic you’ll encounter and rate the most intuitive. The methods of the type parameter are usable as one would expect. All methods of the type parameter are accessible. They cannot be exchanged and one can read both from them which is illustrated below illustrations how.
Illustration 1: Cannot be exchanged
// Type hierarchy Person :> Joe :> JoeJr
List<Person> p = new ArrayList<>();
// Ok
p.add(new Person());
// Ok
p.add(new Joe());
// Ok
p.add(new JoeJr());
Illustration 2: Reading objects from them
// Type hierarchy : Person :>Joe :> JoeJr
List <Joe> joes = new ArrayList<>();
// Ok
Joe j = joes.get(0);
// Ok
Person p = joes.get(0);
Type 2: Covariance in Java
The use-site must an open lower bound on the type parameter. If B is a subtype of A, then GenericType<B> is a subtype of GenericType<? Extends A>.
Note: Arrays in Java have always been covariant
Before generics were introduced in Java 1.5, arrays were the only generic containers available. They have always been covariant, eg. Integer[] is a subtype of Object[]. The compiler allows you to pass your Integer[] to a method that accepts Object[]. If the method inserts a supertype of Integer, an ArrayStoreException is thrown at runtime. Covariant generic type rules implement this check at compile time, disallowing the mistake to ever happen in the first place.
Example
Java
class GFG { public static void main(String args[]) { Number[] numbers = new Number[] { 1, 2, 3, 4, 5 }; trick(numbers); } private static void trick(zobject[] objects) { objects[0] = new Float(123); // ok objects[1] = new Objects(); // ArrayStoreException // thrown at runtime }}
Output:
Now let us discuss Covariant containers. Java allows subtyping (covariant) generic types but it places restrictions on what can “flow into and out of” these generic types in accordance with the Principle of Least Astonishment. In other words, methods with return values of the type parameter are accessible, while methods with input arguments of the type parameter are inaccessible.
Illustration 1: One can exchange the supertype for the subtype:
// Type hierarchy : Person :> Joe :> JoeJr
List<? extends Joe> = new ArrayList<Joe>(); //ok
List<? extends Joe> = new ArrayList<JoeJr>(); //ok
List<? extends Joe> = new ArrayList<Person>(); // Compile error
Illustration 2: Reading from them is intuitive:
//Type hierarchy : Person :> Joe :> JoeJr
List<? extends Joe> joes = new ArrayList<>();
Joe j = joes.get(0); //ok
Person p = joes.get(0); //ok
JoeJr jr = joes.get(0); // compile error
Writing to them is prohibited (counterintuitive) to guard against the pitfalls with arrays described above. Eg. in the example code below, the caller/owner of a List<Joe> would be astonished if someone else’s method with covariant arg List<? extends Person> added a Jill.
// Type hierarchy : Person > Joe > JoeJr
List<? extends Joe> joes = new ArrayList<>();
joes.add(new Joe()); // compile error (you don't what subtype of Joe is in the list)
joes.add(new JoeJr()); // compile error
joes.add(new Person()); //compile error
joes.add(new Object()); // compile error
Type 3: Contravariant Containers
Contravariant containers behave counterintuitively: contrary to covariant containers, access to methods with return values of the type parameter are inaccessible while methods with input arguments of the type parameter are accessible:
Illustration 1: You can exchange the subtype for the supertype:
List<> super Joe> joes = new ArrayList<Joe>(); // ok
List<? super Joe> joes = new ArrayList<Person>(); // ok
List<? super Joe> joes = new ArrayList<JoeJr>(); //Compile Error
Illustration 2: Cannot capture a specific type when reading from them:
List<? super Joe> joes = new ArrayList<>();
Joe j = joes.get(0); // compile error
Person p = joes.get(0); // compile error
Object o = joes.get(0); // because everything is a object in java
Illustration 3: You can add subtypes of the “lower bound”:
List<? super Joe> Joes = new ArrayList<>();
joes.add(new JoeJr()); allowed
Illustration 4: But you cannot add supertypes:
List<? super Joe> joes = new ArrayList<>();
joes.add(new Person()); // compile error
joes.add(new Object()); // compile error
Type 4: Bivariance in Java
The use-site must declare an unbounded wildcard on the type parameter.
A generic type with an unbounded wildcard is a supertype of all bounded variations of the same generic type.Example is GenericType<?> is a supertype of GenericType<String>. Since the unbounded type is the root of the type hierarchy, it follows that of its parametric types it can only access methods inherited from java.lang.Object.
Think of GenericType<?> as GenericType<Object>.
Let us do discuss the variance of structures with N-type parameters. What about more complex types such as Functions? The same principles apply, you just have more type parameters to consider. It is illustrated in the below illustration to answer such set of dilemas.
Illustration:
Function<Person, Joe> personToJoe = null;
Function<Joe, JoeJr> joeToJoeJr = null;
personToJoe = joeToJoeJr; // compile error
// Covariance
Function<? extends Person, ? extends Joe> personToJoe
= null;
Function<Joe, JoeJr> jorToJorJr = null;
personToJoe = joeToJoeJr; // ok
// Contravariance
Function<? super Joe, ? super JoeJr> joeToJoeJr = null;
Function<? super Person, ? super Joe> personToJoe = null;
joeToJoeJr = personToJoe; // ok
Variance and Inheritance
Illustration 1: Java allows overriding methods with covariant return types and exception types:
interface person {
Person get();
void fail() throws Exception;
}
interface Joe extends Person {
JoeJr get();
void fail() throws IOException;
}
class JoeImpl implements Joe {
public JoeJr get() {} // overriden
public void fail throws IOException {} // Overriden
}
Illustration 2: Attempting to override methods with covariant arguments results in merely an overload:
interface Person {
void add(Person p);
}
interface Joe extends Person {
void add(Joe j);
}
class JoeImpl implements Joe {
public void add(Person p) {} // overload
public void add(Joe j) {} // overload
}
Conclusion: Variance introduces additional complexity to Java. While the typing rules around variance are easy to understand, the rules regarding accessibility of methods of the type parameter are counterintuitive. Understanding them isn’t just “obvious”. It requires pausing to think through the logical consequences.
Variance provides moderate net benefits in my daily programming, particularly when compatibility with subtypes is required(which is a regular occurrence in OOP).
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 446,
"s": 28,
"text": "Variance refers to how subtyping between more complex types relates to subtyping between their components. “More complex types” here refers to higher-level structures like containers and functions. So, variance is about the assignment compatibility between containers and functions composed of parameters that are connected via a Type Hierarchy. It allows the safe integration of parametric and subtype polymorphism. "
},
{
"code": null,
"e": 492,
"s": 446,
"text": "In java, variance is defined at the use-site."
},
{
"code": null,
"e": 609,
"s": 492,
"text": "Types of variance: There are 4 kinds of variance which are as follows. A type constructor is of the following types:"
},
{
"code": null,
"e": 914,
"s": 609,
"text": "Invariance in Java: The use-site must have no open bounds on the type parameter. If A is a supertype of B, then GenericType<A> is not a Supertype of GenericType<B> and vice versa. This means these two types have no relation to each other and neither can be exchanged for the other under any circumstance."
},
{
"code": null,
"e": 943,
"s": 914,
"text": "Type 1: Invariant Containers"
},
{
"code": null,
"e": 1269,
"s": 943,
"text": "In java, invariants are likely the first examples of generic you’ll encounter and rate the most intuitive. The methods of the type parameter are usable as one would expect. All methods of the type parameter are accessible. They cannot be exchanged and one can read both from them which is illustrated below illustrations how."
},
{
"code": null,
"e": 1305,
"s": 1269,
"text": "Illustration 1: Cannot be exchanged"
},
{
"code": null,
"e": 1470,
"s": 1305,
"text": "// Type hierarchy Person :> Joe :> JoeJr\n\nList<Person> p = new ArrayList<>();\n\n// Ok\np.add(new Person()); \n// Ok \np.add(new Joe()); \n// Ok\np.add(new JoeJr()); "
},
{
"code": null,
"e": 1512,
"s": 1470,
"text": "Illustration 2: Reading objects from them"
},
{
"code": null,
"e": 1653,
"s": 1512,
"text": "// Type hierarchy : Person :>Joe :> JoeJr\n\nList <Joe> joes = new ArrayList<>();\n// Ok\nJoe j = joes.get(0); \n// Ok\nPerson p = joes.get(0); "
},
{
"code": null,
"e": 1680,
"s": 1653,
"text": "Type 2: Covariance in Java"
},
{
"code": null,
"e": 1827,
"s": 1680,
"text": "The use-site must an open lower bound on the type parameter. If B is a subtype of A, then GenericType<B> is a subtype of GenericType<? Extends A>."
},
{
"code": null,
"e": 1875,
"s": 1827,
"text": "Note: Arrays in Java have always been covariant"
},
{
"code": null,
"e": 2343,
"s": 1875,
"text": "Before generics were introduced in Java 1.5, arrays were the only generic containers available. They have always been covariant, eg. Integer[] is a subtype of Object[]. The compiler allows you to pass your Integer[] to a method that accepts Object[]. If the method inserts a supertype of Integer, an ArrayStoreException is thrown at runtime. Covariant generic type rules implement this check at compile time, disallowing the mistake to ever happen in the first place."
},
{
"code": null,
"e": 2351,
"s": 2343,
"text": "Example"
},
{
"code": null,
"e": 2356,
"s": 2351,
"text": "Java"
},
{
"code": "class GFG { public static void main(String args[]) { Number[] numbers = new Number[] { 1, 2, 3, 4, 5 }; trick(numbers); } private static void trick(zobject[] objects) { objects[0] = new Float(123); // ok objects[1] = new Objects(); // ArrayStoreException // thrown at runtime }}",
"e": 2718,
"s": 2356,
"text": null
},
{
"code": null,
"e": 2726,
"s": 2718,
"text": "Output:"
},
{
"code": null,
"e": 3109,
"s": 2726,
"text": "Now let us discuss Covariant containers. Java allows subtyping (covariant) generic types but it places restrictions on what can “flow into and out of” these generic types in accordance with the Principle of Least Astonishment. In other words, methods with return values of the type parameter are accessible, while methods with input arguments of the type parameter are inaccessible."
},
{
"code": null,
"e": 3173,
"s": 3109,
"text": "Illustration 1: One can exchange the supertype for the subtype:"
},
{
"code": null,
"e": 3383,
"s": 3173,
"text": "// Type hierarchy : Person :> Joe :> JoeJr\nList<? extends Joe> = new ArrayList<Joe>(); //ok\nList<? extends Joe> = new ArrayList<JoeJr>(); //ok\nList<? extends Joe> = new ArrayList<Person>(); // Compile error"
},
{
"code": null,
"e": 3431,
"s": 3383,
"text": "Illustration 2: Reading from them is intuitive:"
},
{
"code": null,
"e": 3618,
"s": 3431,
"text": "//Type hierarchy : Person :> Joe :> JoeJr\nList<? extends Joe> joes = new ArrayList<>();\nJoe j = joes.get(0); //ok\nPerson p = joes.get(0); //ok\nJoeJr jr = joes.get(0); // compile error"
},
{
"code": null,
"e": 3891,
"s": 3618,
"text": "Writing to them is prohibited (counterintuitive) to guard against the pitfalls with arrays described above. Eg. in the example code below, the caller/owner of a List<Joe> would be astonished if someone else’s method with covariant arg List<? extends Person> added a Jill."
},
{
"code": null,
"e": 4189,
"s": 3891,
"text": "// Type hierarchy : Person > Joe > JoeJr\nList<? extends Joe> joes = new ArrayList<>();\njoes.add(new Joe()); // compile error (you don't what subtype of Joe is in the list)\njoes.add(new JoeJr()); // compile error\njoes.add(new Person()); //compile error\njoes.add(new Object()); // compile error"
},
{
"code": null,
"e": 4222,
"s": 4189,
"text": "Type 3: Contravariant Containers"
},
{
"code": null,
"e": 4457,
"s": 4222,
"text": "Contravariant containers behave counterintuitively: contrary to covariant containers, access to methods with return values of the type parameter are inaccessible while methods with input arguments of the type parameter are accessible:"
},
{
"code": null,
"e": 4521,
"s": 4457,
"text": "Illustration 1: You can exchange the subtype for the supertype:"
},
{
"code": null,
"e": 4698,
"s": 4521,
"text": "List<> super Joe> joes = new ArrayList<Joe>(); // ok\nList<? super Joe> joes = new ArrayList<Person>(); // ok\nList<? super Joe> joes = new ArrayList<JoeJr>(); //Compile Error"
},
{
"code": null,
"e": 4769,
"s": 4698,
"text": "Illustration 2: Cannot capture a specific type when reading from them:"
},
{
"code": null,
"e": 4962,
"s": 4769,
"text": "List<? super Joe> joes = new ArrayList<>();\nJoe j = joes.get(0); // compile error\nPerson p = joes.get(0); // compile error\nObject o = joes.get(0); // because everything is a object in java"
},
{
"code": null,
"e": 5021,
"s": 4962,
"text": "Illustration 3: You can add subtypes of the “lower bound”:"
},
{
"code": null,
"e": 5097,
"s": 5021,
"text": "List<? super Joe> Joes = new ArrayList<>();\njoes.add(new JoeJr()); allowed"
},
{
"code": null,
"e": 5144,
"s": 5097,
"text": "Illustration 4: But you cannot add supertypes:"
},
{
"code": null,
"e": 5272,
"s": 5144,
"text": "List<? super Joe> joes = new ArrayList<>();\njoes.add(new Person()); // compile error\njoes.add(new Object()); // compile error"
},
{
"code": null,
"e": 5299,
"s": 5272,
"text": "Type 4: Bivariance in Java"
},
{
"code": null,
"e": 5370,
"s": 5299,
"text": "The use-site must declare an unbounded wildcard on the type parameter."
},
{
"code": null,
"e": 5703,
"s": 5370,
"text": "A generic type with an unbounded wildcard is a supertype of all bounded variations of the same generic type.Example is GenericType<?> is a supertype of GenericType<String>. Since the unbounded type is the root of the type hierarchy, it follows that of its parametric types it can only access methods inherited from java.lang.Object."
},
{
"code": null,
"e": 5751,
"s": 5703,
"text": "Think of GenericType<?> as GenericType<Object>."
},
{
"code": null,
"e": 6019,
"s": 5751,
"text": "Let us do discuss the variance of structures with N-type parameters. What about more complex types such as Functions? The same principles apply, you just have more type parameters to consider. It is illustrated in the below illustration to answer such set of dilemas."
},
{
"code": null,
"e": 6033,
"s": 6019,
"text": "Illustration:"
},
{
"code": null,
"e": 6476,
"s": 6033,
"text": "Function<Person, Joe> personToJoe = null;\nFunction<Joe, JoeJr> joeToJoeJr = null;\npersonToJoe = joeToJoeJr; // compile error\n\n// Covariance\nFunction<? extends Person, ? extends Joe> personToJoe\n = null;\nFunction<Joe, JoeJr> jorToJorJr = null;\npersonToJoe = joeToJoeJr; // ok\n\n// Contravariance\nFunction<? super Joe, ? super JoeJr> joeToJoeJr = null;\nFunction<? super Person, ? super Joe> personToJoe = null;\njoeToJoeJr = personToJoe; // ok"
},
{
"code": null,
"e": 6501,
"s": 6476,
"text": "Variance and Inheritance"
},
{
"code": null,
"e": 6597,
"s": 6501,
"text": "Illustration 1: Java allows overriding methods with covariant return types and exception types:"
},
{
"code": null,
"e": 6884,
"s": 6597,
"text": "interface person {\n Person get();\n void fail() throws Exception;\n}\ninterface Joe extends Person {\n JoeJr get();\n void fail() throws IOException;\n}\nclass JoeImpl implements Joe {\n public JoeJr get() {} // overriden\n public void fail throws IOException {} // Overriden\n}"
},
{
"code": null,
"e": 6987,
"s": 6884,
"text": "Illustration 2: Attempting to override methods with covariant arguments results in merely an overload:"
},
{
"code": null,
"e": 7206,
"s": 6987,
"text": "interface Person {\n void add(Person p);\n}\ninterface Joe extends Person {\n void add(Joe j);\n}\nclass JoeImpl implements Joe {\n public void add(Person p) {} // overload\n public void add(Joe j) {} // overload\n}"
},
{
"code": null,
"e": 7525,
"s": 7206,
"text": "Conclusion: Variance introduces additional complexity to Java. While the typing rules around variance are easy to understand, the rules regarding accessibility of methods of the type parameter are counterintuitive. Understanding them isn’t just “obvious”. It requires pausing to think through the logical consequences."
},
{
"code": null,
"e": 7687,
"s": 7525,
"text": "Variance provides moderate net benefits in my daily programming, particularly when compatibility with subtypes is required(which is a regular occurrence in OOP)."
},
{
"code": null,
"e": 7692,
"s": 7687,
"text": "Java"
},
{
"code": null,
"e": 7697,
"s": 7692,
"text": "Java"
},
{
"code": null,
"e": 7795,
"s": 7697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7810,
"s": 7795,
"text": "Stream In Java"
},
{
"code": null,
"e": 7831,
"s": 7810,
"text": "Introduction to Java"
},
{
"code": null,
"e": 7852,
"s": 7831,
"text": "Constructors in Java"
},
{
"code": null,
"e": 7871,
"s": 7852,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 7888,
"s": 7871,
"text": "Generics in Java"
},
{
"code": null,
"e": 7918,
"s": 7888,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 7944,
"s": 7918,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 7960,
"s": 7944,
"text": "Strings in Java"
},
{
"code": null,
"e": 7997,
"s": 7960,
"text": "Differences between JDK, JRE and JVM"
}
] |
Calculate the angle between hour hand and minute hand
|
14 Jan, 2022
This problem is known as Clock angle problem where we need to find angle between hands of an analog clock at a given time.Examples:
Input:
h = 12:00
m = 30.00
Output:
165 degree
Input:
h = 3.00
m = 30.00
Output:
75 degree
The idea is to take 12:00 (h = 12, m = 0) as a reference. Following are detailed steps.
1. Calculate the angle made by hour hand with respect to 12:00 in h hours and m minutes. 2. Calculate the angle made by minute hand with respect to 12:00 in h hours and m minutes. 3. The difference between the two angles is the angle between the two hands.
How to calculate the two angles with respect to 12:00? The minute hand moves 360 degrees in 60 minute(or 6 degrees in one minute) and hour hand moves 360 degrees in 12 hours(or 0.5 degrees in 1 minute). In h hours and m minutes, the minute hand would move (h*60 + m)*6 and hour hand would move (h*60 + m)*0.5.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find angle between hour and minute hands#include <bits/stdc++.h>using namespace std; // Utility function to find minimum of two integersint min(int x, int y){ return (x < y)? x: y; } int calcAngle(double h, double m){ // validate the input if (h <0 || m < 0 || h >12 || m > 60) printf("Wrong input"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved // by hour and minute hands // with reference to 12:00 float hour_angle = 0.5 * (h * 60 + m); float minute_angle = 6 * m; // Find the difference between two angles float angle = abs(hour_angle - minute_angle); // Return the smaller angle of two possible angles angle = min(360 - angle, angle); return angle;} // Driver Codeint main(){ cout << calcAngle(9, 60) << endl; cout << calcAngle(3, 30) << endl; return 0;} // This is code is contributed by rathbhupendra
// C program to find angle between hour and minute hands#include <stdio.h>#include <stdlib.h> // Utility function to find minimum of two integersint min(int x, int y) { return (x < y)? x: y; } int calcAngle(double h, double m){ // validate the input if (h <0 || m < 0 || h >12 || m > 60) printf("Wrong input"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved by hour and minute hands // with reference to 12:00 int hour_angle = 0.5 * (h*60 + m); int minute_angle = 6*m; // Find the difference between two angles int angle = abs(hour_angle - minute_angle); // Return the smaller angle of two possible angles angle = min(360-angle, angle); return angle;} // Driver Codeint main(){ printf("%d n", calcAngle(9, 60)); printf("%d n", calcAngle(3, 30)); return 0;}
// Java program to find angle between hour and minute handsimport java.io.*; class GFG{ // Function to calculate the angle static int calcAngle(double h, double m) { // validate the input if (h <0 || m < 0 || h >12 || m > 60) System.out.println("Wrong input"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved by hour and minute hands // with reference to 12:00 int hour_angle = (int)(0.5 * (h*60 + m)); int minute_angle = (int)(6*m); // Find the difference between two angles int angle = Math.abs(hour_angle - minute_angle); // smaller angle of two possible angles angle = Math.min(360-angle, angle); return angle; } // Driver Code public static void main (String[] args) { System.out.println(calcAngle(9, 60)+" degree"); System.out.println(calcAngle(3, 30)+" degree"); }} // Contributed by Pramod Kumar
# Python program to find angle# between hour and minute hands # Function to Calculate angle b/w# hour hand and minute handdef calcAngle(h,m): # validate the input if (h < 0 or m < 0 or h > 12 or m > 60): print('Wrong input') if (h == 12): h = 0 if (m == 60): m = 0 h += 1; if(h>12): h = h-12; # Calculate the angles moved by # hour and minute hands with # reference to 12:00 hour_angle = 0.5 * (h * 60 + m) minute_angle = 6 * m # Find the difference between two angles angle = abs(hour_angle - minute_angle) # Return the smaller angle of two # possible angles angle = min(360 - angle, angle) return angle # Driver Codeh = 9m = 60print('Angle ', calcAngle(h,m)) # This code is contributed by Danish Raza
// C# program to find angle between// hour and minute handsusing System; class GFG { // Function to calculate the angle static int calcAngle(double h, double m) { // validate the input if (h < 0 || m < 0 || h > 12 || m > 60) Console.Write("Wrong input"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved by hour and // minute hands with reference to 12:00 int hour_angle = (int)(0.5 * (h * 60 + m)); int minute_angle = (int)(6 * m); // Find the difference between two angles int angle = Math.Abs(hour_angle - minute_angle); // smaller angle of two possible angles angle = Math.Min(360 - angle, angle); return angle; } // Driver code public static void Main () { Console.WriteLine(calcAngle(9, 60)); Console.Write(calcAngle(3, 30)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find// angle between hour// and minute hands // Utility function to// find minimum of two// integersfunction mintwo($x, $y){ return ($x < $y) ? $x : $y;} function calcAngle($h, $m){ // validate the input if ($h <0 || $m < 0 || $h >12 || $m > 60) echo "Wrong input"; if ($h == 12) $h = 0; if ($m == 60) { $m = 0; $h += 1; if($h>12) $h = $h-12; } // Calculate the angles // moved by hour and // minute hands with // reference to 12:00 $hour_angle = 0.5 * ($h * 60 + $m); $minute_angle = 6 * $m; // Find the difference // between two angles $angle = abs($hour_angle - $minute_angle); // Return the smaller angle // of two possible angles $angle = min(360 - $angle, $angle); return $angle;} // Driver Codeecho calcAngle(9, 60), "\n";echo calcAngle(3, 30), "\n"; // This code is contributed by ajit?>
<script>// Javascript program to find angle between hour and minute hands // Utility function to find minimum of two integersfunction min(x, y){ return (x < y)? x: y; } function calcAngle(h, m){ // validate the input if (h <0 || m < 0 || h >12 || m > 60) document.write("Wrong input"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved // by hour and minute hands // with reference to 12:00 let hour_angle = 0.5 * (h * 60 + m); let minute_angle = 6 * m; // Find the difference between two angles let angle = Math.abs(hour_angle - minute_angle); // Return the smaller angle of two possible angles angle = min(360 - angle, angle); return angle;} // Driver Code document.write(calcAngle(9, 60) + "<br>"); document.write(calcAngle(3, 30) + "<br>"); // This code is contributed by Surbhi Tyagi. </script>
60
75
Time Complexity: O(1)
Auxiliary Space: O(1)Exercise: Find all times when hour and minute hands get superimposed.This article is contributed by Ashish Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
nitin mittal
jit_t
rathbhupendra
kunalyadav2
pranshul2112
tejendrapratap
surbhityagi15
subhammahato348
amartyaghoshgfg
Amazon
Infinera
Paytm
Salesforce
Mathematical
Paytm
Amazon
Salesforce
Infinera
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 185,
"s": 52,
"text": "This problem is known as Clock angle problem where we need to find angle between hands of an analog clock at a given time.Examples: "
},
{
"code": null,
"e": 282,
"s": 185,
"text": "Input: \nh = 12:00\nm = 30.00\nOutput: \n165 degree\n\nInput: \nh = 3.00\nm = 30.00\nOutput: \n75 degree"
},
{
"code": null,
"e": 370,
"s": 282,
"text": "The idea is to take 12:00 (h = 12, m = 0) as a reference. Following are detailed steps."
},
{
"code": null,
"e": 627,
"s": 370,
"text": "1. Calculate the angle made by hour hand with respect to 12:00 in h hours and m minutes. 2. Calculate the angle made by minute hand with respect to 12:00 in h hours and m minutes. 3. The difference between the two angles is the angle between the two hands."
},
{
"code": null,
"e": 939,
"s": 627,
"text": "How to calculate the two angles with respect to 12:00? The minute hand moves 360 degrees in 60 minute(or 6 degrees in one minute) and hour hand moves 360 degrees in 12 hours(or 0.5 degrees in 1 minute). In h hours and m minutes, the minute hand would move (h*60 + m)*6 and hour hand would move (h*60 + m)*0.5. "
},
{
"code": null,
"e": 943,
"s": 939,
"text": "C++"
},
{
"code": null,
"e": 945,
"s": 943,
"text": "C"
},
{
"code": null,
"e": 950,
"s": 945,
"text": "Java"
},
{
"code": null,
"e": 958,
"s": 950,
"text": "Python3"
},
{
"code": null,
"e": 961,
"s": 958,
"text": "C#"
},
{
"code": null,
"e": 965,
"s": 961,
"text": "PHP"
},
{
"code": null,
"e": 976,
"s": 965,
"text": "Javascript"
},
{
"code": "// C++ program to find angle between hour and minute hands#include <bits/stdc++.h>using namespace std; // Utility function to find minimum of two integersint min(int x, int y){ return (x < y)? x: y; } int calcAngle(double h, double m){ // validate the input if (h <0 || m < 0 || h >12 || m > 60) printf(\"Wrong input\"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved // by hour and minute hands // with reference to 12:00 float hour_angle = 0.5 * (h * 60 + m); float minute_angle = 6 * m; // Find the difference between two angles float angle = abs(hour_angle - minute_angle); // Return the smaller angle of two possible angles angle = min(360 - angle, angle); return angle;} // Driver Codeint main(){ cout << calcAngle(9, 60) << endl; cout << calcAngle(3, 30) << endl; return 0;} // This is code is contributed by rathbhupendra",
"e": 1959,
"s": 976,
"text": null
},
{
"code": "// C program to find angle between hour and minute hands#include <stdio.h>#include <stdlib.h> // Utility function to find minimum of two integersint min(int x, int y) { return (x < y)? x: y; } int calcAngle(double h, double m){ // validate the input if (h <0 || m < 0 || h >12 || m > 60) printf(\"Wrong input\"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved by hour and minute hands // with reference to 12:00 int hour_angle = 0.5 * (h*60 + m); int minute_angle = 6*m; // Find the difference between two angles int angle = abs(hour_angle - minute_angle); // Return the smaller angle of two possible angles angle = min(360-angle, angle); return angle;} // Driver Codeint main(){ printf(\"%d n\", calcAngle(9, 60)); printf(\"%d n\", calcAngle(3, 30)); return 0;}",
"e": 2862,
"s": 1959,
"text": null
},
{
"code": "// Java program to find angle between hour and minute handsimport java.io.*; class GFG{ // Function to calculate the angle static int calcAngle(double h, double m) { // validate the input if (h <0 || m < 0 || h >12 || m > 60) System.out.println(\"Wrong input\"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved by hour and minute hands // with reference to 12:00 int hour_angle = (int)(0.5 * (h*60 + m)); int minute_angle = (int)(6*m); // Find the difference between two angles int angle = Math.abs(hour_angle - minute_angle); // smaller angle of two possible angles angle = Math.min(360-angle, angle); return angle; } // Driver Code public static void main (String[] args) { System.out.println(calcAngle(9, 60)+\" degree\"); System.out.println(calcAngle(3, 30)+\" degree\"); }} // Contributed by Pramod Kumar",
"e": 3929,
"s": 2862,
"text": null
},
{
"code": "# Python program to find angle# between hour and minute hands # Function to Calculate angle b/w# hour hand and minute handdef calcAngle(h,m): # validate the input if (h < 0 or m < 0 or h > 12 or m > 60): print('Wrong input') if (h == 12): h = 0 if (m == 60): m = 0 h += 1; if(h>12): h = h-12; # Calculate the angles moved by # hour and minute hands with # reference to 12:00 hour_angle = 0.5 * (h * 60 + m) minute_angle = 6 * m # Find the difference between two angles angle = abs(hour_angle - minute_angle) # Return the smaller angle of two # possible angles angle = min(360 - angle, angle) return angle # Driver Codeh = 9m = 60print('Angle ', calcAngle(h,m)) # This code is contributed by Danish Raza",
"e": 4864,
"s": 3929,
"text": null
},
{
"code": "// C# program to find angle between// hour and minute handsusing System; class GFG { // Function to calculate the angle static int calcAngle(double h, double m) { // validate the input if (h < 0 || m < 0 || h > 12 || m > 60) Console.Write(\"Wrong input\"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved by hour and // minute hands with reference to 12:00 int hour_angle = (int)(0.5 * (h * 60 + m)); int minute_angle = (int)(6 * m); // Find the difference between two angles int angle = Math.Abs(hour_angle - minute_angle); // smaller angle of two possible angles angle = Math.Min(360 - angle, angle); return angle; } // Driver code public static void Main () { Console.WriteLine(calcAngle(9, 60)); Console.Write(calcAngle(3, 30)); }} // This code is contributed by Nitin Mittal.",
"e": 5927,
"s": 4864,
"text": null
},
{
"code": "<?php// PHP program to find// angle between hour// and minute hands // Utility function to// find minimum of two// integersfunction mintwo($x, $y){ return ($x < $y) ? $x : $y;} function calcAngle($h, $m){ // validate the input if ($h <0 || $m < 0 || $h >12 || $m > 60) echo \"Wrong input\"; if ($h == 12) $h = 0; if ($m == 60) { $m = 0; $h += 1; if($h>12) $h = $h-12; } // Calculate the angles // moved by hour and // minute hands with // reference to 12:00 $hour_angle = 0.5 * ($h * 60 + $m); $minute_angle = 6 * $m; // Find the difference // between two angles $angle = abs($hour_angle - $minute_angle); // Return the smaller angle // of two possible angles $angle = min(360 - $angle, $angle); return $angle;} // Driver Codeecho calcAngle(9, 60), \"\\n\";echo calcAngle(3, 30), \"\\n\"; // This code is contributed by ajit?>",
"e": 6928,
"s": 5927,
"text": null
},
{
"code": "<script>// Javascript program to find angle between hour and minute hands // Utility function to find minimum of two integersfunction min(x, y){ return (x < y)? x: y; } function calcAngle(h, m){ // validate the input if (h <0 || m < 0 || h >12 || m > 60) document.write(\"Wrong input\"); if (h == 12) h = 0; if (m == 60) { m = 0; h += 1; if(h>12) h = h-12; } // Calculate the angles moved // by hour and minute hands // with reference to 12:00 let hour_angle = 0.5 * (h * 60 + m); let minute_angle = 6 * m; // Find the difference between two angles let angle = Math.abs(hour_angle - minute_angle); // Return the smaller angle of two possible angles angle = min(360 - angle, angle); return angle;} // Driver Code document.write(calcAngle(9, 60) + \"<br>\"); document.write(calcAngle(3, 30) + \"<br>\"); // This code is contributed by Surbhi Tyagi. </script>",
"e": 7872,
"s": 6928,
"text": null
},
{
"code": null,
"e": 7878,
"s": 7872,
"text": "60\n75"
},
{
"code": null,
"e": 7900,
"s": 7878,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 8161,
"s": 7900,
"text": "Auxiliary Space: O(1)Exercise: Find all times when hour and minute hands get superimposed.This article is contributed by Ashish Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 8174,
"s": 8161,
"text": "nitin mittal"
},
{
"code": null,
"e": 8180,
"s": 8174,
"text": "jit_t"
},
{
"code": null,
"e": 8194,
"s": 8180,
"text": "rathbhupendra"
},
{
"code": null,
"e": 8206,
"s": 8194,
"text": "kunalyadav2"
},
{
"code": null,
"e": 8219,
"s": 8206,
"text": "pranshul2112"
},
{
"code": null,
"e": 8234,
"s": 8219,
"text": "tejendrapratap"
},
{
"code": null,
"e": 8248,
"s": 8234,
"text": "surbhityagi15"
},
{
"code": null,
"e": 8264,
"s": 8248,
"text": "subhammahato348"
},
{
"code": null,
"e": 8280,
"s": 8264,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 8287,
"s": 8280,
"text": "Amazon"
},
{
"code": null,
"e": 8296,
"s": 8287,
"text": "Infinera"
},
{
"code": null,
"e": 8302,
"s": 8296,
"text": "Paytm"
},
{
"code": null,
"e": 8313,
"s": 8302,
"text": "Salesforce"
},
{
"code": null,
"e": 8326,
"s": 8313,
"text": "Mathematical"
},
{
"code": null,
"e": 8332,
"s": 8326,
"text": "Paytm"
},
{
"code": null,
"e": 8339,
"s": 8332,
"text": "Amazon"
},
{
"code": null,
"e": 8350,
"s": 8339,
"text": "Salesforce"
},
{
"code": null,
"e": 8359,
"s": 8350,
"text": "Infinera"
},
{
"code": null,
"e": 8372,
"s": 8359,
"text": "Mathematical"
},
{
"code": null,
"e": 8470,
"s": 8372,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8494,
"s": 8470,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 8515,
"s": 8494,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 8529,
"s": 8515,
"text": "Prime Numbers"
},
{
"code": null,
"e": 8571,
"s": 8529,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 8608,
"s": 8571,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 8661,
"s": 8608,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 8704,
"s": 8661,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 8736,
"s": 8704,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 8777,
"s": 8736,
"text": "Program for Decimal to Binary Conversion"
}
] |
random.setstate() in Python
|
17 May, 2020
Random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
The setstate() method of the random module is used in conjugation with the getstate() method. After using the getstate() method to capture the state of the random number generator, the setstate() method is used to restore the state of the random number generator back to the specified state.
The setstate() method requires a state object as a parameter which can be obtained by invoking the getstate() method.
Example 1:
# import the random moduleimport random # capture the current state# using the getstate() methodstate = random.getstate() # print a random number of the# captured statenum = random.random()print("A random number of the captured state: "+ str(num)) # print another random numbernum = random.random()print("Another random number: "+ str(num)) # restore the captured state# using the setstate() method# pass the captured state as the parameterrandom.setstate(state) # now printing the same random number# as in the captured statenum = random.random()print("The random number of the previously captured state: "+ str(num))
Output:
A random number of the captured state: 0.8059083574308233Another random number: 0.46568313950438245The random number of the previously captured state: 0.8059083574308233
Example 2:
# import the random moduleimport random list1 = [1, 2, 3, 4, 5] # capture the current state# using the getstate() methodstate = random.getstate() # Prints list of random items of given length print(random.sample(list1, 3)) # restore the captured state# using the setstate() method# pass the captured state as the parameterrandom.setstate(state) # now printing the same list of random# itemsprint(random.sample(list1, 3))
Output:
[5, 2, 4]
[5, 2, 4]
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 258,
"s": 52,
"text": "Random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined."
},
{
"code": null,
"e": 550,
"s": 258,
"text": "The setstate() method of the random module is used in conjugation with the getstate() method. After using the getstate() method to capture the state of the random number generator, the setstate() method is used to restore the state of the random number generator back to the specified state."
},
{
"code": null,
"e": 668,
"s": 550,
"text": "The setstate() method requires a state object as a parameter which can be obtained by invoking the getstate() method."
},
{
"code": null,
"e": 679,
"s": 668,
"text": "Example 1:"
},
{
"code": "# import the random moduleimport random # capture the current state# using the getstate() methodstate = random.getstate() # print a random number of the# captured statenum = random.random()print(\"A random number of the captured state: \"+ str(num)) # print another random numbernum = random.random()print(\"Another random number: \"+ str(num)) # restore the captured state# using the setstate() method# pass the captured state as the parameterrandom.setstate(state) # now printing the same random number# as in the captured statenum = random.random()print(\"The random number of the previously captured state: \"+ str(num))",
"e": 1303,
"s": 679,
"text": null
},
{
"code": null,
"e": 1311,
"s": 1303,
"text": "Output:"
},
{
"code": null,
"e": 1481,
"s": 1311,
"text": "A random number of the captured state: 0.8059083574308233Another random number: 0.46568313950438245The random number of the previously captured state: 0.8059083574308233"
},
{
"code": null,
"e": 1492,
"s": 1481,
"text": "Example 2:"
},
{
"code": "# import the random moduleimport random list1 = [1, 2, 3, 4, 5] # capture the current state# using the getstate() methodstate = random.getstate() # Prints list of random items of given length print(random.sample(list1, 3)) # restore the captured state# using the setstate() method# pass the captured state as the parameterrandom.setstate(state) # now printing the same list of random# itemsprint(random.sample(list1, 3)) ",
"e": 1924,
"s": 1492,
"text": null
},
{
"code": null,
"e": 1932,
"s": 1924,
"text": "Output:"
},
{
"code": null,
"e": 1952,
"s": 1932,
"text": "[5, 2, 4]\n[5, 2, 4]"
},
{
"code": null,
"e": 1966,
"s": 1952,
"text": "Python-random"
},
{
"code": null,
"e": 1973,
"s": 1966,
"text": "Python"
},
{
"code": null,
"e": 2071,
"s": 1973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2099,
"s": 2071,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2149,
"s": 2099,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2171,
"s": 2149,
"text": "Python map() function"
},
{
"code": null,
"e": 2215,
"s": 2171,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2233,
"s": 2215,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2275,
"s": 2233,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2298,
"s": 2275,
"text": "Taking input in Python"
},
{
"code": null,
"e": 2320,
"s": 2298,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2355,
"s": 2320,
"text": "Read a file line by line in Python"
}
] |
Quickly merging two sorted arrays using std::merge() in C++ STL
|
13 Jun, 2022
C++ program to merge two sorted arrays of length ‘n’ and ‘m’ respectively in sorted order.
Examples:
Input: A[] = {3, 6, 9}
B[] = {2, 7, 11}
Output: C[] = {2, 3, 6, 7, 9, 11}
Input: A[] = {1, 1, 3, 6, 9}
B[] = {1, 2, 7, 11, 11}
Output: C[] = {1, 1, 1, 2, 3, 6, 7, 9, 11, 11}
We have discussed other approaches in below postsMerge two sorted arrays with O(1) extra spaceMerge two sorted arrays
We can quickly merge two sorted arrays using std::merge present algorithm header file.
Below is the implementation using std :: merge
// C++ program to merge two sorted arrays// std::merge()#include <iostream>#include <algorithm>using namespace std; // Driver codeint main(){ int A[] = {1, 1, 9}; int n = sizeof(A)/sizeof(A[0]); int B[] = {2, 7, 11, 11}; int m = sizeof(B)/sizeof(B[0]); // Merging in sorted order int C[m + n]; merge(A, (A + n), B, (B + m), C); // Print the merged array. for (int i = 0; i < (m + n); i++) cout << C[i] << " "; return 0;}
Output:
1 1 2 7 9 11 11
In general, syntax of merge() is
// Merges elements from aFirst to aLast and bFirst
// to bLast into a result and returns iterator pointing
// to first element of result
OutputItr merge(InputItr1 aFirst, InputItr1 aLast,
InputItr2 bFirst, InputItr2 bLast,
OutputItr result);
We can use it for array of user defined objects
also by overloading < operator.
This article is contributed by Rohit Thapliyal. 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.
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 145,
"s": 54,
"text": "C++ program to merge two sorted arrays of length ‘n’ and ‘m’ respectively in sorted order."
},
{
"code": null,
"e": 155,
"s": 145,
"text": "Examples:"
},
{
"code": null,
"e": 345,
"s": 155,
"text": "Input: A[] = {3, 6, 9}\n B[] = {2, 7, 11}\nOutput: C[] = {2, 3, 6, 7, 9, 11}\n\nInput: A[] = {1, 1, 3, 6, 9}\n B[] = {1, 2, 7, 11, 11}\nOutput: C[] = {1, 1, 1, 2, 3, 6, 7, 9, 11, 11}\n"
},
{
"code": null,
"e": 463,
"s": 345,
"text": "We have discussed other approaches in below postsMerge two sorted arrays with O(1) extra spaceMerge two sorted arrays"
},
{
"code": null,
"e": 550,
"s": 463,
"text": "We can quickly merge two sorted arrays using std::merge present algorithm header file."
},
{
"code": null,
"e": 597,
"s": 550,
"text": "Below is the implementation using std :: merge"
},
{
"code": "// C++ program to merge two sorted arrays// std::merge()#include <iostream>#include <algorithm>using namespace std; // Driver codeint main(){ int A[] = {1, 1, 9}; int n = sizeof(A)/sizeof(A[0]); int B[] = {2, 7, 11, 11}; int m = sizeof(B)/sizeof(B[0]); // Merging in sorted order int C[m + n]; merge(A, (A + n), B, (B + m), C); // Print the merged array. for (int i = 0; i < (m + n); i++) cout << C[i] << \" \"; return 0;}",
"e": 1065,
"s": 597,
"text": null
},
{
"code": null,
"e": 1073,
"s": 1065,
"text": "Output:"
},
{
"code": null,
"e": 1091,
"s": 1073,
"text": "1 1 2 7 9 11 11 \n"
},
{
"code": null,
"e": 1124,
"s": 1091,
"text": "In general, syntax of merge() is"
},
{
"code": null,
"e": 1480,
"s": 1124,
"text": "// Merges elements from aFirst to aLast and bFirst\n// to bLast into a result and returns iterator pointing\n// to first element of result\nOutputItr merge(InputItr1 aFirst, InputItr1 aLast,\n InputItr2 bFirst, InputItr2 bLast,\n OutputItr result);\n\nWe can use it for array of user defined objects\nalso by overloading < operator.\n"
},
{
"code": null,
"e": 1779,
"s": 1480,
"text": "This article is contributed by Rohit Thapliyal. 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": 1904,
"s": 1779,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1926,
"s": 1904,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 1930,
"s": 1926,
"text": "STL"
},
{
"code": null,
"e": 1934,
"s": 1930,
"text": "C++"
},
{
"code": null,
"e": 1938,
"s": 1934,
"text": "STL"
},
{
"code": null,
"e": 1942,
"s": 1938,
"text": "CPP"
},
{
"code": null,
"e": 2040,
"s": 1942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2064,
"s": 2040,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2084,
"s": 2064,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2128,
"s": 2084,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2161,
"s": 2128,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2186,
"s": 2161,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2231,
"s": 2186,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2248,
"s": 2231,
"text": "std::find in C++"
},
{
"code": null,
"e": 2296,
"s": 2248,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2340,
"s": 2296,
"text": "List in C++ Standard Template Library (STL)"
}
] |
How to create a transparent iframe ?
|
14 Jul, 2020
The <iframe> tag is an inline frame. It is used to embed another HTML page within the current HTML page.
Syntax:
<iframe src = "URL"></iframe>
A transparent iframe can be made by setting its background to transparent.
body {
background-color : transparent;
}
And, the allowtransparency attribute of “iframe” is to be set as “true”.
<iframe src = "URL" allowtransparency = "true"></iframe>
Example:
HTML code:<!DOCTYPE html><html> <body> <div style="background: green; padding: 30px;"> <iframe src="iframe.html" allowtransparency="true"> Alternate content </iframe> </div></body> </html>
<!DOCTYPE html><html> <body> <div style="background: green; padding: 30px;"> <iframe src="iframe.html" allowtransparency="true"> Alternate content </iframe> </div></body> </html>
iframe.html<!DOCTYPE html><html> <body style= "background-color: transparent; text-align: center; color: #ffffff;"> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p></body> </html>
<!DOCTYPE html><html> <body style= "background-color: transparent; text-align: center; color: #ffffff;"> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p></body> </html>
Output:
HTML-Misc
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 133,
"s": 28,
"text": "The <iframe> tag is an inline frame. It is used to embed another HTML page within the current HTML page."
},
{
"code": null,
"e": 141,
"s": 133,
"text": "Syntax:"
},
{
"code": "<iframe src = \"URL\"></iframe>",
"e": 171,
"s": 141,
"text": null
},
{
"code": null,
"e": 246,
"s": 171,
"text": "A transparent iframe can be made by setting its background to transparent."
},
{
"code": null,
"e": 292,
"s": 246,
"text": "body {\n background-color : transparent;\n}\n"
},
{
"code": null,
"e": 365,
"s": 292,
"text": "And, the allowtransparency attribute of “iframe” is to be set as “true”."
},
{
"code": "<iframe src = \"URL\" allowtransparency = \"true\"></iframe>",
"e": 422,
"s": 365,
"text": null
},
{
"code": null,
"e": 431,
"s": 422,
"text": "Example:"
},
{
"code": null,
"e": 691,
"s": 431,
"text": "HTML code:<!DOCTYPE html><html> <body> <div style=\"background: green; padding: 30px;\"> <iframe src=\"iframe.html\" allowtransparency=\"true\"> Alternate content </iframe> </div></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <body> <div style=\"background: green; padding: 30px;\"> <iframe src=\"iframe.html\" allowtransparency=\"true\"> Alternate content </iframe> </div></body> </html>",
"e": 941,
"s": 691,
"text": null
},
{
"code": null,
"e": 1259,
"s": 941,
"text": "iframe.html<!DOCTYPE html><html> <body style= \"background-color: transparent; text-align: center; color: #ffffff;\"> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <body style= \"background-color: transparent; text-align: center; color: #ffffff;\"> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p> <p>geeksforgeeks</p></body> </html>",
"e": 1566,
"s": 1259,
"text": null
},
{
"code": null,
"e": 1574,
"s": 1566,
"text": "Output:"
},
{
"code": null,
"e": 1584,
"s": 1574,
"text": "HTML-Misc"
},
{
"code": null,
"e": 1591,
"s": 1584,
"text": "Picked"
},
{
"code": null,
"e": 1596,
"s": 1591,
"text": "HTML"
},
{
"code": null,
"e": 1613,
"s": 1596,
"text": "Web Technologies"
},
{
"code": null,
"e": 1618,
"s": 1613,
"text": "HTML"
},
{
"code": null,
"e": 1716,
"s": 1618,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1740,
"s": 1716,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1779,
"s": 1740,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1818,
"s": 1779,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1855,
"s": 1818,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 1875,
"s": 1855,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1908,
"s": 1875,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1969,
"s": 1908,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2012,
"s": 1969,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2084,
"s": 2012,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Python PIL | logical_xor() and invert() method - GeeksforGeeks
|
06 Nov, 2019
PIL.ImageChops.logical_xor() method applies Logical XOR between two images. At least one of the images must have mode “1”.
Image 1:Image2:
Syntax: PIL.ImageChops.logical_xor(image1, image2)
Parameters:image1: first imageimage2: second image
Return Type: Image
# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 object im1 = Image.open(r"C:\Users\sadow984\Desktop\a2.PNG") .convert("1") # creating a image2 object im2 = Image.open(r"C:\Users\sadow984\Desktop\x5.PNG") .convert("1") # applying logical_xor method im3 = ImageChops.logical_xor(im1, im2) im3.show()
Output:
PIL.ImageChops.invert() method invert an image (channel).
Syntax: PIL.ImageChops.invert(image)
Parameters:image1: image
Return Type: Image
# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 object im1 = Image.open(r"C:\Users\sadow984\Desktop\a2.PNG") # applying invert method im3 = ImageChops.invert(im1) im3.show()
Output:
nidhi_biet
Image-Processing
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
|
[
{
"code": null,
"e": 24590,
"s": 24562,
"text": "\n06 Nov, 2019"
},
{
"code": null,
"e": 24713,
"s": 24590,
"text": "PIL.ImageChops.logical_xor() method applies Logical XOR between two images. At least one of the images must have mode “1”."
},
{
"code": null,
"e": 24729,
"s": 24713,
"text": "Image 1:Image2:"
},
{
"code": null,
"e": 24780,
"s": 24729,
"text": "Syntax: PIL.ImageChops.logical_xor(image1, image2)"
},
{
"code": null,
"e": 24831,
"s": 24780,
"text": "Parameters:image1: first imageimage2: second image"
},
{
"code": null,
"e": 24850,
"s": 24831,
"text": "Return Type: Image"
},
{
"code": "# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 object im1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\a2.PNG\") .convert(\"1\") # creating a image2 object im2 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\x5.PNG\") .convert(\"1\") # applying logical_xor method im3 = ImageChops.logical_xor(im1, im2) im3.show() ",
"e": 25231,
"s": 24850,
"text": null
},
{
"code": null,
"e": 25239,
"s": 25231,
"text": "Output:"
},
{
"code": null,
"e": 25297,
"s": 25239,
"text": "PIL.ImageChops.invert() method invert an image (channel)."
},
{
"code": null,
"e": 25334,
"s": 25297,
"text": "Syntax: PIL.ImageChops.invert(image)"
},
{
"code": null,
"e": 25359,
"s": 25334,
"text": "Parameters:image1: image"
},
{
"code": null,
"e": 25378,
"s": 25359,
"text": "Return Type: Image"
},
{
"code": "# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 object im1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\a2.PNG\") # applying invert method im3 = ImageChops.invert(im1) im3.show() ",
"e": 25631,
"s": 25378,
"text": null
},
{
"code": null,
"e": 25639,
"s": 25631,
"text": "Output:"
},
{
"code": null,
"e": 25650,
"s": 25639,
"text": "nidhi_biet"
},
{
"code": null,
"e": 25667,
"s": 25650,
"text": "Image-Processing"
},
{
"code": null,
"e": 25678,
"s": 25667,
"text": "Python-pil"
},
{
"code": null,
"e": 25685,
"s": 25678,
"text": "Python"
},
{
"code": null,
"e": 25783,
"s": 25685,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25801,
"s": 25783,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25836,
"s": 25801,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25868,
"s": 25836,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25890,
"s": 25868,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25932,
"s": 25890,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25962,
"s": 25932,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25988,
"s": 25962,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26032,
"s": 25988,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26069,
"s": 26032,
"text": "Create a Pandas DataFrame from Lists"
}
] |
React Best Practices ⚛. The React Best Practices should follow... | by Sabesan Sathananthan | Towards Data Science
|
During my Internship period in Sysco LABS, I received significant exposure to React Js. For our project, we used React Js, and we followed React best practices. Therefore my team lead and my mentor Nadun Indunil suggested that I write about React best practices. This is my 25th article in Medium.
React is a JavaScript library for developing user interfaces. React library was created by Facebook. React allows for integration with many exciting components, libraries and frameworks. Admittedly, developers can make their own components.
Before the best practices, I would suggest Test-driven Development when you develop a react application. Test-driven Development means write a test first and then develop your code according to the tests. It is easier to identify the bugs. If you follow another Software development process when you find a bug, write a test first.
File organizationTiny and functional componentsReusability componentsDelete Redundant codeIndex as keysUnnecessary <div>sNecessary Comments onlyUnderstand to handle ‘this’Props — State — ConstructorNaming in the endAware of State and RenderingAvoid objects inside the ‘setState’Use Upper Camel Case NamesUtilize prop-typesCSS in JavaScriptTestingUse ESLint, Prettier and snippet librariesUse React Developer Tools
File organization
Tiny and functional components
Reusability components
Delete Redundant code
Index as keys
Unnecessary <div>s
Necessary Comments only
Understand to handle ‘this’
Props — State — Constructor
Naming in the end
Aware of State and Rendering
Avoid objects inside the ‘setState’
Use Upper Camel Case Names
Utilize prop-types
CSS in JavaScript
Testing
Use ESLint, Prettier and snippet libraries
Use React Developer Tools
File organization is not only the best practice for react applications, but also it is the best for other applications as well. The file structure of create-react-app is one possible way of organizing your react files. While there is not necessarily one file structure that is better than another, it important to keep your files organized. In React, your file structure will grow rapidly, considering every component has at least one file associated with it. Keep an assets folder that contains top-level CSS, images, and font files. Maintain a helpers folder to put other files for any kind of file for functionalities. Keep all the files related to a component into one folder. Usually, the component folder contains more than a single component file, such as test file CSS and one or more component files. If there are any minor components used by a particular component only, better to keep those all small components in the component folder. When you keep your large components in their own folder and the small components that are used by the components are in a subfolder is easier to understand the file hierarchy. developers mainly named the main component file inside a file index.js. This can become cumbersome to navigate once you have several files, all named as index.js. The solution for this is to add a package.json file to each of your components folders, set the main entry point for this corresponding folder. For instance, for button component main entry point is Button.js. Adding package.json to each folder is not a good practice but It helps to easily handle your files. So we can add the following package.json file inside the button component folder.
When you use Redux in your React project you can use Rails-style or Domain-style or “Ducks” pattern folder structure according to your project. In Rails-style pattern, separate folders are used for “actions”, “constants”, “reducers”, “containers”, and “components”. In Domain-style pattern, separate folders are used per feature or domain, possibly with sub-folders per file type. “Ducks” pattern is similar to domain style, but it explicitly ties together actions and reducers, often by defining them in the same file. However, folder structure could be something developers wish but there should be an easy way to handle components. React says, it doesn’t have opinions on how you put files into folders. New teams to react use Duck style. When they get matured they start to use rails. Rails has its advantage of understanding the project easily.
Dan Abramov tweeted a solution that 👉
moves files around until it feels right.
That’s exactly what you should do. You should move files around until they feel right.
As we all know, React will work with large components. But if we break them into small sizes, we can reuse them. Small components are easier to read, test, maintain, and reuse. Most beginners in React create Class components even when they aren’t using component state or life cycle methods. Functional components are more efficient for simple components.
The above Class component could be written as below.
Advantages of using Functional Components.
Less code
Easier to understand
Stateless
Easier to test
There is no this binding.
Easier to extract smaller components.
When you are using functional component you have no control over the re-rendering process. When something changes or even component changes itself, React will re-render functional components. In former react versions has a solution to use React.PureComponent. PureComponent allows shallow props and state comparison. When props or content of the component or component itself changed component will re-render. Otherwise, PureComponent skip re-render and reuse the last rendered result instead.
After React v16.6.0 React introduces a new feature that was memo. Memo shallowly compare props. When props or content of the component or component itself changed component will re-render. Based on the comparison react will either reuse last rendered result or re-render. Memo allows you to create an unadulterated functional component. Memo obliterate the use of stateful components and PureComponent.
Each functional component should have one function that means one functional component is equal to one function. When you are creating a functional component with one function you can improve the reusability of that component.
Not only in React but also in all application development the common rule is keeping the code is succinct and tiny as much as possible. React best practices instruct to keep the error-free code and incisive code. Don’t Repeat Yourself (DRY) is a principle of software development focused at minimizing repetition of software patterns, replacing it with abstractions or using data normalization to avoid redundancy. In code fomatting you can use your own style guide or use a popular fully-fledged style guide(Airbnb React/JSX Style Guide, Facebook Style Guide, etc). If you start to follow anyone of the style follow that don’t confuse with others.
When creating an array of JSX elements react requires you to add a key prop to your element. This is commonly done using a map function which in turn results in people using an index to set to the key property. This is bad! React uses the key property to track each element in the array and due to the collapsing nature of an array. This can easily result in the wrong information being rendered in the wrong place. This is especially apparent when looping through class components with the state.
When Creating React component it is important to keep in mind that you are still building an HTML document. People tend to get divitis in React which ultimately leads to incorrect HTML.
In the above example, the div would end up being a direct child of ul which is incorrect HTML vs the below example where the li end up being the direct child of ul, forming correct HTML.
We can use another approach that uses <React.Fragment> tags. <React.Fragment> was introduced in React v16.2, we can use them instead of the extraneous <div> tag.
Add a comment in the application where necessary. Removing the ability to comment from an application meant I HAVE to write literate code, no exceptions. It gives untidy free code sections. In general, comments are a wart that stipulates poor design, especially long-winded comments where its clear the developer didn’t have a clue what the heck they are doing and tried to make up for it by writing a comment.
Since functional components don’t require this binding you’ll want to use them whenever possible. But if you are using ES6 class, you’ll want to bind this manually since React doesn't auto bind the function within that component. Here are some examples for doing so.
Example 1: Bind in render
adding the following snippet to the render known as bind in render
onClick={this.logMessage.bind(this)}
This way is clear, succinct and works but it can cause a slight performance issue because a new function is going to be called every time this component re-renders which could be frequent.
Example 2: Arrow function in render.
Adding the following snippet to the render known as arrow function in render.
onClick={() => this.logMessage()}
This way is clear, succinct like example 1, but like example 1 it will also create a new function every time this component renders.
Example 3: Bind in constructor
Adding the following snippet to the constructor known as bind in constructor.
this.logMessage = this.logMessage.bind(this);
This way is going to solve the potential performance issue of Examples 1 and 2. Don’t forget to call super in the constructor.
Example 4: Arrow function in Class property
Adding the following snippet to the class known as arrow function in class property.
logMessage = () => {const { message } = this.state;console.log(message);}
This way is very clean, readable and it’s going to avoid performance issues of Examples 1 and 2 and avoid the repetition in Example 3. Be aware however that this method does rely on experimental features and it’s not an official part of the ECMA Script specification. You are able to experiment language features by installing and configuring the babel package and apps created by a create react app has many features enabled.
We can divide the heading into two subheadings such as.
Don’t use props during the initial state.
Don’t initialize component states inside class constructors.
When you use props in the initial state the problem is that the constructor is called when the component is created. So the constructor is only called once. If you change something to the props next time, the component state will not update and it remains the same as the previous value. You can fix the problem using react lifecycle method componentDidUpdate. The componentDidUpdate method updates the component when props changed. componentDidUpdate won’t be invoked on the initial render. But, using props in the initial state is not the best practice.
Initializing states as class fields is the best practice. Initializing component state with the constructor is not that much bad practice but it increases the redundancy in your code and makes some performance issues. When you initialize the state inside the class constructor it unwantedly calls super and remembering about props, it makes performance issue.
Another issue is when you are going to initialize state inside the constructor think about the number of lines that you need, want you need constructor(),super()?
Name a function or a component after typing the scripts because they should be easily identifiable. For example, you choose the name of a component like FacebookButton instantly because of the component code. But in the future, you may use that component as TwitterButton,YoutubeButton. So, the best practice is to name that component as Button. Normally when you finish the function, you should be able to choose the common name for the component and function. Naming in the end increases the reusability.
In React, when we can categorize the components by state. There are stateful and stateless. Stateful component store component’s state information and provide necessary context. In the other way around stateless components have no memory and can’t give context to the part of the user interface. Stateless components are scalable, reusable and like pure JavaScript functions. Separates the stateful fetching logic from rendering stateless logic. One better way is to use a stateful component to fetch data and another stateless component to display that fetched data.
After React v16.08 there is a new feature called ‘React Hooks’. React Hooks write stateful functional components. React Hooks obliterate the use of class components.
If data is not being directly rendered in the render method it should not be in the component state. Data that is not being directly rendered can cause unnecessary re-renders.
According to the React Docs React doesn’t guarantee that stage changes are applied immediately. Therefore reading this.state right after calling setState is a potential pitfall because this.state may not actually be what you think it is.
const { ischecked } = this.state;this.setState({ischecked: !ischecked});
Instead of updating the state within an object like the above snippet, we can use the following function.
this .setState((prevState, props) => {return {ischecked: !prevState.ischecked}})
The above function will receive the previous state as its first argument, and props at the time the update is applied as its second argument. State update is an async operation, so to update the state object, we need to use updater function with setState.
When you are working in React remember that you are using JSX (JavaScript Extension) instead of HTML. The component created by you should be named in the upper camel case, a.k.a Pascal Case. The upper camel case means words are written without spaces, and the first letter of each word is capitalized. For example, If there is a component named as selectbutton then you should name it as SelectButton instead of selectbutton. Using the upper camel case helps to JSX to differentiate the default JSX element tags from created elements. However, you can use lower case letters to name a component but it is not a best practice.
The ‘prop-types’ is a library for type checking props and it can help prevent bugs by ensuring you are using the right data types for your props. React.PropTypes has moved into a different package since React v15.5. React.PropTypes package gives us the ability to type check a component’s props and give it default values. So you are going to use an external library by npm install.
npm i prop-types
Import the library, add PropTypes to the component, set the data type accordingly and if the prop is required, add isRequired like below.
Default values can be assigned to the props using defaultProps. When a component does not receive its props, it refers to the defaultProps that has been assigned. It is not necessary to assign defaultProps, if you have marked your props as required. In the code snippet below you can see all the default values that have been assigned to the props for ModalButton. For this example, I used React Bootstrap framework.
Always define explicit defaultProps for all optional props
It is important to note that do type-checking using PropsTypes after assigned the defaultProps. Therefore it type-checks the default values assigned to the props as well.
During my internship works we faced a problem in styling, and especially theming. The CSS was loaded in the development environment but it didn’t load in the production environment. My Teammate Harith Sankalpa wrote about that problem. But now I found so many best approaches according to different applications.
When you have a big CSS (SCSS)file you can use the global prefix followed by the Block-Element-Modifier convention to avoid name collision. When your application becomes bigger this method is not scalable. So you have to evaluate your CSS(SCSS) file. There is another approach to extract CSS via webpack’s Mini CSS Extract Text plugin (it requires webpack 4 to work) but it creates heavy dependency on the webpack. If you use this method, testing your component is difficult. Best practice is to have an easily testable application therefore, following this approach is not the best practice.
EmotionJS, Glamorous and Styled Components are some of the new arrived CSS in JS libraries. You can use these depending on your use cases. When you need to spit out a compiled CSS for production you could use the EmotionJS library. When you have a complicated theming issue you can use Glamorous and Styled Component libraries.
Not only in React but also in other programming languages you should do testing. Testing is important, because it ensures that the code behaves as expected and testable easily and quickly. In best practice, create a __Test__ folder inside the component folder. Create test files with the name of the component with a .test.js suffix. You can use Jest as a test runner and Enzyme as a testing utility for React. My Teammate Kavindu Vindika wrote about Jest and Enzyme Testing, if you want you can check it out.
Crash testing a component is a simple fast way to ensure all your components are functioning without crashing. Component crash testing is easy to throw into every component you make.
You should be doing obviously more extensive testing than the crash testing. If you write more test cases it will give more test coverage for your code. But, very least you should be doing some kind of crash testing. In crash testing what we do is create an element and then it uses ReactDom and mounts whatever component you imported into that the div was just created and then it unmounts div.
A true React developer do proper testing for the entire react application.
ESlint keeps your code nice and tidy by yelling at you with squigglies. You can link this to your IDE. The best practice is to keep your own ESLint configuration file.
A good Developer fix all ESlint errors and warnings rather than disabling that error.
Prettier is a code formatting tool. Prettier has a set of rules for code formatting and indention. You can use Sonarlint to check spells, function length and suggestions for better approaches. Using Husky is not only a good practice for React but also a good practice for Git. You can define the husky in package.json file. Husky prevents your application from bad commit and bad push.
Code snippets help you to code best and trend syntax. They keep your code relatively error-free. You can use a lot of snippet libraries such as ES7 React, JavaScript (ES6) code snippets, etc.
React Developer Tools is available as an extension for Chrome and Firefox. If you use Safari or another standalone shell use the following command to install it.
npm install -g react-devtools@^4
If you are looking for a web application built in React, you can see in the Components tab, the component hierarchy. If you click on a component you can view the props and state of that component. As you can see React Developer Tools extension is very valuable tool to test and debug and really understand what’s happening with that app.
This article describes the best practices in React. These practices improve your application performance, your application code, and your coding skills. As my 25th article, I would like to update this article dynamically. That means I will update this article with the new trends. If I update this article I will inform via Twitter. Keep in touch. Woohoo!!! 🙌
Happy coding 😎
Follow me on Twitter and Medium if you’re interested in more in-depth and informative write-ups like these in the future!
|
[
{
"code": null,
"e": 470,
"s": 172,
"text": "During my Internship period in Sysco LABS, I received significant exposure to React Js. For our project, we used React Js, and we followed React best practices. Therefore my team lead and my mentor Nadun Indunil suggested that I write about React best practices. This is my 25th article in Medium."
},
{
"code": null,
"e": 711,
"s": 470,
"text": "React is a JavaScript library for developing user interfaces. React library was created by Facebook. React allows for integration with many exciting components, libraries and frameworks. Admittedly, developers can make their own components."
},
{
"code": null,
"e": 1043,
"s": 711,
"text": "Before the best practices, I would suggest Test-driven Development when you develop a react application. Test-driven Development means write a test first and then develop your code according to the tests. It is easier to identify the bugs. If you follow another Software development process when you find a bug, write a test first."
},
{
"code": null,
"e": 1457,
"s": 1043,
"text": "File organizationTiny and functional componentsReusability componentsDelete Redundant codeIndex as keysUnnecessary <div>sNecessary Comments onlyUnderstand to handle ‘this’Props — State — ConstructorNaming in the endAware of State and RenderingAvoid objects inside the ‘setState’Use Upper Camel Case NamesUtilize prop-typesCSS in JavaScriptTestingUse ESLint, Prettier and snippet librariesUse React Developer Tools"
},
{
"code": null,
"e": 1475,
"s": 1457,
"text": "File organization"
},
{
"code": null,
"e": 1506,
"s": 1475,
"text": "Tiny and functional components"
},
{
"code": null,
"e": 1529,
"s": 1506,
"text": "Reusability components"
},
{
"code": null,
"e": 1551,
"s": 1529,
"text": "Delete Redundant code"
},
{
"code": null,
"e": 1565,
"s": 1551,
"text": "Index as keys"
},
{
"code": null,
"e": 1584,
"s": 1565,
"text": "Unnecessary <div>s"
},
{
"code": null,
"e": 1608,
"s": 1584,
"text": "Necessary Comments only"
},
{
"code": null,
"e": 1636,
"s": 1608,
"text": "Understand to handle ‘this’"
},
{
"code": null,
"e": 1664,
"s": 1636,
"text": "Props — State — Constructor"
},
{
"code": null,
"e": 1682,
"s": 1664,
"text": "Naming in the end"
},
{
"code": null,
"e": 1711,
"s": 1682,
"text": "Aware of State and Rendering"
},
{
"code": null,
"e": 1747,
"s": 1711,
"text": "Avoid objects inside the ‘setState’"
},
{
"code": null,
"e": 1774,
"s": 1747,
"text": "Use Upper Camel Case Names"
},
{
"code": null,
"e": 1793,
"s": 1774,
"text": "Utilize prop-types"
},
{
"code": null,
"e": 1811,
"s": 1793,
"text": "CSS in JavaScript"
},
{
"code": null,
"e": 1819,
"s": 1811,
"text": "Testing"
},
{
"code": null,
"e": 1862,
"s": 1819,
"text": "Use ESLint, Prettier and snippet libraries"
},
{
"code": null,
"e": 1888,
"s": 1862,
"text": "Use React Developer Tools"
},
{
"code": null,
"e": 3567,
"s": 1888,
"text": "File organization is not only the best practice for react applications, but also it is the best for other applications as well. The file structure of create-react-app is one possible way of organizing your react files. While there is not necessarily one file structure that is better than another, it important to keep your files organized. In React, your file structure will grow rapidly, considering every component has at least one file associated with it. Keep an assets folder that contains top-level CSS, images, and font files. Maintain a helpers folder to put other files for any kind of file for functionalities. Keep all the files related to a component into one folder. Usually, the component folder contains more than a single component file, such as test file CSS and one or more component files. If there are any minor components used by a particular component only, better to keep those all small components in the component folder. When you keep your large components in their own folder and the small components that are used by the components are in a subfolder is easier to understand the file hierarchy. developers mainly named the main component file inside a file index.js. This can become cumbersome to navigate once you have several files, all named as index.js. The solution for this is to add a package.json file to each of your components folders, set the main entry point for this corresponding folder. For instance, for button component main entry point is Button.js. Adding package.json to each folder is not a good practice but It helps to easily handle your files. So we can add the following package.json file inside the button component folder."
},
{
"code": null,
"e": 4417,
"s": 3567,
"text": "When you use Redux in your React project you can use Rails-style or Domain-style or “Ducks” pattern folder structure according to your project. In Rails-style pattern, separate folders are used for “actions”, “constants”, “reducers”, “containers”, and “components”. In Domain-style pattern, separate folders are used per feature or domain, possibly with sub-folders per file type. “Ducks” pattern is similar to domain style, but it explicitly ties together actions and reducers, often by defining them in the same file. However, folder structure could be something developers wish but there should be an easy way to handle components. React says, it doesn’t have opinions on how you put files into folders. New teams to react use Duck style. When they get matured they start to use rails. Rails has its advantage of understanding the project easily."
},
{
"code": null,
"e": 4455,
"s": 4417,
"text": "Dan Abramov tweeted a solution that 👉"
},
{
"code": null,
"e": 4496,
"s": 4455,
"text": "moves files around until it feels right."
},
{
"code": null,
"e": 4583,
"s": 4496,
"text": "That’s exactly what you should do. You should move files around until they feel right."
},
{
"code": null,
"e": 4939,
"s": 4583,
"text": "As we all know, React will work with large components. But if we break them into small sizes, we can reuse them. Small components are easier to read, test, maintain, and reuse. Most beginners in React create Class components even when they aren’t using component state or life cycle methods. Functional components are more efficient for simple components."
},
{
"code": null,
"e": 4992,
"s": 4939,
"text": "The above Class component could be written as below."
},
{
"code": null,
"e": 5035,
"s": 4992,
"text": "Advantages of using Functional Components."
},
{
"code": null,
"e": 5045,
"s": 5035,
"text": "Less code"
},
{
"code": null,
"e": 5066,
"s": 5045,
"text": "Easier to understand"
},
{
"code": null,
"e": 5076,
"s": 5066,
"text": "Stateless"
},
{
"code": null,
"e": 5091,
"s": 5076,
"text": "Easier to test"
},
{
"code": null,
"e": 5117,
"s": 5091,
"text": "There is no this binding."
},
{
"code": null,
"e": 5155,
"s": 5117,
"text": "Easier to extract smaller components."
},
{
"code": null,
"e": 5649,
"s": 5155,
"text": "When you are using functional component you have no control over the re-rendering process. When something changes or even component changes itself, React will re-render functional components. In former react versions has a solution to use React.PureComponent. PureComponent allows shallow props and state comparison. When props or content of the component or component itself changed component will re-render. Otherwise, PureComponent skip re-render and reuse the last rendered result instead."
},
{
"code": null,
"e": 6052,
"s": 5649,
"text": "After React v16.6.0 React introduces a new feature that was memo. Memo shallowly compare props. When props or content of the component or component itself changed component will re-render. Based on the comparison react will either reuse last rendered result or re-render. Memo allows you to create an unadulterated functional component. Memo obliterate the use of stateful components and PureComponent."
},
{
"code": null,
"e": 6279,
"s": 6052,
"text": "Each functional component should have one function that means one functional component is equal to one function. When you are creating a functional component with one function you can improve the reusability of that component."
},
{
"code": null,
"e": 6928,
"s": 6279,
"text": "Not only in React but also in all application development the common rule is keeping the code is succinct and tiny as much as possible. React best practices instruct to keep the error-free code and incisive code. Don’t Repeat Yourself (DRY) is a principle of software development focused at minimizing repetition of software patterns, replacing it with abstractions or using data normalization to avoid redundancy. In code fomatting you can use your own style guide or use a popular fully-fledged style guide(Airbnb React/JSX Style Guide, Facebook Style Guide, etc). If you start to follow anyone of the style follow that don’t confuse with others."
},
{
"code": null,
"e": 7426,
"s": 6928,
"text": "When creating an array of JSX elements react requires you to add a key prop to your element. This is commonly done using a map function which in turn results in people using an index to set to the key property. This is bad! React uses the key property to track each element in the array and due to the collapsing nature of an array. This can easily result in the wrong information being rendered in the wrong place. This is especially apparent when looping through class components with the state."
},
{
"code": null,
"e": 7612,
"s": 7426,
"text": "When Creating React component it is important to keep in mind that you are still building an HTML document. People tend to get divitis in React which ultimately leads to incorrect HTML."
},
{
"code": null,
"e": 7799,
"s": 7612,
"text": "In the above example, the div would end up being a direct child of ul which is incorrect HTML vs the below example where the li end up being the direct child of ul, forming correct HTML."
},
{
"code": null,
"e": 7961,
"s": 7799,
"text": "We can use another approach that uses <React.Fragment> tags. <React.Fragment> was introduced in React v16.2, we can use them instead of the extraneous <div> tag."
},
{
"code": null,
"e": 8372,
"s": 7961,
"text": "Add a comment in the application where necessary. Removing the ability to comment from an application meant I HAVE to write literate code, no exceptions. It gives untidy free code sections. In general, comments are a wart that stipulates poor design, especially long-winded comments where its clear the developer didn’t have a clue what the heck they are doing and tried to make up for it by writing a comment."
},
{
"code": null,
"e": 8639,
"s": 8372,
"text": "Since functional components don’t require this binding you’ll want to use them whenever possible. But if you are using ES6 class, you’ll want to bind this manually since React doesn't auto bind the function within that component. Here are some examples for doing so."
},
{
"code": null,
"e": 8665,
"s": 8639,
"text": "Example 1: Bind in render"
},
{
"code": null,
"e": 8732,
"s": 8665,
"text": "adding the following snippet to the render known as bind in render"
},
{
"code": null,
"e": 8769,
"s": 8732,
"text": "onClick={this.logMessage.bind(this)}"
},
{
"code": null,
"e": 8958,
"s": 8769,
"text": "This way is clear, succinct and works but it can cause a slight performance issue because a new function is going to be called every time this component re-renders which could be frequent."
},
{
"code": null,
"e": 8995,
"s": 8958,
"text": "Example 2: Arrow function in render."
},
{
"code": null,
"e": 9073,
"s": 8995,
"text": "Adding the following snippet to the render known as arrow function in render."
},
{
"code": null,
"e": 9107,
"s": 9073,
"text": "onClick={() => this.logMessage()}"
},
{
"code": null,
"e": 9240,
"s": 9107,
"text": "This way is clear, succinct like example 1, but like example 1 it will also create a new function every time this component renders."
},
{
"code": null,
"e": 9271,
"s": 9240,
"text": "Example 3: Bind in constructor"
},
{
"code": null,
"e": 9349,
"s": 9271,
"text": "Adding the following snippet to the constructor known as bind in constructor."
},
{
"code": null,
"e": 9395,
"s": 9349,
"text": "this.logMessage = this.logMessage.bind(this);"
},
{
"code": null,
"e": 9522,
"s": 9395,
"text": "This way is going to solve the potential performance issue of Examples 1 and 2. Don’t forget to call super in the constructor."
},
{
"code": null,
"e": 9566,
"s": 9522,
"text": "Example 4: Arrow function in Class property"
},
{
"code": null,
"e": 9651,
"s": 9566,
"text": "Adding the following snippet to the class known as arrow function in class property."
},
{
"code": null,
"e": 9725,
"s": 9651,
"text": "logMessage = () => {const { message } = this.state;console.log(message);}"
},
{
"code": null,
"e": 10152,
"s": 9725,
"text": "This way is very clean, readable and it’s going to avoid performance issues of Examples 1 and 2 and avoid the repetition in Example 3. Be aware however that this method does rely on experimental features and it’s not an official part of the ECMA Script specification. You are able to experiment language features by installing and configuring the babel package and apps created by a create react app has many features enabled."
},
{
"code": null,
"e": 10208,
"s": 10152,
"text": "We can divide the heading into two subheadings such as."
},
{
"code": null,
"e": 10250,
"s": 10208,
"text": "Don’t use props during the initial state."
},
{
"code": null,
"e": 10311,
"s": 10250,
"text": "Don’t initialize component states inside class constructors."
},
{
"code": null,
"e": 10867,
"s": 10311,
"text": "When you use props in the initial state the problem is that the constructor is called when the component is created. So the constructor is only called once. If you change something to the props next time, the component state will not update and it remains the same as the previous value. You can fix the problem using react lifecycle method componentDidUpdate. The componentDidUpdate method updates the component when props changed. componentDidUpdate won’t be invoked on the initial render. But, using props in the initial state is not the best practice."
},
{
"code": null,
"e": 11227,
"s": 10867,
"text": "Initializing states as class fields is the best practice. Initializing component state with the constructor is not that much bad practice but it increases the redundancy in your code and makes some performance issues. When you initialize the state inside the class constructor it unwantedly calls super and remembering about props, it makes performance issue."
},
{
"code": null,
"e": 11390,
"s": 11227,
"text": "Another issue is when you are going to initialize state inside the constructor think about the number of lines that you need, want you need constructor(),super()?"
},
{
"code": null,
"e": 11897,
"s": 11390,
"text": "Name a function or a component after typing the scripts because they should be easily identifiable. For example, you choose the name of a component like FacebookButton instantly because of the component code. But in the future, you may use that component as TwitterButton,YoutubeButton. So, the best practice is to name that component as Button. Normally when you finish the function, you should be able to choose the common name for the component and function. Naming in the end increases the reusability."
},
{
"code": null,
"e": 12465,
"s": 11897,
"text": "In React, when we can categorize the components by state. There are stateful and stateless. Stateful component store component’s state information and provide necessary context. In the other way around stateless components have no memory and can’t give context to the part of the user interface. Stateless components are scalable, reusable and like pure JavaScript functions. Separates the stateful fetching logic from rendering stateless logic. One better way is to use a stateful component to fetch data and another stateless component to display that fetched data."
},
{
"code": null,
"e": 12631,
"s": 12465,
"text": "After React v16.08 there is a new feature called ‘React Hooks’. React Hooks write stateful functional components. React Hooks obliterate the use of class components."
},
{
"code": null,
"e": 12807,
"s": 12631,
"text": "If data is not being directly rendered in the render method it should not be in the component state. Data that is not being directly rendered can cause unnecessary re-renders."
},
{
"code": null,
"e": 13045,
"s": 12807,
"text": "According to the React Docs React doesn’t guarantee that stage changes are applied immediately. Therefore reading this.state right after calling setState is a potential pitfall because this.state may not actually be what you think it is."
},
{
"code": null,
"e": 13118,
"s": 13045,
"text": "const { ischecked } = this.state;this.setState({ischecked: !ischecked});"
},
{
"code": null,
"e": 13224,
"s": 13118,
"text": "Instead of updating the state within an object like the above snippet, we can use the following function."
},
{
"code": null,
"e": 13305,
"s": 13224,
"text": "this .setState((prevState, props) => {return {ischecked: !prevState.ischecked}})"
},
{
"code": null,
"e": 13561,
"s": 13305,
"text": "The above function will receive the previous state as its first argument, and props at the time the update is applied as its second argument. State update is an async operation, so to update the state object, we need to use updater function with setState."
},
{
"code": null,
"e": 14187,
"s": 13561,
"text": "When you are working in React remember that you are using JSX (JavaScript Extension) instead of HTML. The component created by you should be named in the upper camel case, a.k.a Pascal Case. The upper camel case means words are written without spaces, and the first letter of each word is capitalized. For example, If there is a component named as selectbutton then you should name it as SelectButton instead of selectbutton. Using the upper camel case helps to JSX to differentiate the default JSX element tags from created elements. However, you can use lower case letters to name a component but it is not a best practice."
},
{
"code": null,
"e": 14570,
"s": 14187,
"text": "The ‘prop-types’ is a library for type checking props and it can help prevent bugs by ensuring you are using the right data types for your props. React.PropTypes has moved into a different package since React v15.5. React.PropTypes package gives us the ability to type check a component’s props and give it default values. So you are going to use an external library by npm install."
},
{
"code": null,
"e": 14587,
"s": 14570,
"text": "npm i prop-types"
},
{
"code": null,
"e": 14725,
"s": 14587,
"text": "Import the library, add PropTypes to the component, set the data type accordingly and if the prop is required, add isRequired like below."
},
{
"code": null,
"e": 15142,
"s": 14725,
"text": "Default values can be assigned to the props using defaultProps. When a component does not receive its props, it refers to the defaultProps that has been assigned. It is not necessary to assign defaultProps, if you have marked your props as required. In the code snippet below you can see all the default values that have been assigned to the props for ModalButton. For this example, I used React Bootstrap framework."
},
{
"code": null,
"e": 15201,
"s": 15142,
"text": "Always define explicit defaultProps for all optional props"
},
{
"code": null,
"e": 15372,
"s": 15201,
"text": "It is important to note that do type-checking using PropsTypes after assigned the defaultProps. Therefore it type-checks the default values assigned to the props as well."
},
{
"code": null,
"e": 15685,
"s": 15372,
"text": "During my internship works we faced a problem in styling, and especially theming. The CSS was loaded in the development environment but it didn’t load in the production environment. My Teammate Harith Sankalpa wrote about that problem. But now I found so many best approaches according to different applications."
},
{
"code": null,
"e": 16278,
"s": 15685,
"text": "When you have a big CSS (SCSS)file you can use the global prefix followed by the Block-Element-Modifier convention to avoid name collision. When your application becomes bigger this method is not scalable. So you have to evaluate your CSS(SCSS) file. There is another approach to extract CSS via webpack’s Mini CSS Extract Text plugin (it requires webpack 4 to work) but it creates heavy dependency on the webpack. If you use this method, testing your component is difficult. Best practice is to have an easily testable application therefore, following this approach is not the best practice."
},
{
"code": null,
"e": 16606,
"s": 16278,
"text": "EmotionJS, Glamorous and Styled Components are some of the new arrived CSS in JS libraries. You can use these depending on your use cases. When you need to spit out a compiled CSS for production you could use the EmotionJS library. When you have a complicated theming issue you can use Glamorous and Styled Component libraries."
},
{
"code": null,
"e": 17116,
"s": 16606,
"text": "Not only in React but also in other programming languages you should do testing. Testing is important, because it ensures that the code behaves as expected and testable easily and quickly. In best practice, create a __Test__ folder inside the component folder. Create test files with the name of the component with a .test.js suffix. You can use Jest as a test runner and Enzyme as a testing utility for React. My Teammate Kavindu Vindika wrote about Jest and Enzyme Testing, if you want you can check it out."
},
{
"code": null,
"e": 17299,
"s": 17116,
"text": "Crash testing a component is a simple fast way to ensure all your components are functioning without crashing. Component crash testing is easy to throw into every component you make."
},
{
"code": null,
"e": 17695,
"s": 17299,
"text": "You should be doing obviously more extensive testing than the crash testing. If you write more test cases it will give more test coverage for your code. But, very least you should be doing some kind of crash testing. In crash testing what we do is create an element and then it uses ReactDom and mounts whatever component you imported into that the div was just created and then it unmounts div."
},
{
"code": null,
"e": 17770,
"s": 17695,
"text": "A true React developer do proper testing for the entire react application."
},
{
"code": null,
"e": 17938,
"s": 17770,
"text": "ESlint keeps your code nice and tidy by yelling at you with squigglies. You can link this to your IDE. The best practice is to keep your own ESLint configuration file."
},
{
"code": null,
"e": 18024,
"s": 17938,
"text": "A good Developer fix all ESlint errors and warnings rather than disabling that error."
},
{
"code": null,
"e": 18410,
"s": 18024,
"text": "Prettier is a code formatting tool. Prettier has a set of rules for code formatting and indention. You can use Sonarlint to check spells, function length and suggestions for better approaches. Using Husky is not only a good practice for React but also a good practice for Git. You can define the husky in package.json file. Husky prevents your application from bad commit and bad push."
},
{
"code": null,
"e": 18602,
"s": 18410,
"text": "Code snippets help you to code best and trend syntax. They keep your code relatively error-free. You can use a lot of snippet libraries such as ES7 React, JavaScript (ES6) code snippets, etc."
},
{
"code": null,
"e": 18764,
"s": 18602,
"text": "React Developer Tools is available as an extension for Chrome and Firefox. If you use Safari or another standalone shell use the following command to install it."
},
{
"code": null,
"e": 18797,
"s": 18764,
"text": "npm install -g react-devtools@^4"
},
{
"code": null,
"e": 19135,
"s": 18797,
"text": "If you are looking for a web application built in React, you can see in the Components tab, the component hierarchy. If you click on a component you can view the props and state of that component. As you can see React Developer Tools extension is very valuable tool to test and debug and really understand what’s happening with that app."
},
{
"code": null,
"e": 19495,
"s": 19135,
"text": "This article describes the best practices in React. These practices improve your application performance, your application code, and your coding skills. As my 25th article, I would like to update this article dynamically. That means I will update this article with the new trends. If I update this article I will inform via Twitter. Keep in touch. Woohoo!!! 🙌"
},
{
"code": null,
"e": 19510,
"s": 19495,
"text": "Happy coding 😎"
}
] |
3 Python Libraries for Effective EDA that You Might Have Missed | by Chi Nguyen | Towards Data Science
|
EDA, or exploratory data analysis, is the first stage of every data science endeavor. It is also the first phase of data mining, assisting in acquiring data insights while making no assumptions. Analysts may use EDA to glance at data descriptions, comprehend the relationship between variables, and evaluate data quality by verifying data sources, discovering missing values, and identifying outliers. In short, EDA plays an essential role in generating precise data reports and accurate data models.
For beginners, it may take time to do this initial screening process because of the unfamiliarity with the syntaxes and procedures in data mining. I was in the same situation when first getting to know Python. At the time, I only wished there would be a tool that could do all the jobs for me at once, automatically. Even today, as I get more familiar with data mining and cleaning procedures, I want to save time in some specific processes and move on swiftly.
That’s why today, I’d want to expose you to some powerful EDA tools that may help you gain a better overall perspective of the data we’re diving through.
In Python package seaborn , there are many free data sets to try. However, I will go with the dataset named “diamonds.” Here is how I get the data set:
import seaborn as snsdf = sns.load_dataset('diamonds')
Data source reference: Waskom, M. et al., 2017. mwaskom/seaborn: v0.8.1 (September 2017), Zenodo. Available at: https://doi.org/10.5281/zenodo.883859.
Personally, this is one of my favorite automated EDA. Why? Because of its super cool interface. To prove my saying, in figure 1, you can see the overview of the report produced by SweetViz. Cool, right?
Well, to put it simply, SweetViz Package is an open-source Python library that can automatically launch EDA and create stunning visuals with just a few lines of code. Output is an entirely self-contained HTML application, as shown in Figure 1. SweetViz helps to quickly view different dataset characteristics and primarily provides complete information about the associations between variables. One more outstanding feature of SweetViz is its target analysis, which explains how a target value relates to other variables.
Basically, there are three functions to create reports, which are analyze() , compare() and compare_intra()
First, let’s try to get the summarization of all data set. analyze() is the function you should use in this case.
#Installing the library pip install sweetviz#Importing the library import sweetviz as svreport = sv.analyze(df)report.show_html()
And the result is what you can see in Fig 1 above.
How about when you want to compare two separate data frames? For example, in my case, I want to compare the training and testing set? Very simple, using compare() and here is what I got:
#Spliting data set into training and testing settraining_data = df.sample(frac=0.8, random_state=25)testing_data = df.drop(training_data.index)#Applying compare functionreport2 = sv.compare([training_data,"TRAINING SET"], [testing_data, "TESTING SET"])report2.show_html()
In case you might want to make a comparison between the subsets of your data, compare_intra() is your selection. For instance, figure 3 shows the comparison between the subset of D color and the rest.
report3 = sv.compare_intra(df, df["color"] == "D", ["D", "The rest"])report3.show_html()
If there is one sentence to describe this package, I would say, “it already did all the work.” In other words, we can find almost all the information in the created report. One bonus point of this package is that the output is interactive, which makes the report more convenient to follow.
DataPrep is definitely my favorite automated EDA among all. Similar to SweetViz, this library also helps explore data in just a single line of code. This is all you have to do:
#Installing the library!pip install dataprep#Importing from dataprep.eda import create_report#Creating reportcreate_report(df)
Skimpy is a small Python package that provides an extended version of data summarization. As you can see in Figure 5, the data report is quite simple but includes almost all necessary information. This library is not as complete as previous reports; however, I think this summary is enough to use sometimes. It also runs quicker than the other two libraries.
from skimpy import skimskim(df)
There are many exciting libraries for automated EDA that I will definitely learn further, such as Bamboolib, Autoviz, or Dora. That’s all I have for now.
If you guys have any recommendations, please share them with me :D I’m happy to know more.
|
[
{
"code": null,
"e": 666,
"s": 165,
"text": "EDA, or exploratory data analysis, is the first stage of every data science endeavor. It is also the first phase of data mining, assisting in acquiring data insights while making no assumptions. Analysts may use EDA to glance at data descriptions, comprehend the relationship between variables, and evaluate data quality by verifying data sources, discovering missing values, and identifying outliers. In short, EDA plays an essential role in generating precise data reports and accurate data models."
},
{
"code": null,
"e": 1128,
"s": 666,
"text": "For beginners, it may take time to do this initial screening process because of the unfamiliarity with the syntaxes and procedures in data mining. I was in the same situation when first getting to know Python. At the time, I only wished there would be a tool that could do all the jobs for me at once, automatically. Even today, as I get more familiar with data mining and cleaning procedures, I want to save time in some specific processes and move on swiftly."
},
{
"code": null,
"e": 1282,
"s": 1128,
"text": "That’s why today, I’d want to expose you to some powerful EDA tools that may help you gain a better overall perspective of the data we’re diving through."
},
{
"code": null,
"e": 1434,
"s": 1282,
"text": "In Python package seaborn , there are many free data sets to try. However, I will go with the dataset named “diamonds.” Here is how I get the data set:"
},
{
"code": null,
"e": 1489,
"s": 1434,
"text": "import seaborn as snsdf = sns.load_dataset('diamonds')"
},
{
"code": null,
"e": 1640,
"s": 1489,
"text": "Data source reference: Waskom, M. et al., 2017. mwaskom/seaborn: v0.8.1 (September 2017), Zenodo. Available at: https://doi.org/10.5281/zenodo.883859."
},
{
"code": null,
"e": 1843,
"s": 1640,
"text": "Personally, this is one of my favorite automated EDA. Why? Because of its super cool interface. To prove my saying, in figure 1, you can see the overview of the report produced by SweetViz. Cool, right?"
},
{
"code": null,
"e": 2365,
"s": 1843,
"text": "Well, to put it simply, SweetViz Package is an open-source Python library that can automatically launch EDA and create stunning visuals with just a few lines of code. Output is an entirely self-contained HTML application, as shown in Figure 1. SweetViz helps to quickly view different dataset characteristics and primarily provides complete information about the associations between variables. One more outstanding feature of SweetViz is its target analysis, which explains how a target value relates to other variables."
},
{
"code": null,
"e": 2473,
"s": 2365,
"text": "Basically, there are three functions to create reports, which are analyze() , compare() and compare_intra()"
},
{
"code": null,
"e": 2587,
"s": 2473,
"text": "First, let’s try to get the summarization of all data set. analyze() is the function you should use in this case."
},
{
"code": null,
"e": 2717,
"s": 2587,
"text": "#Installing the library pip install sweetviz#Importing the library import sweetviz as svreport = sv.analyze(df)report.show_html()"
},
{
"code": null,
"e": 2768,
"s": 2717,
"text": "And the result is what you can see in Fig 1 above."
},
{
"code": null,
"e": 2955,
"s": 2768,
"text": "How about when you want to compare two separate data frames? For example, in my case, I want to compare the training and testing set? Very simple, using compare() and here is what I got:"
},
{
"code": null,
"e": 3227,
"s": 2955,
"text": "#Spliting data set into training and testing settraining_data = df.sample(frac=0.8, random_state=25)testing_data = df.drop(training_data.index)#Applying compare functionreport2 = sv.compare([training_data,\"TRAINING SET\"], [testing_data, \"TESTING SET\"])report2.show_html()"
},
{
"code": null,
"e": 3428,
"s": 3227,
"text": "In case you might want to make a comparison between the subsets of your data, compare_intra() is your selection. For instance, figure 3 shows the comparison between the subset of D color and the rest."
},
{
"code": null,
"e": 3517,
"s": 3428,
"text": "report3 = sv.compare_intra(df, df[\"color\"] == \"D\", [\"D\", \"The rest\"])report3.show_html()"
},
{
"code": null,
"e": 3807,
"s": 3517,
"text": "If there is one sentence to describe this package, I would say, “it already did all the work.” In other words, we can find almost all the information in the created report. One bonus point of this package is that the output is interactive, which makes the report more convenient to follow."
},
{
"code": null,
"e": 3984,
"s": 3807,
"text": "DataPrep is definitely my favorite automated EDA among all. Similar to SweetViz, this library also helps explore data in just a single line of code. This is all you have to do:"
},
{
"code": null,
"e": 4111,
"s": 3984,
"text": "#Installing the library!pip install dataprep#Importing from dataprep.eda import create_report#Creating reportcreate_report(df)"
},
{
"code": null,
"e": 4470,
"s": 4111,
"text": "Skimpy is a small Python package that provides an extended version of data summarization. As you can see in Figure 5, the data report is quite simple but includes almost all necessary information. This library is not as complete as previous reports; however, I think this summary is enough to use sometimes. It also runs quicker than the other two libraries."
},
{
"code": null,
"e": 4502,
"s": 4470,
"text": "from skimpy import skimskim(df)"
},
{
"code": null,
"e": 4656,
"s": 4502,
"text": "There are many exciting libraries for automated EDA that I will definitely learn further, such as Bamboolib, Autoviz, or Dora. That’s all I have for now."
}
] |
Creating a Flask App to Classify Consumer Complaints using Natural Language Processing (Multi-class Classification with TFIDF/Word2Vec) | by Xian Jin Seow | Towards Data Science
|
In part 1 of this series, I will cover the workflow in obtaining the working model that churns out these classifications. This post will be continued in part 2, which involves building the Flask App of this model. So if you’re solely interested in the Flask portion, click here (still WIP) to head on over to that post!
Without further ado, let’s jump into part 1 of this series.
I am dissatisfied with the current outcome of a dispute that was initiated with Discover Card regarding a single transaction that occurred on XXXX/XXXX/2015 in the amount of {$280.00}. I have corresponded with Discover Card at least four times since XXXX/XXXX/2015 ( which I have enclosed as an attachment to this complaint ). I believe that the credit card issuer has violated consumer protection laws by failing to implement the Special Rule for Credit Card Purchase protection despite overwhelming paperwork evidence submitted by me that shows the merchant has conducted business in bad faith less favorable to the consumer. I have sustained a monetary loss as a result of merchants bad faith and intent. I have patiently utilized the internal Discover Card dispute process over the past three months with the credit card issuer always favoring the merchant ; I have repeatedly submitted irrefutable paperwork evidence that has shown that the merchant has conducted business in bad faith. I have tried in good faith to address my complaint with the merchant and Discover Card but believe that I will not receive a favorable outcome.I suffered a work-related injury in XXXX and am now permanently XXXX. My income has dropped substantially in the past 5 years and I am now on a low fixed income. On XXXX separate occasions from XXXX to XXXX I had zero income and had to use my Sams Club card to purchase food, thus running up debt out of necessity. I am currently in the process of attempting to pay down my Sams Club ( Synchrony Bank ) card, and stopped using the card some time ago. I have always made at least minimum payments and have never missed a payment. Despite this, my interest rate has been unilaterally raised three times in the past two years, and is now at 23.15 %. I called a Sams Club account rep today to file a complaint over the phone, because I am never going to be able to pay down this card when I am paying almost {$50.00} a month in interest and can only afford to pay the minimum payment + {$4.00} or {$5.00} dollars. They would not work with me, which I expected. In my opinion, Synchrony Bank is taking unfair advantage of recent interest rate hikes to gouge customers, especially those who are financially unable to make substantial monthly payments on their accounts. Therefore I am contacting the CFPB to file a complaint through which I might receive some relief.
Did you read read the wall of text above? Chances are you didn’t (because I wouldn’t either). Who has the time to read a whole chunk of text with no headers, no summary and terrible formatting (bold, spacing, etc.) that potentially holds no relevance to you?
If you actually read the texts above, you’d realize they’re actually customer complaints. And as Mr Gates once mentioned:
There is so much we can learn from our customers’ complaints. The best brands always connect with their consumers and make decisions revolving around them (think Paramount, who actually pushed the release of the Sonic movie to a later date and changed the design of our favorite blue hedgehog because of the terrible reviews and the countless memes that ensued).
Understanding your customers is important and all, but it doesn’t change the fact that a wall of text from an angry customer is not only strenuous to read through, but also demotivating. And often times it’s not going to be just one complaint.
Typically, in banks (or any customer service department of large companies), they see thousands of complaints like these on a daily basis and they’re not exactly going to be as pleasantly phrased and formatted as the ones above.
Furthermore, the complaints can be filed into the wrong sections by the consumers themselves, and it is going to be a huge pain to go through every single complaint and direct them to the relevant departments to be dealt with. And needless to say, these slow processing times also lead to slow response times to the customers, leading to your already-angry customers becoming angrier.
Man, if only there were some way to quickly categorize each complaint in order to speed up your reading process.
Well — turns out there is, which is the very purpose of this project. In my project, I developed a model that can correctly classify a customer complaint according to it’s product type, with an accuracy of 83%.
The app utilizes a machine learning algorithm in conjunction with Natural Language Processing (NLP) methodologies to process text to make a prediction on the type of product the complaint is referring to.
This is essentially a supervised (labelled) text multi-class classification problem, of which our goal is to make a prediction (assign to correct category) with a new input (complaint). In the steps below, I will take you through the following:
Data Exploration (Understanding the dataset)
Data (text) Pre-processing and the general steps one might take in an NLP project
Model selection and why Micro-F1 is used as an evaluation metric
Selected model final test and results
In Part 2 of the Series...
Flask App demonstration & how to build one
All the code to this project can be found here at my github. Feel free to drop me a message should you need any clarification.
The data used to train this model is taken from here. And an explanation of what each column means can be found here. It is essentially a labelled dataset provided by the Consumer Financial Protection Bureau (CFPB) about complaints received about financial products and services.
We observe that the dataset contains 1,437,716 rows of data and many, many rows containing null values.
<class 'pandas.core.frame.DataFrame'>RangeIndex: 1437716 entries, 0 to 1437715Data columns (total 18 columns):Date received 1437716 non-null objectProduct 1437716 non-null objectSub-product 1202551 non-null objectIssue 1437716 non-null objectSub-issue 887045 non-null objectConsumer complaint narrative 463991 non-null objectCompany public response 530104 non-null objectCompany 1437716 non-null objectState 1414039 non-null objectZIP code 1304830 non-null objectTags 196144 non-null objectConsumer consent provided? 831624 non-null objectSubmitted via 1437716 non-null objectDate sent to company 1437716 non-null objectCompany response to consumer 1437715 non-null objectTimely response? 1437716 non-null objectConsumer disputed? 768482 non-null objectComplaint ID 1437716 non-null int64dtypes: int64(1), object(17)memory usage: 197.4+ MB
However, since we are solely analyzing the complaint itself, we need only the Product and Consumer Complaint Narrative columns.
After only keeping the columns we need, removing the null values and renaming them into something nicer to work with, we are left with just 463,991 rows of data:
<class 'pandas.core.frame.DataFrame'>Int64Index: 463991 entries, 4 to 1437711Data columns (total 2 columns):PRODUCT 463991 non-null objectCONSUMER_COMPLAINT 463991 non-null objectdtypes: object(2)memory usage: 10.6+ MB
Doing a little bit of EDA (exploratory data analysis) on the PRODUCT column, we observe 18 classes with the following distribution:
Some of the classes (products), however, overlap. For instance, Credit card or prepaid card clash with Credit card and Prepaid card. Additionally, there is also a problem with having 463,991 rows to perform analysis on (I doubt your laptop will be able to handle the processing and model training at the later part of this project. Mine couldn’t).
After removing a few product classes, combining some classes together and reducing the number of observations by 90% (the specifics of which can be found in my jupyter notebook on my github), we are left with around 30,000 rows of complaints (of which is manageable for a laptop with 8GB ram).
<class 'pandas.core.frame.DataFrame'>Int64Index: 31942 entries, 72 to 1437623Data columns (total 2 columns):PRODUCT 31942 non-null objectCONSUMER_COMPLAINT 31942 non-null objectdtypes: object(2)memory usage: 748.6+ KB
With the following distribution:
Not too shabby. Now we are ready to do some text pre-processing on our complaint data!
Now that we have our data, we need to go through the cleaning process. For text data sets in general, this often includes:
Removal of punctuation
Removal of stop words (things like “the”, “this”, “what”)
Lowercase
Tokenization
Stemming/lemmatization (reducing words down to their base form by removing suffixes like “-ed”, “-ing”)
If you are dealing with online text and comments, you will require further removal of items like hyperlinks, usernames, and automated messages.
What pre-processing you do varies from project to project, and for this I achieved the best accuracy score doing all of the above except stemming and lemmatization. I considered using bi-grams, but that caused me to consistently run into memory issues, and I had to therefore move forward with only considering 1-gram (standard single-word tokenization).
Below is a sample illustration of punctuation removal, stop-word removal, lower-casing and thereafter tokenization.
To turn words into something a machine learning algorithm can understand and process, we need to do something called vectorization. Put simply, this is the process of turning words into multi-dimensional vectors in such a way that the meaning or context of the word is correlated with where that vector points. In a sense, vectorization allows computers to quantify the meaning of words by mapping similar word meanings to similar vector spaces.
For this application, we want context-based vectorization. This is where Term frequency inverse document frequency vectorization comes in (TF-IDF). This vectorization method looks at the number of times a word appears in a comment relative to the number of times it appears in other comments. Two things result in a higher TF-IDF score:
Higher frequency of the word within the specific complaint being scored.Lower frequency of the word across all other complaints.
Higher frequency of the word within the specific complaint being scored.
Lower frequency of the word across all other complaints.
In a multi-class scenario, it isn’t as simple as Precision, Recall and F1 anymore as per a binary-classification (as with my previous project on Classifying Defaulters). It’s on a whole new level. I recommend referring to Boaz Shmueli’s explanation on evaluation metrics in multi-class classifiers if you need a better understanding on the evaluation metrics used for models in a multi-classification scenario. He does a really good job explaining regarding precision, recall and F1 scoring on both binary and multi-class classification metrics.
As with this mutli-classifcation case, I have decided to use Micro-F1 as an evaluation metric between models for it measures the model’s overall accuracy.
I have decided to use the following models for the multi-class text classification:
Multinomial Naive BayesGaussian Naive BayesLogistic RegressionRandom ForestLinearSVC
Multinomial Naive Bayes
Gaussian Naive Bayes
Logistic Regression
Random Forest
LinearSVC
Each model is cross-validated on a stratified 5-fold split train-validation (of 80% of the whole dataset). The remaining 20% data was held out and untouched to simulate how our final chosen model would perform in real-life scenarios where it would have to deal with inputs it had never seen before.
As always, the code behind how this was done can be found on my jupyter notebook (Section 3 onwards in the notebook) on github.
From our preliminary training results, we see that:
Logistic Regression gives us the highest accuracy of 83%.
83% is a pretty good accuracy. But can we do better? We can’t be sure if it WILL be better, but we can always try and strive for improvement.
Instead of utilizing Vectorization (Tf-idfVectorizer that we used above), we can utilize WordEmbedding on the complaints before feeding them into our classifiers. To understand more about WordEmbeddings, you can find it here.
Some methods such as Word2Vec and spaCy involve pre-trained, multi-gigabyte models that are trained on hundreds of thousands, if not millions of documents and then reduce the meanings of words to a set of a couple hundred numbers. These models are excellent at preserving context and meaning of words in general, but they are slow and large.
I have chosen to use Standford’s GloVe (in increasing complexity) and Google’s Word2Vec for this project.
Compiling all results from the tests, we find that the vanilla TFidfVectorizer does way better than the WordEmbeddings, with the highest accuracy of 83%.
Thus, TfidfVectorizer using Logistic Regression is selected as the text pre-processing and model combination to use for this project.
Remember the 20% data we heldout earlier that we didn’t use in the cross-validation? Here comes the part where we use it as an estimate as to how well our model will perform on unseen data (i.e. how it would perform in real-life scenarios).
The model returns us a whooping 83% accuracy on unseen data! Signifying that it can correctly classify a complaint 83% of the time! Now that we have our model, we can finally see it in action!
To be able to utilize our model in a user-friendly way, I created a Flask app that allows a complaint to be typed in. Thereafter, the app will predict which product category the complaint belongs to. Refer to this post (WIP) to find out how the Flask app is created!
I am dissatisfied with the current outcome of a dispute that was initiated with Discover Card regarding a single transaction that occurred on XXXX/XXXX/2015 in the amount of {$280.00}. I have corresponded with Discover Card at least four times since XXXX/XXXX/2015 ( which I have enclosed as an attachment to this complaint ). I believe that the credit card issuer has violated consumer protection laws by failing to implement the Special Rule for Credit Card Purchase protection despite overwhelming paperwork evidence submitted by me that shows the merchant has conducted business in bad faith less favorable to the consumer. I have sustained a monetary loss as a result of merchants bad faith and intent. I have patiently utilized the internal Discover Card dispute process over the past three months with the credit card issuer always favoring the merchant ; I have repeatedly submitted irrefutable paperwork evidence that has shown that the merchant has conducted business in bad faith. I have tried in good faith to address my complaint with the merchant and Discover Card but believe that I will not receive a favorable outcome.
Remember this horrible wall of text we saw at the beginning of the post? Let’s put our model to the test. Take your time to read it and guess which of these categories it falls under.
Now let’s put our app to the test.
Did you come to the same conclusion as the app did? Now let’s try this with a more difficult complaint, full of typos, caps and millennial lingo.
Omg where is my money?????? AOSINIONSAD WHY DID YOU GUYS TAKE MY MONEY AWAY. SAOIDNSIOADNOIAODNNIOASDNSADNOSDNOASDNI TRANSFERRED IT LAST NIGHT AND I WOKE UP TO NOTHING IN!!!!!! MY BANK ACCOUNT. HELP PLEASE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!I NEED THE MONEY OR ELSE I WILL BE HUNTED BY LOAN SHARKS!!!!!!!!YOU *(#&$) PEOPLE HAVE NO RIGHT TO DO THIS TO ME!!!! I NEED MY MONEY!!!!
We see that the app can handle messy complaints with no errors and correctly classify what product category they fall into as well.
The utilization of this app can bring about a plethora of benefits, from freeing up manpower to increasing efficiency of sifting through customer complaints.
As an augmentation to this app to improve it’s usefulness, we can perhaps look into the following:
Topic SummarizationCurrently, the app only classifies the complaint into the correct product category. While it does file the complaint into it’s correct category, the customer complaint officer would still have to read through the complaint itself. It would be nice for the app to be able to also provide a short abstract of what the complaint is about. This would be an interesting topic to look into and devise how to create this functionality.
Complaint PrioritizationWe can look into also implementing Sentiment Analysis to provide some sort of complaint prioritization. Angrier-sounding complaints (i.e., angry customers) can be given a higher priority, since angry customers tend to provide the most problems. Our app would therefore have an automated sorting for the customer complaint officer as to which complaints need to be urgently attended to.
ask if anyone would like to work on it together, can drop me a text
This has been by no means a short post, and hopefully an informative one in your journey in Data Science. Thank you for taking the time to read this far.
If you learned anything, find this helpful or think it might help someone in this field, do share this post with others!
As always, feel free to hit me up over on my Linkedin or my gmail at xianjinseow92@gmail.com!
|
[
{
"code": null,
"e": 492,
"s": 172,
"text": "In part 1 of this series, I will cover the workflow in obtaining the working model that churns out these classifications. This post will be continued in part 2, which involves building the Flask App of this model. So if you’re solely interested in the Flask portion, click here (still WIP) to head on over to that post!"
},
{
"code": null,
"e": 552,
"s": 492,
"text": "Without further ado, let’s jump into part 1 of this series."
},
{
"code": null,
"e": 2949,
"s": 552,
"text": "I am dissatisfied with the current outcome of a dispute that was initiated with Discover Card regarding a single transaction that occurred on XXXX/XXXX/2015 in the amount of {$280.00}. I have corresponded with Discover Card at least four times since XXXX/XXXX/2015 ( which I have enclosed as an attachment to this complaint ). I believe that the credit card issuer has violated consumer protection laws by failing to implement the Special Rule for Credit Card Purchase protection despite overwhelming paperwork evidence submitted by me that shows the merchant has conducted business in bad faith less favorable to the consumer. I have sustained a monetary loss as a result of merchants bad faith and intent. I have patiently utilized the internal Discover Card dispute process over the past three months with the credit card issuer always favoring the merchant ; I have repeatedly submitted irrefutable paperwork evidence that has shown that the merchant has conducted business in bad faith. I have tried in good faith to address my complaint with the merchant and Discover Card but believe that I will not receive a favorable outcome.I suffered a work-related injury in XXXX and am now permanently XXXX. My income has dropped substantially in the past 5 years and I am now on a low fixed income. On XXXX separate occasions from XXXX to XXXX I had zero income and had to use my Sams Club card to purchase food, thus running up debt out of necessity. I am currently in the process of attempting to pay down my Sams Club ( Synchrony Bank ) card, and stopped using the card some time ago. I have always made at least minimum payments and have never missed a payment. Despite this, my interest rate has been unilaterally raised three times in the past two years, and is now at 23.15 %. I called a Sams Club account rep today to file a complaint over the phone, because I am never going to be able to pay down this card when I am paying almost {$50.00} a month in interest and can only afford to pay the minimum payment + {$4.00} or {$5.00} dollars. They would not work with me, which I expected. In my opinion, Synchrony Bank is taking unfair advantage of recent interest rate hikes to gouge customers, especially those who are financially unable to make substantial monthly payments on their accounts. Therefore I am contacting the CFPB to file a complaint through which I might receive some relief."
},
{
"code": null,
"e": 3208,
"s": 2949,
"text": "Did you read read the wall of text above? Chances are you didn’t (because I wouldn’t either). Who has the time to read a whole chunk of text with no headers, no summary and terrible formatting (bold, spacing, etc.) that potentially holds no relevance to you?"
},
{
"code": null,
"e": 3330,
"s": 3208,
"text": "If you actually read the texts above, you’d realize they’re actually customer complaints. And as Mr Gates once mentioned:"
},
{
"code": null,
"e": 3693,
"s": 3330,
"text": "There is so much we can learn from our customers’ complaints. The best brands always connect with their consumers and make decisions revolving around them (think Paramount, who actually pushed the release of the Sonic movie to a later date and changed the design of our favorite blue hedgehog because of the terrible reviews and the countless memes that ensued)."
},
{
"code": null,
"e": 3937,
"s": 3693,
"text": "Understanding your customers is important and all, but it doesn’t change the fact that a wall of text from an angry customer is not only strenuous to read through, but also demotivating. And often times it’s not going to be just one complaint."
},
{
"code": null,
"e": 4166,
"s": 3937,
"text": "Typically, in banks (or any customer service department of large companies), they see thousands of complaints like these on a daily basis and they’re not exactly going to be as pleasantly phrased and formatted as the ones above."
},
{
"code": null,
"e": 4551,
"s": 4166,
"text": "Furthermore, the complaints can be filed into the wrong sections by the consumers themselves, and it is going to be a huge pain to go through every single complaint and direct them to the relevant departments to be dealt with. And needless to say, these slow processing times also lead to slow response times to the customers, leading to your already-angry customers becoming angrier."
},
{
"code": null,
"e": 4664,
"s": 4551,
"text": "Man, if only there were some way to quickly categorize each complaint in order to speed up your reading process."
},
{
"code": null,
"e": 4875,
"s": 4664,
"text": "Well — turns out there is, which is the very purpose of this project. In my project, I developed a model that can correctly classify a customer complaint according to it’s product type, with an accuracy of 83%."
},
{
"code": null,
"e": 5080,
"s": 4875,
"text": "The app utilizes a machine learning algorithm in conjunction with Natural Language Processing (NLP) methodologies to process text to make a prediction on the type of product the complaint is referring to."
},
{
"code": null,
"e": 5325,
"s": 5080,
"text": "This is essentially a supervised (labelled) text multi-class classification problem, of which our goal is to make a prediction (assign to correct category) with a new input (complaint). In the steps below, I will take you through the following:"
},
{
"code": null,
"e": 5370,
"s": 5325,
"text": "Data Exploration (Understanding the dataset)"
},
{
"code": null,
"e": 5452,
"s": 5370,
"text": "Data (text) Pre-processing and the general steps one might take in an NLP project"
},
{
"code": null,
"e": 5517,
"s": 5452,
"text": "Model selection and why Micro-F1 is used as an evaluation metric"
},
{
"code": null,
"e": 5555,
"s": 5517,
"text": "Selected model final test and results"
},
{
"code": null,
"e": 5582,
"s": 5555,
"text": "In Part 2 of the Series..."
},
{
"code": null,
"e": 5625,
"s": 5582,
"text": "Flask App demonstration & how to build one"
},
{
"code": null,
"e": 5752,
"s": 5625,
"text": "All the code to this project can be found here at my github. Feel free to drop me a message should you need any clarification."
},
{
"code": null,
"e": 6032,
"s": 5752,
"text": "The data used to train this model is taken from here. And an explanation of what each column means can be found here. It is essentially a labelled dataset provided by the Consumer Financial Protection Bureau (CFPB) about complaints received about financial products and services."
},
{
"code": null,
"e": 6136,
"s": 6032,
"text": "We observe that the dataset contains 1,437,716 rows of data and many, many rows containing null values."
},
{
"code": null,
"e": 7281,
"s": 6136,
"text": "<class 'pandas.core.frame.DataFrame'>RangeIndex: 1437716 entries, 0 to 1437715Data columns (total 18 columns):Date received 1437716 non-null objectProduct 1437716 non-null objectSub-product 1202551 non-null objectIssue 1437716 non-null objectSub-issue 887045 non-null objectConsumer complaint narrative 463991 non-null objectCompany public response 530104 non-null objectCompany 1437716 non-null objectState 1414039 non-null objectZIP code 1304830 non-null objectTags 196144 non-null objectConsumer consent provided? 831624 non-null objectSubmitted via 1437716 non-null objectDate sent to company 1437716 non-null objectCompany response to consumer 1437715 non-null objectTimely response? 1437716 non-null objectConsumer disputed? 768482 non-null objectComplaint ID 1437716 non-null int64dtypes: int64(1), object(17)memory usage: 197.4+ MB"
},
{
"code": null,
"e": 7409,
"s": 7281,
"text": "However, since we are solely analyzing the complaint itself, we need only the Product and Consumer Complaint Narrative columns."
},
{
"code": null,
"e": 7571,
"s": 7409,
"text": "After only keeping the columns we need, removing the null values and renaming them into something nicer to work with, we are left with just 463,991 rows of data:"
},
{
"code": null,
"e": 7807,
"s": 7571,
"text": "<class 'pandas.core.frame.DataFrame'>Int64Index: 463991 entries, 4 to 1437711Data columns (total 2 columns):PRODUCT 463991 non-null objectCONSUMER_COMPLAINT 463991 non-null objectdtypes: object(2)memory usage: 10.6+ MB"
},
{
"code": null,
"e": 7939,
"s": 7807,
"text": "Doing a little bit of EDA (exploratory data analysis) on the PRODUCT column, we observe 18 classes with the following distribution:"
},
{
"code": null,
"e": 8287,
"s": 7939,
"text": "Some of the classes (products), however, overlap. For instance, Credit card or prepaid card clash with Credit card and Prepaid card. Additionally, there is also a problem with having 463,991 rows to perform analysis on (I doubt your laptop will be able to handle the processing and model training at the later part of this project. Mine couldn’t)."
},
{
"code": null,
"e": 8581,
"s": 8287,
"text": "After removing a few product classes, combining some classes together and reducing the number of observations by 90% (the specifics of which can be found in my jupyter notebook on my github), we are left with around 30,000 rows of complaints (of which is manageable for a laptop with 8GB ram)."
},
{
"code": null,
"e": 8816,
"s": 8581,
"text": "<class 'pandas.core.frame.DataFrame'>Int64Index: 31942 entries, 72 to 1437623Data columns (total 2 columns):PRODUCT 31942 non-null objectCONSUMER_COMPLAINT 31942 non-null objectdtypes: object(2)memory usage: 748.6+ KB"
},
{
"code": null,
"e": 8849,
"s": 8816,
"text": "With the following distribution:"
},
{
"code": null,
"e": 8936,
"s": 8849,
"text": "Not too shabby. Now we are ready to do some text pre-processing on our complaint data!"
},
{
"code": null,
"e": 9059,
"s": 8936,
"text": "Now that we have our data, we need to go through the cleaning process. For text data sets in general, this often includes:"
},
{
"code": null,
"e": 9082,
"s": 9059,
"text": "Removal of punctuation"
},
{
"code": null,
"e": 9140,
"s": 9082,
"text": "Removal of stop words (things like “the”, “this”, “what”)"
},
{
"code": null,
"e": 9150,
"s": 9140,
"text": "Lowercase"
},
{
"code": null,
"e": 9163,
"s": 9150,
"text": "Tokenization"
},
{
"code": null,
"e": 9267,
"s": 9163,
"text": "Stemming/lemmatization (reducing words down to their base form by removing suffixes like “-ed”, “-ing”)"
},
{
"code": null,
"e": 9411,
"s": 9267,
"text": "If you are dealing with online text and comments, you will require further removal of items like hyperlinks, usernames, and automated messages."
},
{
"code": null,
"e": 9766,
"s": 9411,
"text": "What pre-processing you do varies from project to project, and for this I achieved the best accuracy score doing all of the above except stemming and lemmatization. I considered using bi-grams, but that caused me to consistently run into memory issues, and I had to therefore move forward with only considering 1-gram (standard single-word tokenization)."
},
{
"code": null,
"e": 9882,
"s": 9766,
"text": "Below is a sample illustration of punctuation removal, stop-word removal, lower-casing and thereafter tokenization."
},
{
"code": null,
"e": 10328,
"s": 9882,
"text": "To turn words into something a machine learning algorithm can understand and process, we need to do something called vectorization. Put simply, this is the process of turning words into multi-dimensional vectors in such a way that the meaning or context of the word is correlated with where that vector points. In a sense, vectorization allows computers to quantify the meaning of words by mapping similar word meanings to similar vector spaces."
},
{
"code": null,
"e": 10665,
"s": 10328,
"text": "For this application, we want context-based vectorization. This is where Term frequency inverse document frequency vectorization comes in (TF-IDF). This vectorization method looks at the number of times a word appears in a comment relative to the number of times it appears in other comments. Two things result in a higher TF-IDF score:"
},
{
"code": null,
"e": 10794,
"s": 10665,
"text": "Higher frequency of the word within the specific complaint being scored.Lower frequency of the word across all other complaints."
},
{
"code": null,
"e": 10867,
"s": 10794,
"text": "Higher frequency of the word within the specific complaint being scored."
},
{
"code": null,
"e": 10924,
"s": 10867,
"text": "Lower frequency of the word across all other complaints."
},
{
"code": null,
"e": 11470,
"s": 10924,
"text": "In a multi-class scenario, it isn’t as simple as Precision, Recall and F1 anymore as per a binary-classification (as with my previous project on Classifying Defaulters). It’s on a whole new level. I recommend referring to Boaz Shmueli’s explanation on evaluation metrics in multi-class classifiers if you need a better understanding on the evaluation metrics used for models in a multi-classification scenario. He does a really good job explaining regarding precision, recall and F1 scoring on both binary and multi-class classification metrics."
},
{
"code": null,
"e": 11625,
"s": 11470,
"text": "As with this mutli-classifcation case, I have decided to use Micro-F1 as an evaluation metric between models for it measures the model’s overall accuracy."
},
{
"code": null,
"e": 11709,
"s": 11625,
"text": "I have decided to use the following models for the multi-class text classification:"
},
{
"code": null,
"e": 11794,
"s": 11709,
"text": "Multinomial Naive BayesGaussian Naive BayesLogistic RegressionRandom ForestLinearSVC"
},
{
"code": null,
"e": 11818,
"s": 11794,
"text": "Multinomial Naive Bayes"
},
{
"code": null,
"e": 11839,
"s": 11818,
"text": "Gaussian Naive Bayes"
},
{
"code": null,
"e": 11859,
"s": 11839,
"text": "Logistic Regression"
},
{
"code": null,
"e": 11873,
"s": 11859,
"text": "Random Forest"
},
{
"code": null,
"e": 11883,
"s": 11873,
"text": "LinearSVC"
},
{
"code": null,
"e": 12182,
"s": 11883,
"text": "Each model is cross-validated on a stratified 5-fold split train-validation (of 80% of the whole dataset). The remaining 20% data was held out and untouched to simulate how our final chosen model would perform in real-life scenarios where it would have to deal with inputs it had never seen before."
},
{
"code": null,
"e": 12310,
"s": 12182,
"text": "As always, the code behind how this was done can be found on my jupyter notebook (Section 3 onwards in the notebook) on github."
},
{
"code": null,
"e": 12362,
"s": 12310,
"text": "From our preliminary training results, we see that:"
},
{
"code": null,
"e": 12420,
"s": 12362,
"text": "Logistic Regression gives us the highest accuracy of 83%."
},
{
"code": null,
"e": 12562,
"s": 12420,
"text": "83% is a pretty good accuracy. But can we do better? We can’t be sure if it WILL be better, but we can always try and strive for improvement."
},
{
"code": null,
"e": 12788,
"s": 12562,
"text": "Instead of utilizing Vectorization (Tf-idfVectorizer that we used above), we can utilize WordEmbedding on the complaints before feeding them into our classifiers. To understand more about WordEmbeddings, you can find it here."
},
{
"code": null,
"e": 13130,
"s": 12788,
"text": "Some methods such as Word2Vec and spaCy involve pre-trained, multi-gigabyte models that are trained on hundreds of thousands, if not millions of documents and then reduce the meanings of words to a set of a couple hundred numbers. These models are excellent at preserving context and meaning of words in general, but they are slow and large."
},
{
"code": null,
"e": 13236,
"s": 13130,
"text": "I have chosen to use Standford’s GloVe (in increasing complexity) and Google’s Word2Vec for this project."
},
{
"code": null,
"e": 13390,
"s": 13236,
"text": "Compiling all results from the tests, we find that the vanilla TFidfVectorizer does way better than the WordEmbeddings, with the highest accuracy of 83%."
},
{
"code": null,
"e": 13524,
"s": 13390,
"text": "Thus, TfidfVectorizer using Logistic Regression is selected as the text pre-processing and model combination to use for this project."
},
{
"code": null,
"e": 13765,
"s": 13524,
"text": "Remember the 20% data we heldout earlier that we didn’t use in the cross-validation? Here comes the part where we use it as an estimate as to how well our model will perform on unseen data (i.e. how it would perform in real-life scenarios)."
},
{
"code": null,
"e": 13958,
"s": 13765,
"text": "The model returns us a whooping 83% accuracy on unseen data! Signifying that it can correctly classify a complaint 83% of the time! Now that we have our model, we can finally see it in action!"
},
{
"code": null,
"e": 14225,
"s": 13958,
"text": "To be able to utilize our model in a user-friendly way, I created a Flask app that allows a complaint to be typed in. Thereafter, the app will predict which product category the complaint belongs to. Refer to this post (WIP) to find out how the Flask app is created!"
},
{
"code": null,
"e": 15361,
"s": 14225,
"text": "I am dissatisfied with the current outcome of a dispute that was initiated with Discover Card regarding a single transaction that occurred on XXXX/XXXX/2015 in the amount of {$280.00}. I have corresponded with Discover Card at least four times since XXXX/XXXX/2015 ( which I have enclosed as an attachment to this complaint ). I believe that the credit card issuer has violated consumer protection laws by failing to implement the Special Rule for Credit Card Purchase protection despite overwhelming paperwork evidence submitted by me that shows the merchant has conducted business in bad faith less favorable to the consumer. I have sustained a monetary loss as a result of merchants bad faith and intent. I have patiently utilized the internal Discover Card dispute process over the past three months with the credit card issuer always favoring the merchant ; I have repeatedly submitted irrefutable paperwork evidence that has shown that the merchant has conducted business in bad faith. I have tried in good faith to address my complaint with the merchant and Discover Card but believe that I will not receive a favorable outcome."
},
{
"code": null,
"e": 15545,
"s": 15361,
"text": "Remember this horrible wall of text we saw at the beginning of the post? Let’s put our model to the test. Take your time to read it and guess which of these categories it falls under."
},
{
"code": null,
"e": 15580,
"s": 15545,
"text": "Now let’s put our app to the test."
},
{
"code": null,
"e": 15726,
"s": 15580,
"text": "Did you come to the same conclusion as the app did? Now let’s try this with a more difficult complaint, full of typos, caps and millennial lingo."
},
{
"code": null,
"e": 16097,
"s": 15726,
"text": "Omg where is my money?????? AOSINIONSAD WHY DID YOU GUYS TAKE MY MONEY AWAY. SAOIDNSIOADNOIAODNNIOASDNSADNOSDNOASDNI TRANSFERRED IT LAST NIGHT AND I WOKE UP TO NOTHING IN!!!!!! MY BANK ACCOUNT. HELP PLEASE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!I NEED THE MONEY OR ELSE I WILL BE HUNTED BY LOAN SHARKS!!!!!!!!YOU *(#&$) PEOPLE HAVE NO RIGHT TO DO THIS TO ME!!!! I NEED MY MONEY!!!!"
},
{
"code": null,
"e": 16229,
"s": 16097,
"text": "We see that the app can handle messy complaints with no errors and correctly classify what product category they fall into as well."
},
{
"code": null,
"e": 16387,
"s": 16229,
"text": "The utilization of this app can bring about a plethora of benefits, from freeing up manpower to increasing efficiency of sifting through customer complaints."
},
{
"code": null,
"e": 16486,
"s": 16387,
"text": "As an augmentation to this app to improve it’s usefulness, we can perhaps look into the following:"
},
{
"code": null,
"e": 16934,
"s": 16486,
"text": "Topic SummarizationCurrently, the app only classifies the complaint into the correct product category. While it does file the complaint into it’s correct category, the customer complaint officer would still have to read through the complaint itself. It would be nice for the app to be able to also provide a short abstract of what the complaint is about. This would be an interesting topic to look into and devise how to create this functionality."
},
{
"code": null,
"e": 17344,
"s": 16934,
"text": "Complaint PrioritizationWe can look into also implementing Sentiment Analysis to provide some sort of complaint prioritization. Angrier-sounding complaints (i.e., angry customers) can be given a higher priority, since angry customers tend to provide the most problems. Our app would therefore have an automated sorting for the customer complaint officer as to which complaints need to be urgently attended to."
},
{
"code": null,
"e": 17412,
"s": 17344,
"text": "ask if anyone would like to work on it together, can drop me a text"
},
{
"code": null,
"e": 17566,
"s": 17412,
"text": "This has been by no means a short post, and hopefully an informative one in your journey in Data Science. Thank you for taking the time to read this far."
},
{
"code": null,
"e": 17687,
"s": 17566,
"text": "If you learned anything, find this helpful or think it might help someone in this field, do share this post with others!"
}
] |
How to create headings in HTML page?
|
HTML provides 6 tags to create headings i.e. h1, h2, h3, h4, h5 and h6. Use any of the heading tags <h1> to <h6> and every tag will give you the different size of the heading. The <h1>tag defines the most important heading and <h6> defines the least important heading.
Just keep in mind that you should use these tags inside <body>...</body> tags.
You can try to run the following code to create different headings in an HTML page
<!DOCTYPE html>
<html>
<head>
<title>HTML Headings</title>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>
|
[
{
"code": null,
"e": 1331,
"s": 1062,
"text": "HTML provides 6 tags to create headings i.e. h1, h2, h3, h4, h5 and h6. Use any of the heading tags <h1> to <h6> and every tag will give you the different size of the heading. The <h1>tag defines the most important heading and <h6> defines the least important heading."
},
{
"code": null,
"e": 1410,
"s": 1331,
"text": "Just keep in mind that you should use these tags inside <body>...</body> tags."
},
{
"code": null,
"e": 1493,
"s": 1410,
"text": "You can try to run the following code to create different headings in an HTML page"
},
{
"code": null,
"e": 1800,
"s": 1493,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Headings</title>\n </head>\n\n <body>\n <h1>This is heading 1</h1>\n <h2>This is heading 2</h2>\n <h3>This is heading 3</h3>\n <h4>This is heading 4</h4>\n <h5>This is heading 5</h5>\n <h6>This is heading 6</h6>\n </body>\n</html>"
}
] |
t-SNE Python Example. t-Distributed Stochastic Neighbor... | by Cory Maklin | Towards Data Science
|
t-Distributed Stochastic Neighbor Embedding (t-SNE) is a dimensionality reduction technique used to represent high-dimensional dataset in a low-dimensional space of two or three dimensions so that we can visualize it. In contrast to other dimensionality reduction algorithms like PCA which simply maximizes the variance, t-SNE creates a reduced feature space where similar samples are modeled by nearby points and dissimilar samples are modeled by distant points with high probability.
At a high level, t-SNE constructs a probability distribution for the high-dimensional samples in such a way that similar samples have a high likelihood of being picked while dissimilar points have an extremely small likelihood of being picked. Then, t-SNE defines a similar distribution for the points in the low-dimensional embedding. Finally, t-SNE minimizes the Kullback–Leibler divergence between the two distributions with respect to the locations of the points in the embedding.
As mentioned previously, t-SNE takes a high dimensional dataset and reduces it to a low dimensional graph that retains a lot of the original information.
Suppose we had a dataset composed of 3 distinct classes.
We want to reduce the 2D plot into a 1D plot while maintaining clear boundaries between the clusters.
Recall that simply projecting the data on to an axis is a poor approach to dimensionality reduction because we lose a substantial amount of information.
Instead, we can use a dimensionality reduction technique (hint: t-SNE) to achieve what we want. The first step in the t-SNE algorithm involves measuring the distance from one point with respect to every other point. Instead of working with the distances directly, we map them to a probability distribution.
In the distribution, the points with the smallest distance with respect to the current point have a high likelihood, whereas the points far away from the current point have very low likelihoods.
Taking another look at the 2D plot, notice how the blue cluster is more spread out than the green one. If we don’t address this difference in scale, the likelihood of the green points will be greater than that of the blue ones. To account for this fact, we divide by the sum of the likelihoods.
Thus, although the absolute distance between the points are different, they’re considered just as similar.
Let’s try and tie these concepts back to the underlying theory. Mathematically, we write the equation for a normal distribution as follows.
If we drop everything before the exponent and use another point instead of the mean, all the while addressing the problem of scale discussed earlier, we get the equation from the paper.
Next, let’s address how we come up with the reduced feature space. To begin, we create a n_samples x n_components matrix (in this case: 9x1) and fill it with random values (i.e. positions).
If we take a similar approach to what’s above (measure the distances between points and map them to a probability distribution), we get the following equation.
Notice how like before, we took the equation for a normal distribution , dropped everything in front, used another point instead of the mean and accounted for scale by dividing by the sum of the likelihood for all other points (don’t ask me why we got rid of the standard deviation).
If we could some how make it so the probability distribution for the points in the reduced feature space approximate those in the original feature space, we’d get nicely defined clusters.
To accomplish this, we make use of something called the Kullback-Leiber divergence. The KL divergence is a measure of how different one probability distribution from a second.
The lower the value of the KL divergence, the closer two distributions are to one another. A KL divergence of 0 implies that the two distributions in question are identical.
This should hopefully bring about a flush of ideas. Recall how in the case of linear regression, we were able to determine the best fitting line by using gradient descent to minimize the cost function (i.e. mean square error). Well, in t-SNE, we use gradient descent to minimize the sum of the Kullback-Leiber divergences over data all the data points.
We take the partial derivative of our cost function with respect to every point in order to give us the direction of each update.
Often times we make use of some library without really understanding what goes on under the hood. In the proceeding section, I will attempt (all be it unsuccessfully) to implement the algorithm and associated mathematical equations as Python code. To help with the process, I took bits and pieces from the source code of the TSNE class in the scikit-learn library.
To begin, we’ll import the following libraries and set some properties which will come in to play when we go to plot our data.
import numpy as npfrom sklearn.datasets import load_digitsfrom scipy.spatial.distance import pdistfrom sklearn.manifold.t_sne import _joint_probabilitiesfrom scipy import linalgfrom sklearn.metrics import pairwise_distancesfrom scipy.spatial.distance import squareformfrom sklearn.manifold import TSNEfrom matplotlib import pyplot as pltimport seaborn as snssns.set(rc={'figure.figsize':(11.7,8.27)})palette = sns.color_palette("bright", 10)
For this example, we’ll be working with hand drawn digits. The scikit-learn library provides a method for importing them into our program.
X, y = load_digits(return_X_y=True)
We’re going to want to select either 2 or 3 for the number of components given that t-SNE is strictly used for visualization and we can only see things in up to 3 dimensions. On the other hand, perplexity is related to the number of nearest neighbors used in the algorithm. A different perplexity can cause drastic changes in the end results. In our case, we set it to the default value of the scitkit-learn implementation of t-SNE (30). According to the numpy documentation, the machine epsilon is the smallest representable positive number such that 1.0 + eps != 1.0. In other words, any number below the machine epsilon can’t be manipulated by the computer since it lacks the necessary bits. As we’ll see, the contributors use np.maximum to check whether the values in a matrix are smaller than the machine epsilon and replaces them in the event they are. I don’t understand the reasoning behind this, so if someone could leave a comment explaining why, it would be greatly appreciated.
MACHINE_EPSILON = np.finfo(np.double).epsn_components = 2perplexity = 30
Next, we define the fit function. We’ll make a call to the fit function when we go to transform our data.
def fit(X): n_samples = X.shape[0] # Compute euclidean distance distances = pairwise_distances(X, metric='euclidean', squared=True) # Compute joint probabilities p_ij from distances. P = _joint_probabilities(distances=distances, desired_perplexity=perplexity, verbose=False) # The embedding is initialized with iid samples from Gaussians with standard deviation 1e-4. X_embedded = 1e-4 * np.random.mtrand._rand.randn(n_samples, n_components).astype(np.float32) # degrees_of_freedom = n_components - 1 comes from # "Learning a Parametric Embedding by Preserving Local Structure" # Laurens van der Maaten, 2009. degrees_of_freedom = max(n_components - 1, 1) return _tsne(P, degrees_of_freedom, n_samples, X_embedded=X_embedded)
There’s quite a bit going on in this function so let’s break it up step by step.
1. We store the number of samples in a variable for future reference.
2. We compute the euclidean distance between each data point. this corresponds to ||xi — xj||^2 in the proceeding equation.
3. We pass the euclidean distance computed in the previous step as an argument to the _join_probabilities function which then calculates and returns a matrix of p_ji values (using the same equation).
4. We create the reduced feature space using randomly selecting values from Gaussian distributions with standard deviation 1e-4.
5. We define the degrees_of_freedom. There’s a comment in the source code which tells you to check out this paper explaining their reasoning. Basically, it’s been empirically shown that we get a better results (in bold) when we use the number of components minus one.
6. Finally we call the tsne function which is implemented as follows.
def _tsne(P, degrees_of_freedom, n_samples, X_embedded):params = X_embedded.ravel() obj_func = _kl_divergence params = _gradient_descent(obj_func, params, [P, degrees_of_freedom, n_samples, n_components]) X_embedded = params.reshape(n_samples, n_components)return X_embedded
There isn’t really much going in in this function. First, we use np.ravel to flatten our vector into a 1-D array.
>>> x = np.array([[1, 2, 3], [4, 5, 6]])>>> np.ravel(x)array([1, 2, 3, 4, 5, 6])
Then we use gradient descent to minimize the kl divergence. Once it’s done, we change the embedding back to a 2D array and return it.
Next, let’s take a look at the something with a little more meat to it. The following block of code is responsible for computing the error in the form of the kl divergence and the gradient.
def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components): X_embedded = params.reshape(n_samples, n_components) dist = pdist(X_embedded, "sqeuclidean") dist /= degrees_of_freedom dist += 1. dist **= (degrees_of_freedom + 1.0) / -2.0 Q = np.maximum(dist / (2.0 * np.sum(dist)), MACHINE_EPSILON) # Kullback-Leibler divergence of P and Q kl_divergence = 2.0 * np.dot(P, np.log(np.maximum(P, MACHINE_EPSILON) / Q)) # Gradient: dC/dY grad = np.ndarray((n_samples, n_components), dtype=params.dtype) PQd = squareform((P - Q) * dist) for i in range(n_samples): grad[i] = np.dot(np.ravel(PQd[i], order='K'), X_embedded[i] - X_embedded) grad = grad.ravel() c = 2.0 * (degrees_of_freedom + 1.0) / degrees_of_freedom grad *= creturn kl_divergence, grad
Again, let’s walk through the code step by step.
1. The first part calculates the probability distribution over the points in the low-dimensional map.
The authors actually use a variation of the equation above which includes the degrees of freedom.
where α represents the number of degrees of freedom of the Student-t distribution
2. We calculate the KL divergence (hint: whenever you see np.dot think sum).
3. We calculate the gradient (partial derivatives). dist is actually yi — yj in:
Again, they use a variation of the equation above with the degrees of freedom.
where α represents the number of degrees of freedom of the Student-t distribution
The gradient descent function updates the values in the embedding by minimizing the KL divergence. We stop prematurely when either the gradient norm is below the threshold or when we reach the maximum number of iterations without making any progress.
def _gradient_descent(obj_func, p0, args, it=0, n_iter=1000, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7): p = p0.copy().ravel() update = np.zeros_like(p) gains = np.ones_like(p) error = np.finfo(np.float).max best_error = np.finfo(np.float).max best_iter = i = it for i in range(it, n_iter):error, grad = obj_func(p, *args)grad_norm = linalg.norm(grad)inc = update * grad < 0.0 dec = np.invert(inc) gains[inc] += 0.2 gains[dec] *= 0.8 np.clip(gains, min_gain, np.inf, out=gains) grad *= gains update = momentum * update - learning_rate * grad p += updateprint("[t-SNE] Iteration %d: error = %.7f," " gradient norm = %.7f" % (i + 1, error, grad_norm)) if error < best_error: best_error = error best_iter = i elif i - best_iter > n_iter_without_progress: break if grad_norm <= min_grad_norm: breakreturn p
If you’ve made it this far, give yourself a pat on the back. We’re ready to call the fit function with our data.
X_embedded = fit(X)
As we can see, the model did a fairly decent job of separating the different digits based off of the position of their pixels.
sns.scatterplot(X_embedded[:,0], X_embedded[:,1], hue=y, legend='full', palette=palette)
Let’s do the same thing using the scikit-learn implementation of t-SNE.
tsne = TSNE()X_embedded = tsne.fit_transform(X)
As we can see, the model managed to take a 64-dimensional dataset and project it on to a 2-dimensional space in such a way that similar samples cluster together.
sns.scatterplot(X_embedded[:,0], X_embedded[:,1], hue=y, legend='full', palette=palette)
|
[
{
"code": null,
"e": 658,
"s": 172,
"text": "t-Distributed Stochastic Neighbor Embedding (t-SNE) is a dimensionality reduction technique used to represent high-dimensional dataset in a low-dimensional space of two or three dimensions so that we can visualize it. In contrast to other dimensionality reduction algorithms like PCA which simply maximizes the variance, t-SNE creates a reduced feature space where similar samples are modeled by nearby points and dissimilar samples are modeled by distant points with high probability."
},
{
"code": null,
"e": 1143,
"s": 658,
"text": "At a high level, t-SNE constructs a probability distribution for the high-dimensional samples in such a way that similar samples have a high likelihood of being picked while dissimilar points have an extremely small likelihood of being picked. Then, t-SNE defines a similar distribution for the points in the low-dimensional embedding. Finally, t-SNE minimizes the Kullback–Leibler divergence between the two distributions with respect to the locations of the points in the embedding."
},
{
"code": null,
"e": 1297,
"s": 1143,
"text": "As mentioned previously, t-SNE takes a high dimensional dataset and reduces it to a low dimensional graph that retains a lot of the original information."
},
{
"code": null,
"e": 1354,
"s": 1297,
"text": "Suppose we had a dataset composed of 3 distinct classes."
},
{
"code": null,
"e": 1456,
"s": 1354,
"text": "We want to reduce the 2D plot into a 1D plot while maintaining clear boundaries between the clusters."
},
{
"code": null,
"e": 1609,
"s": 1456,
"text": "Recall that simply projecting the data on to an axis is a poor approach to dimensionality reduction because we lose a substantial amount of information."
},
{
"code": null,
"e": 1916,
"s": 1609,
"text": "Instead, we can use a dimensionality reduction technique (hint: t-SNE) to achieve what we want. The first step in the t-SNE algorithm involves measuring the distance from one point with respect to every other point. Instead of working with the distances directly, we map them to a probability distribution."
},
{
"code": null,
"e": 2111,
"s": 1916,
"text": "In the distribution, the points with the smallest distance with respect to the current point have a high likelihood, whereas the points far away from the current point have very low likelihoods."
},
{
"code": null,
"e": 2406,
"s": 2111,
"text": "Taking another look at the 2D plot, notice how the blue cluster is more spread out than the green one. If we don’t address this difference in scale, the likelihood of the green points will be greater than that of the blue ones. To account for this fact, we divide by the sum of the likelihoods."
},
{
"code": null,
"e": 2513,
"s": 2406,
"text": "Thus, although the absolute distance between the points are different, they’re considered just as similar."
},
{
"code": null,
"e": 2653,
"s": 2513,
"text": "Let’s try and tie these concepts back to the underlying theory. Mathematically, we write the equation for a normal distribution as follows."
},
{
"code": null,
"e": 2839,
"s": 2653,
"text": "If we drop everything before the exponent and use another point instead of the mean, all the while addressing the problem of scale discussed earlier, we get the equation from the paper."
},
{
"code": null,
"e": 3029,
"s": 2839,
"text": "Next, let’s address how we come up with the reduced feature space. To begin, we create a n_samples x n_components matrix (in this case: 9x1) and fill it with random values (i.e. positions)."
},
{
"code": null,
"e": 3189,
"s": 3029,
"text": "If we take a similar approach to what’s above (measure the distances between points and map them to a probability distribution), we get the following equation."
},
{
"code": null,
"e": 3473,
"s": 3189,
"text": "Notice how like before, we took the equation for a normal distribution , dropped everything in front, used another point instead of the mean and accounted for scale by dividing by the sum of the likelihood for all other points (don’t ask me why we got rid of the standard deviation)."
},
{
"code": null,
"e": 3661,
"s": 3473,
"text": "If we could some how make it so the probability distribution for the points in the reduced feature space approximate those in the original feature space, we’d get nicely defined clusters."
},
{
"code": null,
"e": 3837,
"s": 3661,
"text": "To accomplish this, we make use of something called the Kullback-Leiber divergence. The KL divergence is a measure of how different one probability distribution from a second."
},
{
"code": null,
"e": 4011,
"s": 3837,
"text": "The lower the value of the KL divergence, the closer two distributions are to one another. A KL divergence of 0 implies that the two distributions in question are identical."
},
{
"code": null,
"e": 4364,
"s": 4011,
"text": "This should hopefully bring about a flush of ideas. Recall how in the case of linear regression, we were able to determine the best fitting line by using gradient descent to minimize the cost function (i.e. mean square error). Well, in t-SNE, we use gradient descent to minimize the sum of the Kullback-Leiber divergences over data all the data points."
},
{
"code": null,
"e": 4494,
"s": 4364,
"text": "We take the partial derivative of our cost function with respect to every point in order to give us the direction of each update."
},
{
"code": null,
"e": 4859,
"s": 4494,
"text": "Often times we make use of some library without really understanding what goes on under the hood. In the proceeding section, I will attempt (all be it unsuccessfully) to implement the algorithm and associated mathematical equations as Python code. To help with the process, I took bits and pieces from the source code of the TSNE class in the scikit-learn library."
},
{
"code": null,
"e": 4986,
"s": 4859,
"text": "To begin, we’ll import the following libraries and set some properties which will come in to play when we go to plot our data."
},
{
"code": null,
"e": 5428,
"s": 4986,
"text": "import numpy as npfrom sklearn.datasets import load_digitsfrom scipy.spatial.distance import pdistfrom sklearn.manifold.t_sne import _joint_probabilitiesfrom scipy import linalgfrom sklearn.metrics import pairwise_distancesfrom scipy.spatial.distance import squareformfrom sklearn.manifold import TSNEfrom matplotlib import pyplot as pltimport seaborn as snssns.set(rc={'figure.figsize':(11.7,8.27)})palette = sns.color_palette(\"bright\", 10)"
},
{
"code": null,
"e": 5567,
"s": 5428,
"text": "For this example, we’ll be working with hand drawn digits. The scikit-learn library provides a method for importing them into our program."
},
{
"code": null,
"e": 5603,
"s": 5567,
"text": "X, y = load_digits(return_X_y=True)"
},
{
"code": null,
"e": 6593,
"s": 5603,
"text": "We’re going to want to select either 2 or 3 for the number of components given that t-SNE is strictly used for visualization and we can only see things in up to 3 dimensions. On the other hand, perplexity is related to the number of nearest neighbors used in the algorithm. A different perplexity can cause drastic changes in the end results. In our case, we set it to the default value of the scitkit-learn implementation of t-SNE (30). According to the numpy documentation, the machine epsilon is the smallest representable positive number such that 1.0 + eps != 1.0. In other words, any number below the machine epsilon can’t be manipulated by the computer since it lacks the necessary bits. As we’ll see, the contributors use np.maximum to check whether the values in a matrix are smaller than the machine epsilon and replaces them in the event they are. I don’t understand the reasoning behind this, so if someone could leave a comment explaining why, it would be greatly appreciated."
},
{
"code": null,
"e": 6666,
"s": 6593,
"text": "MACHINE_EPSILON = np.finfo(np.double).epsn_components = 2perplexity = 30"
},
{
"code": null,
"e": 6772,
"s": 6666,
"text": "Next, we define the fit function. We’ll make a call to the fit function when we go to transform our data."
},
{
"code": null,
"e": 7554,
"s": 6772,
"text": "def fit(X): n_samples = X.shape[0] # Compute euclidean distance distances = pairwise_distances(X, metric='euclidean', squared=True) # Compute joint probabilities p_ij from distances. P = _joint_probabilities(distances=distances, desired_perplexity=perplexity, verbose=False) # The embedding is initialized with iid samples from Gaussians with standard deviation 1e-4. X_embedded = 1e-4 * np.random.mtrand._rand.randn(n_samples, n_components).astype(np.float32) # degrees_of_freedom = n_components - 1 comes from # \"Learning a Parametric Embedding by Preserving Local Structure\" # Laurens van der Maaten, 2009. degrees_of_freedom = max(n_components - 1, 1) return _tsne(P, degrees_of_freedom, n_samples, X_embedded=X_embedded)"
},
{
"code": null,
"e": 7635,
"s": 7554,
"text": "There’s quite a bit going on in this function so let’s break it up step by step."
},
{
"code": null,
"e": 7705,
"s": 7635,
"text": "1. We store the number of samples in a variable for future reference."
},
{
"code": null,
"e": 7829,
"s": 7705,
"text": "2. We compute the euclidean distance between each data point. this corresponds to ||xi — xj||^2 in the proceeding equation."
},
{
"code": null,
"e": 8029,
"s": 7829,
"text": "3. We pass the euclidean distance computed in the previous step as an argument to the _join_probabilities function which then calculates and returns a matrix of p_ji values (using the same equation)."
},
{
"code": null,
"e": 8158,
"s": 8029,
"text": "4. We create the reduced feature space using randomly selecting values from Gaussian distributions with standard deviation 1e-4."
},
{
"code": null,
"e": 8426,
"s": 8158,
"text": "5. We define the degrees_of_freedom. There’s a comment in the source code which tells you to check out this paper explaining their reasoning. Basically, it’s been empirically shown that we get a better results (in bold) when we use the number of components minus one."
},
{
"code": null,
"e": 8496,
"s": 8426,
"text": "6. Finally we call the tsne function which is implemented as follows."
},
{
"code": null,
"e": 8796,
"s": 8496,
"text": "def _tsne(P, degrees_of_freedom, n_samples, X_embedded):params = X_embedded.ravel() obj_func = _kl_divergence params = _gradient_descent(obj_func, params, [P, degrees_of_freedom, n_samples, n_components]) X_embedded = params.reshape(n_samples, n_components)return X_embedded"
},
{
"code": null,
"e": 8910,
"s": 8796,
"text": "There isn’t really much going in in this function. First, we use np.ravel to flatten our vector into a 1-D array."
},
{
"code": null,
"e": 8991,
"s": 8910,
"text": ">>> x = np.array([[1, 2, 3], [4, 5, 6]])>>> np.ravel(x)array([1, 2, 3, 4, 5, 6])"
},
{
"code": null,
"e": 9125,
"s": 8991,
"text": "Then we use gradient descent to minimize the kl divergence. Once it’s done, we change the embedding back to a 2D array and return it."
},
{
"code": null,
"e": 9315,
"s": 9125,
"text": "Next, let’s take a look at the something with a little more meat to it. The following block of code is responsible for computing the error in the form of the kl divergence and the gradient."
},
{
"code": null,
"e": 10162,
"s": 9315,
"text": "def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components): X_embedded = params.reshape(n_samples, n_components) dist = pdist(X_embedded, \"sqeuclidean\") dist /= degrees_of_freedom dist += 1. dist **= (degrees_of_freedom + 1.0) / -2.0 Q = np.maximum(dist / (2.0 * np.sum(dist)), MACHINE_EPSILON) # Kullback-Leibler divergence of P and Q kl_divergence = 2.0 * np.dot(P, np.log(np.maximum(P, MACHINE_EPSILON) / Q)) # Gradient: dC/dY grad = np.ndarray((n_samples, n_components), dtype=params.dtype) PQd = squareform((P - Q) * dist) for i in range(n_samples): grad[i] = np.dot(np.ravel(PQd[i], order='K'), X_embedded[i] - X_embedded) grad = grad.ravel() c = 2.0 * (degrees_of_freedom + 1.0) / degrees_of_freedom grad *= creturn kl_divergence, grad"
},
{
"code": null,
"e": 10211,
"s": 10162,
"text": "Again, let’s walk through the code step by step."
},
{
"code": null,
"e": 10313,
"s": 10211,
"text": "1. The first part calculates the probability distribution over the points in the low-dimensional map."
},
{
"code": null,
"e": 10411,
"s": 10313,
"text": "The authors actually use a variation of the equation above which includes the degrees of freedom."
},
{
"code": null,
"e": 10493,
"s": 10411,
"text": "where α represents the number of degrees of freedom of the Student-t distribution"
},
{
"code": null,
"e": 10570,
"s": 10493,
"text": "2. We calculate the KL divergence (hint: whenever you see np.dot think sum)."
},
{
"code": null,
"e": 10651,
"s": 10570,
"text": "3. We calculate the gradient (partial derivatives). dist is actually yi — yj in:"
},
{
"code": null,
"e": 10730,
"s": 10651,
"text": "Again, they use a variation of the equation above with the degrees of freedom."
},
{
"code": null,
"e": 10812,
"s": 10730,
"text": "where α represents the number of degrees of freedom of the Student-t distribution"
},
{
"code": null,
"e": 11063,
"s": 10812,
"text": "The gradient descent function updates the values in the embedding by minimizing the KL divergence. We stop prematurely when either the gradient norm is below the threshold or when we reach the maximum number of iterations without making any progress."
},
{
"code": null,
"e": 12210,
"s": 11063,
"text": "def _gradient_descent(obj_func, p0, args, it=0, n_iter=1000, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7): p = p0.copy().ravel() update = np.zeros_like(p) gains = np.ones_like(p) error = np.finfo(np.float).max best_error = np.finfo(np.float).max best_iter = i = it for i in range(it, n_iter):error, grad = obj_func(p, *args)grad_norm = linalg.norm(grad)inc = update * grad < 0.0 dec = np.invert(inc) gains[inc] += 0.2 gains[dec] *= 0.8 np.clip(gains, min_gain, np.inf, out=gains) grad *= gains update = momentum * update - learning_rate * grad p += updateprint(\"[t-SNE] Iteration %d: error = %.7f,\" \" gradient norm = %.7f\" % (i + 1, error, grad_norm)) if error < best_error: best_error = error best_iter = i elif i - best_iter > n_iter_without_progress: break if grad_norm <= min_grad_norm: breakreturn p"
},
{
"code": null,
"e": 12323,
"s": 12210,
"text": "If you’ve made it this far, give yourself a pat on the back. We’re ready to call the fit function with our data."
},
{
"code": null,
"e": 12343,
"s": 12323,
"text": "X_embedded = fit(X)"
},
{
"code": null,
"e": 12470,
"s": 12343,
"text": "As we can see, the model did a fairly decent job of separating the different digits based off of the position of their pixels."
},
{
"code": null,
"e": 12559,
"s": 12470,
"text": "sns.scatterplot(X_embedded[:,0], X_embedded[:,1], hue=y, legend='full', palette=palette)"
},
{
"code": null,
"e": 12631,
"s": 12559,
"text": "Let’s do the same thing using the scikit-learn implementation of t-SNE."
},
{
"code": null,
"e": 12679,
"s": 12631,
"text": "tsne = TSNE()X_embedded = tsne.fit_transform(X)"
},
{
"code": null,
"e": 12841,
"s": 12679,
"text": "As we can see, the model managed to take a 64-dimensional dataset and project it on to a 2-dimensional space in such a way that similar samples cluster together."
}
] |
CICS - Interface Block
|
Any application program would require an interface to interact with the CICS. EIB (Execute Interface Block) acts as an interface to allow application programs communicate with the CICS. EIB contains the information required during the execution of a program.
While coding a CICS program, we cannot use the commands which return the control directly to the MVS. If we code these COBOL verbs, it will not give any compilation error, but we may get unpredictable results. Following are the COBOL verbs which should not be used in a CICS program −
File I/O statements like Open, Read, Write, Rewrite, Close, Delete, and Start. All file I/O in CICS is handled by the file control module and they have their own set of statements like READ, WRITE, REWRITE, and DELETE which we will be discussing in the upcoming modules.
File I/O statements like Open, Read, Write, Rewrite, Close, Delete, and Start. All file I/O in CICS is handled by the file control module and they have their own set of statements like READ, WRITE, REWRITE, and DELETE which we will be discussing in the upcoming modules.
File Section and Environment Division is not required.
File Section and Environment Division is not required.
COBOL statements that invoke operating system functions like Accept, Date/Time cannot be used.
COBOL statements that invoke operating system functions like Accept, Date/Time cannot be used.
Do not use DISPLAY, MERGE, STOP RUN, and GO BACK.
Do not use DISPLAY, MERGE, STOP RUN, and GO BACK.
Execute Interface Block (EIB) is a control block which is loaded automatically by the CICS for every program.
The EIB is unique to a task and it exists for the duration of the task. It contains a set of system related information corresponding to the task.
The EIB is unique to a task and it exists for the duration of the task. It contains a set of system related information corresponding to the task.
It contains information about transaction identifier, time, date, etc., which is used by the CICS during the execution of an application program.
It contains information about transaction identifier, time, date, etc., which is used by the CICS during the execution of an application program.
Every program that executes as a part of the task has access to the same EIB.
Every program that executes as a part of the task has access to the same EIB.
The data in EIB at runtime can be viewed by executing the program in CEDF mode.
The data in EIB at runtime can be viewed by executing the program in CEDF mode.
The following table provides a list of fields which are present in EIB −
CICS Programs are classified in the following three categories which we will discuss one by one −
Non-Conversational Programs
Conversational Programs
Pseudo-Conversational Programs - We will discuss in the next module
While executing non-Conversational programs, no human intervention is required. All the necessary inputs are provided when the program is started.
They are similar to batch programs that run in the batch mode. So in CICS, they are rarely developed.
They are similar to batch programs that run in the batch mode. So in CICS, they are rarely developed.
We can say they are used just for displaying a sequence of screens at regular intervals of time.
We can say they are used just for displaying a sequence of screens at regular intervals of time.
The following example shows a non-conversational program which will simply display "HELLO WORLD" on the CICS terminal as output −
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-MESSAGE PIC X(30).
PROCEDURE DIVISION.
********************************************************
* SENDING DATA TO SCREEN *
********************************************************
MOVE 'HELLO WORLD' TO WS-MESSAGE
EXEC CICS SEND TEXT
FROM (WS-MESSAGE)
END-EXEC
********************************************************
* TASK TERMINATES WITHOUT ANY INTERACTION FROM THE USER*
********************************************************
EXEC CICS RETURN
END-EXEC.
Sending a message to the terminal and receiving a response from the user is called a Conversational. An online application achieves a conversation between the user and the application program by a pair of SEND and RECEIVE command. The key points of a Conversational program are as follows −
The system sends a message to the screen and waits for the user’s response.
The system sends a message to the screen and waits for the user’s response.
The time taken by user to respond is known as Think Time. This time is considerably high, which is a major drawback of conversion programs.
The time taken by user to respond is known as Think Time. This time is considerably high, which is a major drawback of conversion programs.
The user provides the necessary input and presses an AID key.
The user provides the necessary input and presses an AID key.
The application processes the user’s input and sends the output.
The application processes the user’s input and sends the output.
The program is loaded into the main storage at the beginning and is retained till the task ends.
The program is loaded into the main storage at the beginning and is retained till the task ends.
The following example shows a conversion program which takes input from the user and then simply displays the same input on the CICS terminal as output −
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-MESSAGE PIC X(30) VALUE SPACES.
PROCEDURE DIVISION.
MOVE 'ENTER MESSAGE' TO WS-MESSAGE
********************************************************
* SENDING DATA FROM PROGRAM TO SCREEN *
********************************************************
EXEC CICS SEND TEXT
FROM (WS-MESSAGE)
END-EXEC
********************************************************
* GETTING INPUT FROM USER *
********************************************************
EXEC CICS RECEIVE
INTO(WS-MESSAGE)
END-EXEC
EXEC CICS SEND TEXT
FROM (WS-MESSAGE)
END-EXEC
********************************************************
* COMMAND TO TERMINATE THE TRANSACTION *
********************************************************
EXEC CICS RETURN
END-EXEC.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2185,
"s": 1926,
"text": "Any application program would require an interface to interact with the CICS. EIB (Execute Interface Block) acts as an interface to allow application programs communicate with the CICS. EIB contains the information required during the execution of a program."
},
{
"code": null,
"e": 2470,
"s": 2185,
"text": "While coding a CICS program, we cannot use the commands which return the control directly to the MVS. If we code these COBOL verbs, it will not give any compilation error, but we may get unpredictable results. Following are the COBOL verbs which should not be used in a CICS program −"
},
{
"code": null,
"e": 2741,
"s": 2470,
"text": "File I/O statements like Open, Read, Write, Rewrite, Close, Delete, and Start. All file I/O in CICS is handled by the file control module and they have their own set of statements like READ, WRITE, REWRITE, and DELETE which we will be discussing in the upcoming modules."
},
{
"code": null,
"e": 3012,
"s": 2741,
"text": "File I/O statements like Open, Read, Write, Rewrite, Close, Delete, and Start. All file I/O in CICS is handled by the file control module and they have their own set of statements like READ, WRITE, REWRITE, and DELETE which we will be discussing in the upcoming modules."
},
{
"code": null,
"e": 3067,
"s": 3012,
"text": "File Section and Environment Division is not required."
},
{
"code": null,
"e": 3122,
"s": 3067,
"text": "File Section and Environment Division is not required."
},
{
"code": null,
"e": 3217,
"s": 3122,
"text": "COBOL statements that invoke operating system functions like Accept, Date/Time cannot be used."
},
{
"code": null,
"e": 3312,
"s": 3217,
"text": "COBOL statements that invoke operating system functions like Accept, Date/Time cannot be used."
},
{
"code": null,
"e": 3362,
"s": 3312,
"text": "Do not use DISPLAY, MERGE, STOP RUN, and GO BACK."
},
{
"code": null,
"e": 3412,
"s": 3362,
"text": "Do not use DISPLAY, MERGE, STOP RUN, and GO BACK."
},
{
"code": null,
"e": 3522,
"s": 3412,
"text": "Execute Interface Block (EIB) is a control block which is loaded automatically by the CICS for every program."
},
{
"code": null,
"e": 3669,
"s": 3522,
"text": "The EIB is unique to a task and it exists for the duration of the task. It contains a set of system related information corresponding to the task."
},
{
"code": null,
"e": 3816,
"s": 3669,
"text": "The EIB is unique to a task and it exists for the duration of the task. It contains a set of system related information corresponding to the task."
},
{
"code": null,
"e": 3962,
"s": 3816,
"text": "It contains information about transaction identifier, time, date, etc., which is used by the CICS during the execution of an application program."
},
{
"code": null,
"e": 4108,
"s": 3962,
"text": "It contains information about transaction identifier, time, date, etc., which is used by the CICS during the execution of an application program."
},
{
"code": null,
"e": 4186,
"s": 4108,
"text": "Every program that executes as a part of the task has access to the same EIB."
},
{
"code": null,
"e": 4264,
"s": 4186,
"text": "Every program that executes as a part of the task has access to the same EIB."
},
{
"code": null,
"e": 4344,
"s": 4264,
"text": "The data in EIB at runtime can be viewed by executing the program in CEDF mode."
},
{
"code": null,
"e": 4424,
"s": 4344,
"text": "The data in EIB at runtime can be viewed by executing the program in CEDF mode."
},
{
"code": null,
"e": 4497,
"s": 4424,
"text": "The following table provides a list of fields which are present in EIB −"
},
{
"code": null,
"e": 4595,
"s": 4497,
"text": "CICS Programs are classified in the following three categories which we will discuss one by one −"
},
{
"code": null,
"e": 4623,
"s": 4595,
"text": "Non-Conversational Programs"
},
{
"code": null,
"e": 4647,
"s": 4623,
"text": "Conversational Programs"
},
{
"code": null,
"e": 4715,
"s": 4647,
"text": "Pseudo-Conversational Programs - We will discuss in the next module"
},
{
"code": null,
"e": 4862,
"s": 4715,
"text": "While executing non-Conversational programs, no human intervention is required. All the necessary inputs are provided when the program is started."
},
{
"code": null,
"e": 4964,
"s": 4862,
"text": "They are similar to batch programs that run in the batch mode. So in CICS, they are rarely developed."
},
{
"code": null,
"e": 5066,
"s": 4964,
"text": "They are similar to batch programs that run in the batch mode. So in CICS, they are rarely developed."
},
{
"code": null,
"e": 5163,
"s": 5066,
"text": "We can say they are used just for displaying a sequence of screens at regular intervals of time."
},
{
"code": null,
"e": 5260,
"s": 5163,
"text": "We can say they are used just for displaying a sequence of screens at regular intervals of time."
},
{
"code": null,
"e": 5390,
"s": 5260,
"text": "The following example shows a non-conversational program which will simply display \"HELLO WORLD\" on the CICS terminal as output −"
},
{
"code": null,
"e": 6345,
"s": 5390,
"text": "IDENTIFICATION DIVISION. \nPROGRAM-ID. HELLO. \nDATA DIVISION. \nWORKING-STORAGE SECTION. \n01 WS-MESSAGE PIC X(30). \nPROCEDURE DIVISION. \n********************************************************\n* SENDING DATA TO SCREEN * \n********************************************************\n MOVE 'HELLO WORLD' TO WS-MESSAGE \n EXEC CICS SEND TEXT \n FROM (WS-MESSAGE) \n END-EXEC \n********************************************************\n* TASK TERMINATES WITHOUT ANY INTERACTION FROM THE USER* \n********************************************************\n EXEC CICS RETURN \nEND-EXEC.\n"
},
{
"code": null,
"e": 6636,
"s": 6345,
"text": "Sending a message to the terminal and receiving a response from the user is called a Conversational. An online application achieves a conversation between the user and the application program by a pair of SEND and RECEIVE command. The key points of a Conversational program are as follows −"
},
{
"code": null,
"e": 6712,
"s": 6636,
"text": "The system sends a message to the screen and waits for the user’s response."
},
{
"code": null,
"e": 6788,
"s": 6712,
"text": "The system sends a message to the screen and waits for the user’s response."
},
{
"code": null,
"e": 6928,
"s": 6788,
"text": "The time taken by user to respond is known as Think Time. This time is considerably high, which is a major drawback of conversion programs."
},
{
"code": null,
"e": 7068,
"s": 6928,
"text": "The time taken by user to respond is known as Think Time. This time is considerably high, which is a major drawback of conversion programs."
},
{
"code": null,
"e": 7130,
"s": 7068,
"text": "The user provides the necessary input and presses an AID key."
},
{
"code": null,
"e": 7192,
"s": 7130,
"text": "The user provides the necessary input and presses an AID key."
},
{
"code": null,
"e": 7257,
"s": 7192,
"text": "The application processes the user’s input and sends the output."
},
{
"code": null,
"e": 7322,
"s": 7257,
"text": "The application processes the user’s input and sends the output."
},
{
"code": null,
"e": 7419,
"s": 7322,
"text": "The program is loaded into the main storage at the beginning and is retained till the task ends."
},
{
"code": null,
"e": 7516,
"s": 7419,
"text": "The program is loaded into the main storage at the beginning and is retained till the task ends."
},
{
"code": null,
"e": 7670,
"s": 7516,
"text": "The following example shows a conversion program which takes input from the user and then simply displays the same input on the CICS terminal as output −"
},
{
"code": null,
"e": 9125,
"s": 7670,
"text": "IDENTIFICATION DIVISION. \nPROGRAM-ID. HELLO. \nDATA DIVISION. \nWORKING-STORAGE SECTION. \n01 WS-MESSAGE PIC X(30) VALUE SPACES. \nPROCEDURE DIVISION. \n MOVE 'ENTER MESSAGE' TO WS-MESSAGE \n********************************************************\n* SENDING DATA FROM PROGRAM TO SCREEN * \n********************************************************\n EXEC CICS SEND TEXT \n FROM (WS-MESSAGE) \n END-EXEC \n********************************************************\n* GETTING INPUT FROM USER * \n********************************************************\n EXEC CICS RECEIVE \n INTO(WS-MESSAGE) \n END-EXEC \n EXEC CICS SEND TEXT \n FROM (WS-MESSAGE) \n END-EXEC \n********************************************************\n* COMMAND TO TERMINATE THE TRANSACTION * \n********************************************************\n EXEC CICS RETURN \nEND-EXEC. \n"
},
{
"code": null,
"e": 9132,
"s": 9125,
"text": " Print"
},
{
"code": null,
"e": 9143,
"s": 9132,
"text": " Add Notes"
}
] |
Your Ultimate Data Manipulation & Cleaning Cheat Sheet | by Andre Ye | Towards Data Science
|
The majority of a data science project comprises of data cleaning and manipulation. Most of these data cleaning tasks can be broken down into six areas:
Imputing Missing Values. Standard statistical constant imputing, KNN imputing.
Outlier/Anomaly Detection. Isolation Forest, One Class SVM, Local Outlier Factor outlier detection algorithms.
X-Variable Cleaning Methods. Applying custom functions, removing duplicates, replacing values.
Y-Variable Cleaning Methods. Label encoding, dictionary mapping, one-hot encoding.
Joining DataFrames. Concatenating, merging, and joining.
Parsing Dates. Auto-format-detecting string-to-datetime converting, datetime objects to numbers.
Images created by author unless explicitly stated otherwise.
Missing values often plague data, and given that there are not too many of them, they can be imputed (filled in).
Simple Imputing Methods are statistical constant measures like the mean or the median which fills in NaN (missing values) with the statistical measure of each column. The parameter strategy can be substituted with ‘mean’, ‘median’, ‘most_frequent’ (mode), or ‘constant’ (a manual value with parameter fill_value).
from sklearn.impute import SimpleImputerimputer = SimpleImputer(strategy='mean')data = imputer.fit_transform(data)
KNN Imputing is the most popular and complex method for imputing missing values, in which the KNN algorithm finds other data points similar to one with a missing value within multidimensional space.
from sklearn.impute import KNNImputerimputer = KNNImputer()data = imputer.fit_transform(data)
Before using KNN and other distance-based algorithms, the data needs to be scaled or normalized to eliminate differences in scale (for example, one column representing number of children and another representing annual salary — these values cannot be taken at face value). Using KNN imputing follows the following process:
Scale/normalize the data.KNN-impute to fill in missing values.Inverse scale/normalize the data.
Scale/normalize the data.
KNN-impute to fill in missing values.
Inverse scale/normalize the data.
Isolation Forest is an algorithm to return the anomaly score of a sample. The algorithm isolates observations by creating paths by randomly selecting a feature, randomly selecting a split value, the path length representing its normality. Shorter paths represent anomalies — when a forest of random trees collectively produce shorter path lengths for particular samples, they are highly likely to be anomalies.
from sklearn.ensemble import IsolationForestidentifier = IsolationForest().fit(X)identifier.predict(X)
The output of predictions of the anomaly detector is an array of scores from -1 to 1, positive scores representing higher chances of being anomalies.
One Class SVM is another unsupervised method for detecting outliers, suited for high-dimensional distributions where an anomaly detection method like Isolation Forest would develop too much variance.
from sklearn.svm import OneClassSVMidentifier = OneClassSVM().fit(X)identifier.predict(X)
Local Outlier Factor is the third of three commonly used outlier identifiers. The anomaly score of each sample — the Local Outlier Factor — measures the local deviation of density given a sample with respect to its neighbors. Based on the K-Nearest Neighbors, samples that have substantially lower density than their neighbors are considered outliers.
Because this algorithm is distance based, the data needs to be scaled or normalized before it is used. This algorithm can be seen as a non-linear high-variance alternative to Isolation Forest.
from sklearn.neighbors import LocalOutlierFactormodel = LocalOutlierFactor().fit(X)model.predict(X)
For all three anomaly algorithms, it is the data scientist’s choice to eliminate all anomalies. Be sure that anomalies are not just data clusters themselves — make sure that the number of anomalies are not too excessive in number. A PCA visualization can confirm this.
Applying a function to a column is often needed to clean it. In the case where cleaning cannot be done by a built-in function, you may need to write your own function or pass in an external built-in function. For example, say that all values of column b below 2 are invalid. A function to be applied can then act as a filter, returning NaN values for column elements that fail to pass the filter:
def filter_b(value): if value < 2: return np.nan else: return value
A new cleaned column, ‘cleaned_b’, can then be created by applying the filter using pandas’ .apply() function:
data['cleaned_b'] = data['b'].apply(filter_b)
Another common use case is converting data types. For instance, converting a string column into a numerical column could be done with data[‘target’].apply(float) using the Python built-in function float.
Removing duplicates is a common task in data cleaning. This can be done with data.drop_duplicates(), which removes rows that have the exact same values. Be cautious when using this — when the number of features is small, duplicate rows may not be errors in data collection. However, with large datasets and mostly continuous variables, the chance that duplicates are not errors is small.
Sampling data points is common when a dataset is too large (or for another purpose) and data points need to be randomly sampled. This can be done with data.sample(number_of_samples).
Renaming columns is done with .rename, where the parameter passed is a dictionary where the key is the original column name and the value is the renamed value. For example, data.rename({‘a’:1, ‘b’:3}) would rename the column ‘a’ to 1 and the column ‘b’ to 3.
Replacing values within the data can be done with data.replace(), which takes in two parameters to_replace and value, which represent values within the DataFrame that will be replaced by other values. This is helpful for the next section, imputing missing values, which can replace certain variables with np.nan so imputing algorithms can recognize them.
More handy pandas functions specifically for data manipulation can be found here:
towardsdatascience.com
Label Encoding is required for categorical y-variables. For example, if data has two classes ‘cat’ and ‘dog’, they need to be mapped to 0 and 1, as machine learning algorithms operate purely on mathematical bases.
One simple way to do this is with the .map() function, which takes a dictionary in which keys are the original class names and the values are the elements they are to be replaced.
data['target'] = data['target'].map({'cat':0, 'dog':1})
However, in the case where there are too many classes to manually map with a dictionary, sklearn has an automated method:
from sklearn.preprocessing import LabelEncoderencoder = LabelEncoder().fit(data['target'])data['target'] = encoder.transform(data['target'])
The benefit of using this method of label encoding is that data can be inverse transformed — meaning from numerical values to their original classes — using encoder.inverse_transform(array).
One-Hot Encoding is advantageous over label encoding in certain scenarios with several classes when label encoding places quantitative measures on the data. Label encoding between classes ‘dog’, ‘cat’, and ‘fish’ to 0, 1, and 2 assumes that somehow ‘fish’ is larger than ‘dog’ or ‘dog’ is smaller than ‘cat’.
In one-hot encoding, each y-value is a vector the length of the number of distinct classes, with a ‘1’ indicating a unique index within the vector and the remaining values marked with ‘0’s. For example, ‘dog’ may be assigned the vector [1, 0, 0], ‘cat’ to [0, 1, 0], and ‘fish’ to [0, 0, 1].
pandas has a built-in function, get_dummies, which automatically takes in a series or another array form and outputs the one-hot encoded DataFrame. For example, below the command pd.get_dummies(data[‘target’]).
Concatenation is the top-down joining of DataFrames. For example, pd.concat([df1, df2]) will yield a master DataFrame where df2 is stacked below df1.
Merging is the left-to-right process that merges two DataFrames horizontally, instead of vertically with concat(). For example, pd.merge(left_df, right_df, on='ID') will merge the left DataFrame and the right DataFrame based on the ‘ID’ column.
Joining allows for more specialized merging. By default, merging is an inner join, which only fits together rows where the keyword is in both data frames. Other types of joining include left outer joins, where all keywords in the left DataFrame are included, with rows in the right DataFrame included only if their keywords exist in the left one.
The join type of choice can be outlined in a parameter how=”outer” or “right” within merge:
pd.merge(left = left_df, right = right_df, how = 'outer', on = 'id')
Dates are perhaps the most difficult data objects to deal with, but are also essential to the data. Time is the most important variable in real-life contexts, and it’s important not to let difficulty working with it intrude accommodating it in your data.
Converting strings to dates is common — almost never do datasets come with datetime objects that can be handily accessed. The best library for converting strings to dates is dateutil, which can automatically infer the location of days, months, and years, which need to be specified with other libraries.
from dateutil import parser
dateutil can accommodate a wide variety of dates, where each of the commands yields the same result (datetime.datetime(2040, 7, 3, 0, 0)):
parser.parse(‘7/3/40’)
parser.parse(‘7–3–2040’)
parser.parse(‘7.3.40’)
parser.parse(‘July 3rd, 2040’)
parser.parse(‘July 3 2040’)
parser.parse(‘2040 July 3’)
parser.parse(‘3 July 2040’)
Using .apply(parser.parse) to a column can convert strings of almost any form into a datetime object, where attributes of it can be extracted.
Converting dates to numbers is important because while time is essential for a model’s consideration, it cannot handle datetime objects. Instead, time can be represented as an integer, where each date represents the number of days passed since the earliest date in the data. In the example below, 8 March 2016 is the earliest date in the dataset (this needs to be found and replaced).
import datetimedef convert_date_to_num(date): return (date - datetime.datetime(5,8,16)).daysdata['number date'] = data['date'].apply(convert_date_to_num)
The function is applied to the date column (assuming the date column’s elements are datetime objects) using .apply().
Be sure to bookmark this page for easy reference if you found it helpful. If you enjoyed, you may also enjoy other data science cheat sheets:
|
[
{
"code": null,
"e": 325,
"s": 172,
"text": "The majority of a data science project comprises of data cleaning and manipulation. Most of these data cleaning tasks can be broken down into six areas:"
},
{
"code": null,
"e": 404,
"s": 325,
"text": "Imputing Missing Values. Standard statistical constant imputing, KNN imputing."
},
{
"code": null,
"e": 515,
"s": 404,
"text": "Outlier/Anomaly Detection. Isolation Forest, One Class SVM, Local Outlier Factor outlier detection algorithms."
},
{
"code": null,
"e": 610,
"s": 515,
"text": "X-Variable Cleaning Methods. Applying custom functions, removing duplicates, replacing values."
},
{
"code": null,
"e": 693,
"s": 610,
"text": "Y-Variable Cleaning Methods. Label encoding, dictionary mapping, one-hot encoding."
},
{
"code": null,
"e": 750,
"s": 693,
"text": "Joining DataFrames. Concatenating, merging, and joining."
},
{
"code": null,
"e": 847,
"s": 750,
"text": "Parsing Dates. Auto-format-detecting string-to-datetime converting, datetime objects to numbers."
},
{
"code": null,
"e": 908,
"s": 847,
"text": "Images created by author unless explicitly stated otherwise."
},
{
"code": null,
"e": 1022,
"s": 908,
"text": "Missing values often plague data, and given that there are not too many of them, they can be imputed (filled in)."
},
{
"code": null,
"e": 1336,
"s": 1022,
"text": "Simple Imputing Methods are statistical constant measures like the mean or the median which fills in NaN (missing values) with the statistical measure of each column. The parameter strategy can be substituted with ‘mean’, ‘median’, ‘most_frequent’ (mode), or ‘constant’ (a manual value with parameter fill_value)."
},
{
"code": null,
"e": 1451,
"s": 1336,
"text": "from sklearn.impute import SimpleImputerimputer = SimpleImputer(strategy='mean')data = imputer.fit_transform(data)"
},
{
"code": null,
"e": 1650,
"s": 1451,
"text": "KNN Imputing is the most popular and complex method for imputing missing values, in which the KNN algorithm finds other data points similar to one with a missing value within multidimensional space."
},
{
"code": null,
"e": 1744,
"s": 1650,
"text": "from sklearn.impute import KNNImputerimputer = KNNImputer()data = imputer.fit_transform(data)"
},
{
"code": null,
"e": 2067,
"s": 1744,
"text": "Before using KNN and other distance-based algorithms, the data needs to be scaled or normalized to eliminate differences in scale (for example, one column representing number of children and another representing annual salary — these values cannot be taken at face value). Using KNN imputing follows the following process:"
},
{
"code": null,
"e": 2163,
"s": 2067,
"text": "Scale/normalize the data.KNN-impute to fill in missing values.Inverse scale/normalize the data."
},
{
"code": null,
"e": 2189,
"s": 2163,
"text": "Scale/normalize the data."
},
{
"code": null,
"e": 2227,
"s": 2189,
"text": "KNN-impute to fill in missing values."
},
{
"code": null,
"e": 2261,
"s": 2227,
"text": "Inverse scale/normalize the data."
},
{
"code": null,
"e": 2672,
"s": 2261,
"text": "Isolation Forest is an algorithm to return the anomaly score of a sample. The algorithm isolates observations by creating paths by randomly selecting a feature, randomly selecting a split value, the path length representing its normality. Shorter paths represent anomalies — when a forest of random trees collectively produce shorter path lengths for particular samples, they are highly likely to be anomalies."
},
{
"code": null,
"e": 2775,
"s": 2672,
"text": "from sklearn.ensemble import IsolationForestidentifier = IsolationForest().fit(X)identifier.predict(X)"
},
{
"code": null,
"e": 2925,
"s": 2775,
"text": "The output of predictions of the anomaly detector is an array of scores from -1 to 1, positive scores representing higher chances of being anomalies."
},
{
"code": null,
"e": 3125,
"s": 2925,
"text": "One Class SVM is another unsupervised method for detecting outliers, suited for high-dimensional distributions where an anomaly detection method like Isolation Forest would develop too much variance."
},
{
"code": null,
"e": 3215,
"s": 3125,
"text": "from sklearn.svm import OneClassSVMidentifier = OneClassSVM().fit(X)identifier.predict(X)"
},
{
"code": null,
"e": 3567,
"s": 3215,
"text": "Local Outlier Factor is the third of three commonly used outlier identifiers. The anomaly score of each sample — the Local Outlier Factor — measures the local deviation of density given a sample with respect to its neighbors. Based on the K-Nearest Neighbors, samples that have substantially lower density than their neighbors are considered outliers."
},
{
"code": null,
"e": 3760,
"s": 3567,
"text": "Because this algorithm is distance based, the data needs to be scaled or normalized before it is used. This algorithm can be seen as a non-linear high-variance alternative to Isolation Forest."
},
{
"code": null,
"e": 3860,
"s": 3760,
"text": "from sklearn.neighbors import LocalOutlierFactormodel = LocalOutlierFactor().fit(X)model.predict(X)"
},
{
"code": null,
"e": 4129,
"s": 3860,
"text": "For all three anomaly algorithms, it is the data scientist’s choice to eliminate all anomalies. Be sure that anomalies are not just data clusters themselves — make sure that the number of anomalies are not too excessive in number. A PCA visualization can confirm this."
},
{
"code": null,
"e": 4526,
"s": 4129,
"text": "Applying a function to a column is often needed to clean it. In the case where cleaning cannot be done by a built-in function, you may need to write your own function or pass in an external built-in function. For example, say that all values of column b below 2 are invalid. A function to be applied can then act as a filter, returning NaN values for column elements that fail to pass the filter:"
},
{
"code": null,
"e": 4620,
"s": 4526,
"text": "def filter_b(value): if value < 2: return np.nan else: return value"
},
{
"code": null,
"e": 4731,
"s": 4620,
"text": "A new cleaned column, ‘cleaned_b’, can then be created by applying the filter using pandas’ .apply() function:"
},
{
"code": null,
"e": 4777,
"s": 4731,
"text": "data['cleaned_b'] = data['b'].apply(filter_b)"
},
{
"code": null,
"e": 4981,
"s": 4777,
"text": "Another common use case is converting data types. For instance, converting a string column into a numerical column could be done with data[‘target’].apply(float) using the Python built-in function float."
},
{
"code": null,
"e": 5369,
"s": 4981,
"text": "Removing duplicates is a common task in data cleaning. This can be done with data.drop_duplicates(), which removes rows that have the exact same values. Be cautious when using this — when the number of features is small, duplicate rows may not be errors in data collection. However, with large datasets and mostly continuous variables, the chance that duplicates are not errors is small."
},
{
"code": null,
"e": 5552,
"s": 5369,
"text": "Sampling data points is common when a dataset is too large (or for another purpose) and data points need to be randomly sampled. This can be done with data.sample(number_of_samples)."
},
{
"code": null,
"e": 5811,
"s": 5552,
"text": "Renaming columns is done with .rename, where the parameter passed is a dictionary where the key is the original column name and the value is the renamed value. For example, data.rename({‘a’:1, ‘b’:3}) would rename the column ‘a’ to 1 and the column ‘b’ to 3."
},
{
"code": null,
"e": 6166,
"s": 5811,
"text": "Replacing values within the data can be done with data.replace(), which takes in two parameters to_replace and value, which represent values within the DataFrame that will be replaced by other values. This is helpful for the next section, imputing missing values, which can replace certain variables with np.nan so imputing algorithms can recognize them."
},
{
"code": null,
"e": 6248,
"s": 6166,
"text": "More handy pandas functions specifically for data manipulation can be found here:"
},
{
"code": null,
"e": 6271,
"s": 6248,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6485,
"s": 6271,
"text": "Label Encoding is required for categorical y-variables. For example, if data has two classes ‘cat’ and ‘dog’, they need to be mapped to 0 and 1, as machine learning algorithms operate purely on mathematical bases."
},
{
"code": null,
"e": 6665,
"s": 6485,
"text": "One simple way to do this is with the .map() function, which takes a dictionary in which keys are the original class names and the values are the elements they are to be replaced."
},
{
"code": null,
"e": 6721,
"s": 6665,
"text": "data['target'] = data['target'].map({'cat':0, 'dog':1})"
},
{
"code": null,
"e": 6843,
"s": 6721,
"text": "However, in the case where there are too many classes to manually map with a dictionary, sklearn has an automated method:"
},
{
"code": null,
"e": 6984,
"s": 6843,
"text": "from sklearn.preprocessing import LabelEncoderencoder = LabelEncoder().fit(data['target'])data['target'] = encoder.transform(data['target'])"
},
{
"code": null,
"e": 7175,
"s": 6984,
"text": "The benefit of using this method of label encoding is that data can be inverse transformed — meaning from numerical values to their original classes — using encoder.inverse_transform(array)."
},
{
"code": null,
"e": 7484,
"s": 7175,
"text": "One-Hot Encoding is advantageous over label encoding in certain scenarios with several classes when label encoding places quantitative measures on the data. Label encoding between classes ‘dog’, ‘cat’, and ‘fish’ to 0, 1, and 2 assumes that somehow ‘fish’ is larger than ‘dog’ or ‘dog’ is smaller than ‘cat’."
},
{
"code": null,
"e": 7776,
"s": 7484,
"text": "In one-hot encoding, each y-value is a vector the length of the number of distinct classes, with a ‘1’ indicating a unique index within the vector and the remaining values marked with ‘0’s. For example, ‘dog’ may be assigned the vector [1, 0, 0], ‘cat’ to [0, 1, 0], and ‘fish’ to [0, 0, 1]."
},
{
"code": null,
"e": 7987,
"s": 7776,
"text": "pandas has a built-in function, get_dummies, which automatically takes in a series or another array form and outputs the one-hot encoded DataFrame. For example, below the command pd.get_dummies(data[‘target’])."
},
{
"code": null,
"e": 8137,
"s": 7987,
"text": "Concatenation is the top-down joining of DataFrames. For example, pd.concat([df1, df2]) will yield a master DataFrame where df2 is stacked below df1."
},
{
"code": null,
"e": 8382,
"s": 8137,
"text": "Merging is the left-to-right process that merges two DataFrames horizontally, instead of vertically with concat(). For example, pd.merge(left_df, right_df, on='ID') will merge the left DataFrame and the right DataFrame based on the ‘ID’ column."
},
{
"code": null,
"e": 8729,
"s": 8382,
"text": "Joining allows for more specialized merging. By default, merging is an inner join, which only fits together rows where the keyword is in both data frames. Other types of joining include left outer joins, where all keywords in the left DataFrame are included, with rows in the right DataFrame included only if their keywords exist in the left one."
},
{
"code": null,
"e": 8821,
"s": 8729,
"text": "The join type of choice can be outlined in a parameter how=”outer” or “right” within merge:"
},
{
"code": null,
"e": 8890,
"s": 8821,
"text": "pd.merge(left = left_df, right = right_df, how = 'outer', on = 'id')"
},
{
"code": null,
"e": 9145,
"s": 8890,
"text": "Dates are perhaps the most difficult data objects to deal with, but are also essential to the data. Time is the most important variable in real-life contexts, and it’s important not to let difficulty working with it intrude accommodating it in your data."
},
{
"code": null,
"e": 9449,
"s": 9145,
"text": "Converting strings to dates is common — almost never do datasets come with datetime objects that can be handily accessed. The best library for converting strings to dates is dateutil, which can automatically infer the location of days, months, and years, which need to be specified with other libraries."
},
{
"code": null,
"e": 9477,
"s": 9449,
"text": "from dateutil import parser"
},
{
"code": null,
"e": 9616,
"s": 9477,
"text": "dateutil can accommodate a wide variety of dates, where each of the commands yields the same result (datetime.datetime(2040, 7, 3, 0, 0)):"
},
{
"code": null,
"e": 9639,
"s": 9616,
"text": "parser.parse(‘7/3/40’)"
},
{
"code": null,
"e": 9664,
"s": 9639,
"text": "parser.parse(‘7–3–2040’)"
},
{
"code": null,
"e": 9687,
"s": 9664,
"text": "parser.parse(‘7.3.40’)"
},
{
"code": null,
"e": 9718,
"s": 9687,
"text": "parser.parse(‘July 3rd, 2040’)"
},
{
"code": null,
"e": 9746,
"s": 9718,
"text": "parser.parse(‘July 3 2040’)"
},
{
"code": null,
"e": 9774,
"s": 9746,
"text": "parser.parse(‘2040 July 3’)"
},
{
"code": null,
"e": 9802,
"s": 9774,
"text": "parser.parse(‘3 July 2040’)"
},
{
"code": null,
"e": 9945,
"s": 9802,
"text": "Using .apply(parser.parse) to a column can convert strings of almost any form into a datetime object, where attributes of it can be extracted."
},
{
"code": null,
"e": 10330,
"s": 9945,
"text": "Converting dates to numbers is important because while time is essential for a model’s consideration, it cannot handle datetime objects. Instead, time can be represented as an integer, where each date represents the number of days passed since the earliest date in the data. In the example below, 8 March 2016 is the earliest date in the dataset (this needs to be found and replaced)."
},
{
"code": null,
"e": 10488,
"s": 10330,
"text": "import datetimedef convert_date_to_num(date): return (date - datetime.datetime(5,8,16)).daysdata['number date'] = data['date'].apply(convert_date_to_num)"
},
{
"code": null,
"e": 10606,
"s": 10488,
"text": "The function is applied to the date column (assuming the date column’s elements are datetime objects) using .apply()."
}
] |
PyTorch JIT and TorchScript. A path to production for PyTorch models | by Abhishek Sharma | Towards Data Science
|
We all love the dynamicity and ease of use of PyTorch. But when it comes to deployment these qualities are not as desirable as performance and portability.
In the past deployment required moving to a different framework. The move from research to production required 2 separate teams with different skill sets to make this possible. This process changed with the introduction of TorchScript.
With TorchScript, PyTorch aims to create a unified framework from research to production. TorchScript will take your PyTorch modules as input and convert them into a production-friendly format.
It will run your models faster and independent of the Python runtime.
PyTorch supports 2 separate modes to handle research and production environment.
First is the Eager mode. It is built for faster prototyping, training, and experimentation.
Second is the Script mode. It is focused on the production use case. It has 2 components PyTorch JIT and TorchScript.
In one line, it gets rids of Python’s GIL and dependence on Python runtime. A nuanced explanation is as follows
PortabilityPortability allows models to be deployed in multithreaded inference servers, mobiles, and cars which is difficult with Python. In order to achieve this PyTorch models needs to be decoupled from any specific runtime.PerformancePyTorch JIT is an optimizing JIT compiler for PyTorch. It uses runtime information to optimize TorchScript modules. It can automate optimizations like layer fusion, quantization, sparsification.
PortabilityPortability allows models to be deployed in multithreaded inference servers, mobiles, and cars which is difficult with Python. In order to achieve this PyTorch models needs to be decoupled from any specific runtime.
PerformancePyTorch JIT is an optimizing JIT compiler for PyTorch. It uses runtime information to optimize TorchScript modules. It can automate optimizations like layer fusion, quantization, sparsification.
Script mode creates an intermediate representation (IR) of your PyTorch Eager module(throughtorch.jit.trace/torch.jit.script). The IR is internally optimized and utilizes PyTorch JIT compilation at runtime. PyTorch JIT compiler uses runtime information to optimize the IR. This IR is decoupled from the Python runtime.
The script mode works by utilizing PyTorch JIT and TorchScript.
PyTorch JIT is an optimized compiler for PyTorch programs.
It is a lightweight threadsafe interpreterSupports easy to write custom transformationsIt’s not just for inference as it has auto diff support
It is a lightweight threadsafe interpreter
Supports easy to write custom transformations
It’s not just for inference as it has auto diff support
TorchScript is a static high-performance subset of Python language, specialized for ML applications. It supports
Complex control flowsCommon data structuresUser-defined classes
Complex control flows
Common data structures
User-defined classes
We have introduced PyTorch JIT, TorchScript, and Script mode. We have discussed, What are they, and why we need them? In the following segments, we will understand how to use them?
Script mode is invoked by either torch.jit.trace or torch.jit.script.
torch.jit.trace take a data instance and your trained eager module as input. The tracer runs the supplied module and records the tensor operations performed. This recording is turned into a TorchScript module.
Skip to Example 1 to see it in action
It can reuse existing eager model code and can handle almost any program with exclusive torch tensors/operations.
Its main drawback is that it omits all control flow, data structures, and python constructs. It can also create unfaithful representations without any warnings. Always checks its IR to see if it is correctly parsing the structure of your PyTorch model.
torch.jit.script allows you to write your code directly into TorchScript. It's more verbose but it more versatile and with a little tweaking can support the majority of the PyTorch models.
In contrast to trace mode you only need to pass an instance of your model/module to torch.jit.script. A data sample is not necessary.
Skip to Example 2 on its practical utility
It preserves control flows and other python constructs and looks more like Python. It has first-class support for lists/dictionaries.
It omits constant values and requires typecasting. If no type is provided it defaults to tensor
That’s too much theory for one sitting, Let’s move over to the code and see the trace/script in action.
BERT (Bidirectional Encoder Representations from Transformers) was developed by researchers at Google AI. In the following example, we utilize BERT from the transformer’s library provided by HuggingFace.
This example is divided into 3 parts
Part 1Initializes BERT model/tokenizers and creates a sample data for inference
Part 2:Prepares PyTorch models for inference on CPU/GPU.
Model/Data should be on the same device for training/inference to happen. cuda() transfers the model/data from CPU to GPU.
Step 3:Prepares TorchScript modules for inference on CPU/GPU
On CPU the runtimes are similar but on GPU TorchScript clearly outperforms PyTorch.
TorchScript creates an IR of the PyTorch models which can be compiled optimally at runtime by PyTorch JIT. This IR can be viewed using traced_model.code.
ResNet, short for Residual Networks is a classic neural network used as a backbone for many computer vision tasks. This model was the winner of the ImageNet challenge in 2015.
The following example has 2 segments
Example 1.1 / 1.2:PyTorch ResNet initialization and inference on CPU/GPU
Example 2.1/2.2:torch.jit.script initialization and inference on CPU/GPU
TorchScript significantly outperforms the PyTorch implementation on GPU.
TorchScript saves/loads modules into an archive format. This archive is a standalone representation of the model and can be loaded into an entirely separate process.
Saving a module torch.jit.save(traced_model,’traced_bert.pt’)
Loading a module loaded = torch.jit.load('traced_bert.pt')
Example 1: Use traced_model.code to view PyTorch IRSkipping this as it’s very verbose
Example 2: Use script_cell_gpu.code to view PyTorch IR
def forward(self, input: Tensor) -> Tensor: _0 = self.fc _1 = self.avgpool _2 = self.layer4 _3 = self.layer3 _4 = self.layer2 _5 = self.layer1 _6 = self.maxpool _7 = self.relu _8 = (self.bn1).forward((self.conv1).forward(input, ), ) _9 = (_5).forward((_6).forward((_7).forward(_8, ), ), ) _10 = (_2).forward((_3).forward((_4).forward(_9, ), ), ) input0 = torch.flatten((_1).forward(_10, ), 1, -1) return (_0).forward(input0, )
torch.jit.trace and torch.jit.script can be combined to cover for their deficiencies. Look at this official example. They do this by inlining the code.
Apart from improved inference time, there are other benefits of using TorchScript
TorchScript decouples your model from any runtime environment. It gets rid of Python’s GIL which is a major bottleneck for multithreaded inference.
TorchScript focuses on whole program optimizations.
TorchScript automatically optimizes common patterns in neural networks to improve latency and throughput.
TorchScript modules are exportable to a wide variety of environments, from C++ servers to mobile.
This blog has introduced script mode. Functionally the script mode provides tools to take your research models to production while still being in the PyTorch ecosystem.
To reiterate this is how a typical path for model development and deployment would look like.
Step 0: Develop your models, preferably in the PyTorch Eager mode
Step 1: Create TorchScript module by using eithertorch.jit.trace or/andtorch.jit.script on your PyTorch model
Step 2: Transfer these modules to the production environment using torch.jit.save/torch.jit.load. In this format, they can be run anywhere from servers to edge devices
Step 3: Use the PyTorch JIT compiler to optimize these programs at inference time and enjoy faster inference with minimal effort.
Torchscript + PyTorch JITResearch to ProductionPyTorch DocumentationUsing TorchScript for Transformer models
Torchscript + PyTorch JIT
Research to Production
PyTorch Documentation
Using TorchScript for Transformer models
|
[
{
"code": null,
"e": 328,
"s": 172,
"text": "We all love the dynamicity and ease of use of PyTorch. But when it comes to deployment these qualities are not as desirable as performance and portability."
},
{
"code": null,
"e": 564,
"s": 328,
"text": "In the past deployment required moving to a different framework. The move from research to production required 2 separate teams with different skill sets to make this possible. This process changed with the introduction of TorchScript."
},
{
"code": null,
"e": 758,
"s": 564,
"text": "With TorchScript, PyTorch aims to create a unified framework from research to production. TorchScript will take your PyTorch modules as input and convert them into a production-friendly format."
},
{
"code": null,
"e": 828,
"s": 758,
"text": "It will run your models faster and independent of the Python runtime."
},
{
"code": null,
"e": 909,
"s": 828,
"text": "PyTorch supports 2 separate modes to handle research and production environment."
},
{
"code": null,
"e": 1001,
"s": 909,
"text": "First is the Eager mode. It is built for faster prototyping, training, and experimentation."
},
{
"code": null,
"e": 1119,
"s": 1001,
"text": "Second is the Script mode. It is focused on the production use case. It has 2 components PyTorch JIT and TorchScript."
},
{
"code": null,
"e": 1231,
"s": 1119,
"text": "In one line, it gets rids of Python’s GIL and dependence on Python runtime. A nuanced explanation is as follows"
},
{
"code": null,
"e": 1663,
"s": 1231,
"text": "PortabilityPortability allows models to be deployed in multithreaded inference servers, mobiles, and cars which is difficult with Python. In order to achieve this PyTorch models needs to be decoupled from any specific runtime.PerformancePyTorch JIT is an optimizing JIT compiler for PyTorch. It uses runtime information to optimize TorchScript modules. It can automate optimizations like layer fusion, quantization, sparsification."
},
{
"code": null,
"e": 1890,
"s": 1663,
"text": "PortabilityPortability allows models to be deployed in multithreaded inference servers, mobiles, and cars which is difficult with Python. In order to achieve this PyTorch models needs to be decoupled from any specific runtime."
},
{
"code": null,
"e": 2096,
"s": 1890,
"text": "PerformancePyTorch JIT is an optimizing JIT compiler for PyTorch. It uses runtime information to optimize TorchScript modules. It can automate optimizations like layer fusion, quantization, sparsification."
},
{
"code": null,
"e": 2415,
"s": 2096,
"text": "Script mode creates an intermediate representation (IR) of your PyTorch Eager module(throughtorch.jit.trace/torch.jit.script). The IR is internally optimized and utilizes PyTorch JIT compilation at runtime. PyTorch JIT compiler uses runtime information to optimize the IR. This IR is decoupled from the Python runtime."
},
{
"code": null,
"e": 2479,
"s": 2415,
"text": "The script mode works by utilizing PyTorch JIT and TorchScript."
},
{
"code": null,
"e": 2538,
"s": 2479,
"text": "PyTorch JIT is an optimized compiler for PyTorch programs."
},
{
"code": null,
"e": 2681,
"s": 2538,
"text": "It is a lightweight threadsafe interpreterSupports easy to write custom transformationsIt’s not just for inference as it has auto diff support"
},
{
"code": null,
"e": 2724,
"s": 2681,
"text": "It is a lightweight threadsafe interpreter"
},
{
"code": null,
"e": 2770,
"s": 2724,
"text": "Supports easy to write custom transformations"
},
{
"code": null,
"e": 2826,
"s": 2770,
"text": "It’s not just for inference as it has auto diff support"
},
{
"code": null,
"e": 2939,
"s": 2826,
"text": "TorchScript is a static high-performance subset of Python language, specialized for ML applications. It supports"
},
{
"code": null,
"e": 3003,
"s": 2939,
"text": "Complex control flowsCommon data structuresUser-defined classes"
},
{
"code": null,
"e": 3025,
"s": 3003,
"text": "Complex control flows"
},
{
"code": null,
"e": 3048,
"s": 3025,
"text": "Common data structures"
},
{
"code": null,
"e": 3069,
"s": 3048,
"text": "User-defined classes"
},
{
"code": null,
"e": 3250,
"s": 3069,
"text": "We have introduced PyTorch JIT, TorchScript, and Script mode. We have discussed, What are they, and why we need them? In the following segments, we will understand how to use them?"
},
{
"code": null,
"e": 3320,
"s": 3250,
"text": "Script mode is invoked by either torch.jit.trace or torch.jit.script."
},
{
"code": null,
"e": 3530,
"s": 3320,
"text": "torch.jit.trace take a data instance and your trained eager module as input. The tracer runs the supplied module and records the tensor operations performed. This recording is turned into a TorchScript module."
},
{
"code": null,
"e": 3568,
"s": 3530,
"text": "Skip to Example 1 to see it in action"
},
{
"code": null,
"e": 3682,
"s": 3568,
"text": "It can reuse existing eager model code and can handle almost any program with exclusive torch tensors/operations."
},
{
"code": null,
"e": 3935,
"s": 3682,
"text": "Its main drawback is that it omits all control flow, data structures, and python constructs. It can also create unfaithful representations without any warnings. Always checks its IR to see if it is correctly parsing the structure of your PyTorch model."
},
{
"code": null,
"e": 4124,
"s": 3935,
"text": "torch.jit.script allows you to write your code directly into TorchScript. It's more verbose but it more versatile and with a little tweaking can support the majority of the PyTorch models."
},
{
"code": null,
"e": 4258,
"s": 4124,
"text": "In contrast to trace mode you only need to pass an instance of your model/module to torch.jit.script. A data sample is not necessary."
},
{
"code": null,
"e": 4301,
"s": 4258,
"text": "Skip to Example 2 on its practical utility"
},
{
"code": null,
"e": 4435,
"s": 4301,
"text": "It preserves control flows and other python constructs and looks more like Python. It has first-class support for lists/dictionaries."
},
{
"code": null,
"e": 4531,
"s": 4435,
"text": "It omits constant values and requires typecasting. If no type is provided it defaults to tensor"
},
{
"code": null,
"e": 4635,
"s": 4531,
"text": "That’s too much theory for one sitting, Let’s move over to the code and see the trace/script in action."
},
{
"code": null,
"e": 4839,
"s": 4635,
"text": "BERT (Bidirectional Encoder Representations from Transformers) was developed by researchers at Google AI. In the following example, we utilize BERT from the transformer’s library provided by HuggingFace."
},
{
"code": null,
"e": 4876,
"s": 4839,
"text": "This example is divided into 3 parts"
},
{
"code": null,
"e": 4956,
"s": 4876,
"text": "Part 1Initializes BERT model/tokenizers and creates a sample data for inference"
},
{
"code": null,
"e": 5013,
"s": 4956,
"text": "Part 2:Prepares PyTorch models for inference on CPU/GPU."
},
{
"code": null,
"e": 5136,
"s": 5013,
"text": "Model/Data should be on the same device for training/inference to happen. cuda() transfers the model/data from CPU to GPU."
},
{
"code": null,
"e": 5197,
"s": 5136,
"text": "Step 3:Prepares TorchScript modules for inference on CPU/GPU"
},
{
"code": null,
"e": 5281,
"s": 5197,
"text": "On CPU the runtimes are similar but on GPU TorchScript clearly outperforms PyTorch."
},
{
"code": null,
"e": 5435,
"s": 5281,
"text": "TorchScript creates an IR of the PyTorch models which can be compiled optimally at runtime by PyTorch JIT. This IR can be viewed using traced_model.code."
},
{
"code": null,
"e": 5611,
"s": 5435,
"text": "ResNet, short for Residual Networks is a classic neural network used as a backbone for many computer vision tasks. This model was the winner of the ImageNet challenge in 2015."
},
{
"code": null,
"e": 5648,
"s": 5611,
"text": "The following example has 2 segments"
},
{
"code": null,
"e": 5721,
"s": 5648,
"text": "Example 1.1 / 1.2:PyTorch ResNet initialization and inference on CPU/GPU"
},
{
"code": null,
"e": 5794,
"s": 5721,
"text": "Example 2.1/2.2:torch.jit.script initialization and inference on CPU/GPU"
},
{
"code": null,
"e": 5867,
"s": 5794,
"text": "TorchScript significantly outperforms the PyTorch implementation on GPU."
},
{
"code": null,
"e": 6033,
"s": 5867,
"text": "TorchScript saves/loads modules into an archive format. This archive is a standalone representation of the model and can be loaded into an entirely separate process."
},
{
"code": null,
"e": 6095,
"s": 6033,
"text": "Saving a module torch.jit.save(traced_model,’traced_bert.pt’)"
},
{
"code": null,
"e": 6154,
"s": 6095,
"text": "Loading a module loaded = torch.jit.load('traced_bert.pt')"
},
{
"code": null,
"e": 6240,
"s": 6154,
"text": "Example 1: Use traced_model.code to view PyTorch IRSkipping this as it’s very verbose"
},
{
"code": null,
"e": 6295,
"s": 6240,
"text": "Example 2: Use script_cell_gpu.code to view PyTorch IR"
},
{
"code": null,
"e": 6738,
"s": 6295,
"text": "def forward(self, input: Tensor) -> Tensor: _0 = self.fc _1 = self.avgpool _2 = self.layer4 _3 = self.layer3 _4 = self.layer2 _5 = self.layer1 _6 = self.maxpool _7 = self.relu _8 = (self.bn1).forward((self.conv1).forward(input, ), ) _9 = (_5).forward((_6).forward((_7).forward(_8, ), ), ) _10 = (_2).forward((_3).forward((_4).forward(_9, ), ), ) input0 = torch.flatten((_1).forward(_10, ), 1, -1) return (_0).forward(input0, )"
},
{
"code": null,
"e": 6890,
"s": 6738,
"text": "torch.jit.trace and torch.jit.script can be combined to cover for their deficiencies. Look at this official example. They do this by inlining the code."
},
{
"code": null,
"e": 6972,
"s": 6890,
"text": "Apart from improved inference time, there are other benefits of using TorchScript"
},
{
"code": null,
"e": 7120,
"s": 6972,
"text": "TorchScript decouples your model from any runtime environment. It gets rid of Python’s GIL which is a major bottleneck for multithreaded inference."
},
{
"code": null,
"e": 7172,
"s": 7120,
"text": "TorchScript focuses on whole program optimizations."
},
{
"code": null,
"e": 7278,
"s": 7172,
"text": "TorchScript automatically optimizes common patterns in neural networks to improve latency and throughput."
},
{
"code": null,
"e": 7376,
"s": 7278,
"text": "TorchScript modules are exportable to a wide variety of environments, from C++ servers to mobile."
},
{
"code": null,
"e": 7545,
"s": 7376,
"text": "This blog has introduced script mode. Functionally the script mode provides tools to take your research models to production while still being in the PyTorch ecosystem."
},
{
"code": null,
"e": 7639,
"s": 7545,
"text": "To reiterate this is how a typical path for model development and deployment would look like."
},
{
"code": null,
"e": 7705,
"s": 7639,
"text": "Step 0: Develop your models, preferably in the PyTorch Eager mode"
},
{
"code": null,
"e": 7815,
"s": 7705,
"text": "Step 1: Create TorchScript module by using eithertorch.jit.trace or/andtorch.jit.script on your PyTorch model"
},
{
"code": null,
"e": 7983,
"s": 7815,
"text": "Step 2: Transfer these modules to the production environment using torch.jit.save/torch.jit.load. In this format, they can be run anywhere from servers to edge devices"
},
{
"code": null,
"e": 8113,
"s": 7983,
"text": "Step 3: Use the PyTorch JIT compiler to optimize these programs at inference time and enjoy faster inference with minimal effort."
},
{
"code": null,
"e": 8222,
"s": 8113,
"text": "Torchscript + PyTorch JITResearch to ProductionPyTorch DocumentationUsing TorchScript for Transformer models"
},
{
"code": null,
"e": 8248,
"s": 8222,
"text": "Torchscript + PyTorch JIT"
},
{
"code": null,
"e": 8271,
"s": 8248,
"text": "Research to Production"
},
{
"code": null,
"e": 8293,
"s": 8271,
"text": "PyTorch Documentation"
}
] |
Command Line Arguments in ElectronJS - GeeksforGeeks
|
09 Nov, 2021
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
The Command-line arguments are parameters that are passed to the program when it is invoked. Different programming languages and frameworks use different methods to parse these arguments. Command-line arguments are important because they can be used to control the behavior of the application. These arguments are passed to the main function of any application. Electron also supports Command-line arguments. We can pass Command-line arguments to Electron from outside the application on invoking it or we can simply hard code these values using the Instance methods of the built-in CommandLine Property of the app Module of Electron. This tutorial will demonstrate how to add Command-line arguments in Electron.
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
Project Structure:
Command-line arguments in Electron The app Module and the CommandLine Property are part of the Main Process. We need to append the Command-Line arguments to the applications Main Process before the ready Event of the app Module is emitted. In Electron, the CommandLine property is used to read and manipulate the command-line arguments that Chromium reads and uses. They can be used to control and override the default behaviour of Chromium. For a detailed list of supported Command-Line flags and switches that can be used in Electron. We will also be using some of these flags and switches for demonstration. The CommandLine property only supports Instance methods. It does not have any Instance events and properties associated with it.
Example: Follow the give Steps to pass Command-line arguments in Electron.
Step 1: Follow the Steps given in Drag and Drop Files in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. package.json:
{
"name": "electron-command",
"version": "1.0.0",
"description": "Command Line Switches in Electron",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
Create the assets folder according to the project structure. We will use this folder to store logs. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result.
Step 2: Now we will pass Command-line arguments to the Electron application using any of the two approaches. Approach 1: Passing Command-line arguments while launching the application. We will be using the –log-net-log=path Command-line switch. This switch enables network logging events to be recorded and writes the generated logs to the path file. We have already made the necessary changes to the package.json file to launch the application using the start script. We will modify this script to pass this Command-line switch.package.json: Change the following snippet in that file.Output: Upon launching the application, network logging will be enabled by Chromium and a log.txt file will be automatically generated within the assets folder with initial network log entries.Approach 2: Passing Command-line arguments using the CommandLine property of the app module. main.js Add the following Snippet at the start of the file just after importing the app module and before the ready event is emitted.
Approach 1: Passing Command-line arguments while launching the application. We will be using the –log-net-log=path Command-line switch. This switch enables network logging events to be recorded and writes the generated logs to the path file. We have already made the necessary changes to the package.json file to launch the application using the start script. We will modify this script to pass this Command-line switch.package.json: Change the following snippet in that file.
Output: Upon launching the application, network logging will be enabled by Chromium and a log.txt file will be automatically generated within the assets folder with initial network log entries.
Approach 2: Passing Command-line arguments using the CommandLine property of the app module. main.js Add the following Snippet at the start of the file just after importing the app module and before the ready event is emitted.
javascript
const { app, BrowserWindow } = require("electron");app.commandLine.appendSwitch("log-net-log", "assets/log.txt");console.log(app.commandLine.hasSwitch("log-net-log"));console.log(app.commandLine.getSwitchValue("log-net-log"));
A detailed Explanation of all the Instance methods of the CommandLine property used in the code are explained below. For more detailed Information on the CommandLine property.
commandLine.appendSwitch(switch, value) This method appends a Switch with optional value parameter to Chromium’s Command line when invoking the application. This method does not have any return type. It takes in the following parameters. In our code, we have used this Instance method to append the –log-net-log=path Command-line switch.switch: String A Command-line switch without the leading — for appending to Chromium’s Command line when invoking the application. This value cannot be empty.value: String (Optional) A String value for the given Switch if it supports any. In case the Switch takes in a Boolean value, we will wrap the Boolean within String for it to be passed via this method. In our code, we have specified the path to the assets folder. By default, it will take the CWD (Current working Directory).
switch: String A Command-line switch without the leading — for appending to Chromium’s Command line when invoking the application. This value cannot be empty.
value: String (Optional) A String value for the given Switch if it supports any. In case the Switch takes in a Boolean value, we will wrap the Boolean within String for it to be passed via this method. In our code, we have specified the path to the assets folder. By default, it will take the CWD (Current working Directory).
commandLine.hasSwitch(switch) This method is used to check whether a Command-line switch is present when invoking the application from outside such as, the start script in the package.json file or has been appended using the commandLine.appendSwitch() method. It returns a Boolean value stating whether the Command-line switch is present. It takes in the following parameters.switch: String A Command-line switch without the leading — for checking the Chromium’s Command line. This value cannot be empty.
switch: String A Command-line switch without the leading — for checking the Chromium’s Command line. This value cannot be empty.
commandLine.getSwitchValue(switch) This method is used to return the Command-line Switch value, if any. It returns a String value. In case the Command-line switch is not present or there is no value, it will return an empty String. It takes in the following parameters.switch: String A Command-line switch without the leading — for checking the Chromium’s Command line. This value cannot be empty.
switch: String A Command-line switch without the leading — for checking the Chromium’s Command line. This value cannot be empty.
commandLine.appendArgument(argument) This method is used to append an Argument to the Chromium’s Command line when invoking the application. The argument will be quoted appropriately by the application. This method does not have any return type. This method is similar to the commandLine.appendSwitch() method but Command-line Switches will always precede the Arguments regardless of the appending order. In case we want to append a Command-line switch as an entire Argument, for example, ‘–log-net-log=assets/log.txt’ then we should not use this method. We should use the commandLine.appendSwitch() method instead. It takes in the following parameters.argument: String An String argument to be appended to Chromium’s Command-line. This value cannot be empty.
argument: String An String argument to be appended to Chromium’s Command-line. This value cannot be empty.
surinderdawra388
kashishsoda
ElectronJS
CSS
HTML
JavaScript
Node.js
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 24285,
"s": 24257,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 24585,
"s": 24285,
"text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime."
},
{
"code": null,
"e": 25298,
"s": 24585,
"text": "The Command-line arguments are parameters that are passed to the program when it is invoked. Different programming languages and frameworks use different methods to parse these arguments. Command-line arguments are important because they can be used to control the behavior of the application. These arguments are passed to the main function of any application. Electron also supports Command-line arguments. We can pass Command-line arguments to Electron from outside the application on invoking it or we can simply hard code these values using the Instance methods of the built-in CommandLine Property of the app Module of Electron. This tutorial will demonstrate how to add Command-line arguments in Electron."
},
{
"code": null,
"e": 25468,
"s": 25298,
"text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system."
},
{
"code": null,
"e": 25489,
"s": 25468,
"text": "Project Structure: "
},
{
"code": null,
"e": 26229,
"s": 25489,
"text": "Command-line arguments in Electron The app Module and the CommandLine Property are part of the Main Process. We need to append the Command-Line arguments to the applications Main Process before the ready Event of the app Module is emitted. In Electron, the CommandLine property is used to read and manipulate the command-line arguments that Chromium reads and uses. They can be used to control and override the default behaviour of Chromium. For a detailed list of supported Command-Line flags and switches that can be used in Electron. We will also be using some of these flags and switches for demonstration. The CommandLine property only supports Instance methods. It does not have any Instance events and properties associated with it."
},
{
"code": null,
"e": 26304,
"s": 26229,
"text": "Example: Follow the give Steps to pass Command-line arguments in Electron."
},
{
"code": null,
"e": 26701,
"s": 26304,
"text": "Step 1: Follow the Steps given in Drag and Drop Files in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. package.json:"
},
{
"code": null,
"e": 27013,
"s": 26701,
"text": "{\n \"name\": \"electron-command\",\n \"version\": \"1.0.0\",\n \"description\": \"Command Line Switches in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}"
},
{
"code": null,
"e": 27246,
"s": 27013,
"text": "Create the assets folder according to the project structure. We will use this folder to store logs. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result."
},
{
"code": null,
"e": 28251,
"s": 27246,
"text": "Step 2: Now we will pass Command-line arguments to the Electron application using any of the two approaches. Approach 1: Passing Command-line arguments while launching the application. We will be using the –log-net-log=path Command-line switch. This switch enables network logging events to be recorded and writes the generated logs to the path file. We have already made the necessary changes to the package.json file to launch the application using the start script. We will modify this script to pass this Command-line switch.package.json: Change the following snippet in that file.Output: Upon launching the application, network logging will be enabled by Chromium and a log.txt file will be automatically generated within the assets folder with initial network log entries.Approach 2: Passing Command-line arguments using the CommandLine property of the app module. main.js Add the following Snippet at the start of the file just after importing the app module and before the ready event is emitted."
},
{
"code": null,
"e": 28728,
"s": 28251,
"text": "Approach 1: Passing Command-line arguments while launching the application. We will be using the –log-net-log=path Command-line switch. This switch enables network logging events to be recorded and writes the generated logs to the path file. We have already made the necessary changes to the package.json file to launch the application using the start script. We will modify this script to pass this Command-line switch.package.json: Change the following snippet in that file."
},
{
"code": null,
"e": 28922,
"s": 28728,
"text": "Output: Upon launching the application, network logging will be enabled by Chromium and a log.txt file will be automatically generated within the assets folder with initial network log entries."
},
{
"code": null,
"e": 29149,
"s": 28922,
"text": "Approach 2: Passing Command-line arguments using the CommandLine property of the app module. main.js Add the following Snippet at the start of the file just after importing the app module and before the ready event is emitted."
},
{
"code": null,
"e": 29160,
"s": 29149,
"text": "javascript"
},
{
"code": "const { app, BrowserWindow } = require(\"electron\");app.commandLine.appendSwitch(\"log-net-log\", \"assets/log.txt\");console.log(app.commandLine.hasSwitch(\"log-net-log\"));console.log(app.commandLine.getSwitchValue(\"log-net-log\"));",
"e": 29387,
"s": 29160,
"text": null
},
{
"code": null,
"e": 29566,
"s": 29390,
"text": "A detailed Explanation of all the Instance methods of the CommandLine property used in the code are explained below. For more detailed Information on the CommandLine property."
},
{
"code": null,
"e": 30389,
"s": 29568,
"text": "commandLine.appendSwitch(switch, value) This method appends a Switch with optional value parameter to Chromium’s Command line when invoking the application. This method does not have any return type. It takes in the following parameters. In our code, we have used this Instance method to append the –log-net-log=path Command-line switch.switch: String A Command-line switch without the leading — for appending to Chromium’s Command line when invoking the application. This value cannot be empty.value: String (Optional) A String value for the given Switch if it supports any. In case the Switch takes in a Boolean value, we will wrap the Boolean within String for it to be passed via this method. In our code, we have specified the path to the assets folder. By default, it will take the CWD (Current working Directory)."
},
{
"code": null,
"e": 30548,
"s": 30389,
"text": "switch: String A Command-line switch without the leading — for appending to Chromium’s Command line when invoking the application. This value cannot be empty."
},
{
"code": null,
"e": 30874,
"s": 30548,
"text": "value: String (Optional) A String value for the given Switch if it supports any. In case the Switch takes in a Boolean value, we will wrap the Boolean within String for it to be passed via this method. In our code, we have specified the path to the assets folder. By default, it will take the CWD (Current working Directory)."
},
{
"code": null,
"e": 31379,
"s": 30874,
"text": "commandLine.hasSwitch(switch) This method is used to check whether a Command-line switch is present when invoking the application from outside such as, the start script in the package.json file or has been appended using the commandLine.appendSwitch() method. It returns a Boolean value stating whether the Command-line switch is present. It takes in the following parameters.switch: String A Command-line switch without the leading — for checking the Chromium’s Command line. This value cannot be empty."
},
{
"code": null,
"e": 31508,
"s": 31379,
"text": "switch: String A Command-line switch without the leading — for checking the Chromium’s Command line. This value cannot be empty."
},
{
"code": null,
"e": 31906,
"s": 31508,
"text": "commandLine.getSwitchValue(switch) This method is used to return the Command-line Switch value, if any. It returns a String value. In case the Command-line switch is not present or there is no value, it will return an empty String. It takes in the following parameters.switch: String A Command-line switch without the leading — for checking the Chromium’s Command line. This value cannot be empty."
},
{
"code": null,
"e": 32035,
"s": 31906,
"text": "switch: String A Command-line switch without the leading — for checking the Chromium’s Command line. This value cannot be empty."
},
{
"code": null,
"e": 32795,
"s": 32035,
"text": "commandLine.appendArgument(argument) This method is used to append an Argument to the Chromium’s Command line when invoking the application. The argument will be quoted appropriately by the application. This method does not have any return type. This method is similar to the commandLine.appendSwitch() method but Command-line Switches will always precede the Arguments regardless of the appending order. In case we want to append a Command-line switch as an entire Argument, for example, ‘–log-net-log=assets/log.txt’ then we should not use this method. We should use the commandLine.appendSwitch() method instead. It takes in the following parameters.argument: String An String argument to be appended to Chromium’s Command-line. This value cannot be empty."
},
{
"code": null,
"e": 32902,
"s": 32795,
"text": "argument: String An String argument to be appended to Chromium’s Command-line. This value cannot be empty."
},
{
"code": null,
"e": 32921,
"s": 32904,
"text": "surinderdawra388"
},
{
"code": null,
"e": 32933,
"s": 32921,
"text": "kashishsoda"
},
{
"code": null,
"e": 32944,
"s": 32933,
"text": "ElectronJS"
},
{
"code": null,
"e": 32948,
"s": 32944,
"text": "CSS"
},
{
"code": null,
"e": 32953,
"s": 32948,
"text": "HTML"
},
{
"code": null,
"e": 32964,
"s": 32953,
"text": "JavaScript"
},
{
"code": null,
"e": 32972,
"s": 32964,
"text": "Node.js"
},
{
"code": null,
"e": 32989,
"s": 32972,
"text": "Web Technologies"
},
{
"code": null,
"e": 32994,
"s": 32989,
"text": "HTML"
},
{
"code": null,
"e": 33092,
"s": 32994,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33101,
"s": 33092,
"text": "Comments"
},
{
"code": null,
"e": 33114,
"s": 33101,
"text": "Old Comments"
},
{
"code": null,
"e": 33172,
"s": 33114,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 33209,
"s": 33172,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 33250,
"s": 33209,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 33287,
"s": 33250,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 33351,
"s": 33287,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 33411,
"s": 33351,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 33472,
"s": 33411,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 33509,
"s": 33472,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 33562,
"s": 33509,
"text": "Hide or show elements in HTML using display property"
}
] |
Check if bitwise AND of any subset is power of two - GeeksforGeeks
|
26 Jul, 2021
Given an array arr[] of n positive integers. The task is to check if there exist any subset of the array whose bitwise AND is a power of two (i.e 1, 2, 4, 8, 16, ...).Examples:
Input : n = 3, arr[] = { 12, 13, 7 }
Output : Yes
Subset { 12, 7 } has Bitwise AND value 4, which
is power of 2.
Input : n = 2, arr[] = { 10, 20 }
Output : No
Observe, for a number to be the power of 2, it should have only 1 set bit. If n is 1, then we simply check if the number has the only single set bit. For n is greater than one, our task becomes to choose those numbers from the array whose bitwise AND leads to an only single bit set number. To do so, we search a position, at which all elements in the set has a bit set at that position. For example, for set { 4 (100), 6 (110), 7 (111) }, at position 2 (from right to left, 0-based indexing) bit is set for all element. So, doing bitwise AND gives 4, which is a power of 2.Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to check if Bitwise AND of any// subset is power of two#include <bits/stdc++.h>using namespace std; const int NUM_BITS = 32; // Check for power of 2 or notbool isPowerOf2(int num){ return (num && !(num & (num - 1)));} // Check if there exist a subset whose bitwise AND// is power of 2.bool checkSubsequence(int arr[], int n){ // if there is only one element in the set. if (n == 1) return isPowerOf2(arr[0]); // Finding a number with all bit sets. int total = 0; for (int i = 0; i < NUM_BITS; i++) total = total | (1 << i); // check all the positions at which the bit is set. for (int i = 0; i < NUM_BITS; i++) { int ans = total; for (int j = 0; j < n; j++) { // include all those elements whose // i-th bit is set if (arr[j] & (1 << i)) ans = ans & arr[j]; } // check for the set contains elements // make a power of 2 or not if (isPowerOf2(ans)) return true; } return false;} // Driver Programint main(){ int arr[] = { 12, 13, 7 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkSubsequence(arr, n)) printf("YES\n"); else printf("NO\n"); return 0;}
// Java Program to check if Bitwise AND of any// subset is power of twoimport java.io.*;import java.util.*; public class GFG { static int NUM_BITS = 32; // Check for power of 2 or not static boolean isPowerOf2(int num) { if(num != 0 && (num & (num - 1)) == 0) return true; return false; } // Check if there exist a // subset whose bitwise AND // is power of 2. static boolean checkSubsequence(int []arr, int n) { // if there is only one // element in the set. if (n == 1) return isPowerOf2(arr[0]); // Finding a number with // all bit sets. int total = 0; for (int i = 0; i < NUM_BITS; i++) total = total | (1 << i); // check all the positions // at which the bit is set. for (int i = 0; i < NUM_BITS; i++) { int ans = total; for (int j = 0; j < n; j++) { // include all those // elements whose // i-th bit is set int p = arr[j] & (1 << i); if (p == 0) ans = ans & arr[j]; } // check for the set // contains elements // make a power of 2 // or not if (isPowerOf2(ans)) return true; } return false; } // Driver Code public static void main(String args[]) { int []arr = {12, 13, 7}; int n = arr.length; if (checkSubsequence(arr, n)) System.out.println("YES"); else System.out.println("NO"); }} // This code is contributed by// Manish Shaw (manishshaw1)
# Python3 Program to check if Bitwise AND of any# subset is power of two NUM_BITS = 32 # Check for power of 2 or notdef isPowerOf2(num): return (num and (num & (num - 1)) == 0) # Check if there exist a subset whose bitwise AND# is power of 2.def checkSubsequence(arr, n): # if there is only one element in the set. if (n == 1): return isPowerOf2(arr[0]) # Finding a number with all bit sets. total = 0 for i in range(0, NUM_BITS): total = total | (1 << i) # check all the positions at which the bit is set. for i in range(0, NUM_BITS): ans = total for j in range(0, n): # include all those elements whose # i-th bit is set if (arr[j] & (1 << i)): ans = ans & arr[j] # check for the set contains elements # make a power of 2 or not if (isPowerOf2(ans)): return True return False # Driver Programarr = [ 12, 13, 7 ]n = len(arr)if (checkSubsequence(arr, n)): print ("YES\n")else: print ("NO\n") # This code is contributed by Manish Shaw# (manishshaw1)
// C# Program to check if Bitwise AND of any// subset is power of twousing System;using System.Collections.Generic; class GFG { static int NUM_BITS = 32; // Check for power of 2 or not static bool isPowerOf2(int num) { if(num != 0 && (num & (num - 1)) == 0) return true; return false; } // Check if there exist a // subset whose bitwise AND // is power of 2. static bool checkSubsequence(int []arr, int n) { // if there is only one // element in the set. if (n == 1) return isPowerOf2(arr[0]); // Finding a number with // all bit sets. int total = 0; for (int i = 0; i < NUM_BITS; i++) total = total | (1 << i); // check all the positions // at which the bit is set. for (int i = 0; i < NUM_BITS; i++) { int ans = total; for (int j = 0; j < n; j++) { // include all those // elements whose // i-th bit is set int p = arr[j] & (1 << i); if (p == 0) ans = ans & arr[j]; } // check for the set // contains elements // make a power of 2 // or not if (isPowerOf2(ans)) return true; } return false; } // Driver Code public static void Main() { int []arr = {12, 13, 7}; int n = arr.Length; if (checkSubsequence(arr, n)) Console.Write("YES\n"); else Console.Write("NO\n"); }} // This code is contributed by// Manish Shaw (manishshaw1)
<?php// PHP Program to check if// Bitwise AND of any subset// is power of two // Check for power of 2 or notfunction isPowerOf2($num){ return ($num && !($num & ($num - 1)));} // Check if there exist a// subset whose bitwise AND// is power of 2.function checkSubsequence($arr, $n){ $NUM_BITS = 32; // if there is only one // element in the set. if ($n == 1) return isPowerOf2($arr[0]); // Finding a number with // all bit sets. $total = 0; for($i = 0; $i < $NUM_BITS; $i++) $total = $total | (1 << $i); // check all the positions at // which the bit is set. for($i = 0; $i < $NUM_BITS; $i++) { $ans = $total; for ($j = 0; $j < $n; $j++) { // include all those // elements whose // i-th bit is set if ($arr[$j] & (1 << $i)) $ans = $ans & $arr[$j]; } // check for the set // contains elements // make a power of 2 or not if (isPowerOf2($ans)) return true; } return false;} // Driver Code $arr= array(12, 13, 7); $n = sizeof($arr) / sizeof($arr[0]); if (checkSubsequence($arr, $n)) echo "YES"; else echo "NO"; // This code is contributed by mits?>
<script> // Javascript Program to check if Bitwise AND of any// subset is power of two var NUM_BITS = 32; // Check for power of 2 or notfunction isPowerOf2(num){ return (num && !(num & (num - 1)));} // Check if there exist a subset whose bitwise AND// is power of 2.function checkSubsequence(arr, n){ // if there is only one element in the set. if (n == 1) return isPowerOf2(arr[0]); // Finding a number with all bit sets. var total = 0; for (var i = 0; i < NUM_BITS; i++) total = total | (1 << i); // check all the positions at which the bit is set. for (var i = 0; i < NUM_BITS; i++) { var ans = total; for (var j = 0; j < n; j++) { // include all those elements whose // i-th bit is set if (arr[j] & (1 << i)) ans = ans & arr[j]; } // check for the set contains elements // make a power of 2 or not if (isPowerOf2(ans)) return true; } return false;} // Driver Programvar arr = [ 12, 13, 7 ];var n = arr.length;if (checkSubsequence(arr, n)) document.write("YES<br>");else document.write("NO<br>"); // This code is contributed by itsok.</script>
YES
Reference: https://stackoverflow.com/questions/35990794/subset-of-array-a-in-which-if-we-do-and-of-all-elements-of-that-subset-then-outp
Mithun Kumar
manishshaw1
itsok
surinderdawra388
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Trapping Rain Water
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Window Sliding Technique
Find duplicates in O(n) time and O(1) extra space | Set 1
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Cyclic Redundancy Check and Modulo-2 Division
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
|
[
{
"code": null,
"e": 24740,
"s": 24712,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 24919,
"s": 24740,
"text": "Given an array arr[] of n positive integers. The task is to check if there exist any subset of the array whose bitwise AND is a power of two (i.e 1, 2, 4, 8, 16, ...).Examples: "
},
{
"code": null,
"e": 25080,
"s": 24919,
"text": "Input : n = 3, arr[] = { 12, 13, 7 }\nOutput : Yes\nSubset { 12, 7 } has Bitwise AND value 4, which \nis power of 2.\n\nInput : n = 2, arr[] = { 10, 20 }\nOutput : No"
},
{
"code": null,
"e": 25704,
"s": 25082,
"text": "Observe, for a number to be the power of 2, it should have only 1 set bit. If n is 1, then we simply check if the number has the only single set bit. For n is greater than one, our task becomes to choose those numbers from the array whose bitwise AND leads to an only single bit set number. To do so, we search a position, at which all elements in the set has a bit set at that position. For example, for set { 4 (100), 6 (110), 7 (111) }, at position 2 (from right to left, 0-based indexing) bit is set for all element. So, doing bitwise AND gives 4, which is a power of 2.Below is the implementation of this approach: "
},
{
"code": null,
"e": 25708,
"s": 25704,
"text": "C++"
},
{
"code": null,
"e": 25713,
"s": 25708,
"text": "Java"
},
{
"code": null,
"e": 25721,
"s": 25713,
"text": "Python3"
},
{
"code": null,
"e": 25724,
"s": 25721,
"text": "C#"
},
{
"code": null,
"e": 25728,
"s": 25724,
"text": "PHP"
},
{
"code": null,
"e": 25739,
"s": 25728,
"text": "Javascript"
},
{
"code": "// CPP Program to check if Bitwise AND of any// subset is power of two#include <bits/stdc++.h>using namespace std; const int NUM_BITS = 32; // Check for power of 2 or notbool isPowerOf2(int num){ return (num && !(num & (num - 1)));} // Check if there exist a subset whose bitwise AND// is power of 2.bool checkSubsequence(int arr[], int n){ // if there is only one element in the set. if (n == 1) return isPowerOf2(arr[0]); // Finding a number with all bit sets. int total = 0; for (int i = 0; i < NUM_BITS; i++) total = total | (1 << i); // check all the positions at which the bit is set. for (int i = 0; i < NUM_BITS; i++) { int ans = total; for (int j = 0; j < n; j++) { // include all those elements whose // i-th bit is set if (arr[j] & (1 << i)) ans = ans & arr[j]; } // check for the set contains elements // make a power of 2 or not if (isPowerOf2(ans)) return true; } return false;} // Driver Programint main(){ int arr[] = { 12, 13, 7 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkSubsequence(arr, n)) printf(\"YES\\n\"); else printf(\"NO\\n\"); return 0;}",
"e": 26983,
"s": 25739,
"text": null
},
{
"code": "// Java Program to check if Bitwise AND of any// subset is power of twoimport java.io.*;import java.util.*; public class GFG { static int NUM_BITS = 32; // Check for power of 2 or not static boolean isPowerOf2(int num) { if(num != 0 && (num & (num - 1)) == 0) return true; return false; } // Check if there exist a // subset whose bitwise AND // is power of 2. static boolean checkSubsequence(int []arr, int n) { // if there is only one // element in the set. if (n == 1) return isPowerOf2(arr[0]); // Finding a number with // all bit sets. int total = 0; for (int i = 0; i < NUM_BITS; i++) total = total | (1 << i); // check all the positions // at which the bit is set. for (int i = 0; i < NUM_BITS; i++) { int ans = total; for (int j = 0; j < n; j++) { // include all those // elements whose // i-th bit is set int p = arr[j] & (1 << i); if (p == 0) ans = ans & arr[j]; } // check for the set // contains elements // make a power of 2 // or not if (isPowerOf2(ans)) return true; } return false; } // Driver Code public static void main(String args[]) { int []arr = {12, 13, 7}; int n = arr.length; if (checkSubsequence(arr, n)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }} // This code is contributed by// Manish Shaw (manishshaw1)",
"e": 28740,
"s": 26983,
"text": null
},
{
"code": "# Python3 Program to check if Bitwise AND of any# subset is power of two NUM_BITS = 32 # Check for power of 2 or notdef isPowerOf2(num): return (num and (num & (num - 1)) == 0) # Check if there exist a subset whose bitwise AND# is power of 2.def checkSubsequence(arr, n): # if there is only one element in the set. if (n == 1): return isPowerOf2(arr[0]) # Finding a number with all bit sets. total = 0 for i in range(0, NUM_BITS): total = total | (1 << i) # check all the positions at which the bit is set. for i in range(0, NUM_BITS): ans = total for j in range(0, n): # include all those elements whose # i-th bit is set if (arr[j] & (1 << i)): ans = ans & arr[j] # check for the set contains elements # make a power of 2 or not if (isPowerOf2(ans)): return True return False # Driver Programarr = [ 12, 13, 7 ]n = len(arr)if (checkSubsequence(arr, n)): print (\"YES\\n\")else: print (\"NO\\n\") # This code is contributed by Manish Shaw# (manishshaw1)",
"e": 29844,
"s": 28740,
"text": null
},
{
"code": "// C# Program to check if Bitwise AND of any// subset is power of twousing System;using System.Collections.Generic; class GFG { static int NUM_BITS = 32; // Check for power of 2 or not static bool isPowerOf2(int num) { if(num != 0 && (num & (num - 1)) == 0) return true; return false; } // Check if there exist a // subset whose bitwise AND // is power of 2. static bool checkSubsequence(int []arr, int n) { // if there is only one // element in the set. if (n == 1) return isPowerOf2(arr[0]); // Finding a number with // all bit sets. int total = 0; for (int i = 0; i < NUM_BITS; i++) total = total | (1 << i); // check all the positions // at which the bit is set. for (int i = 0; i < NUM_BITS; i++) { int ans = total; for (int j = 0; j < n; j++) { // include all those // elements whose // i-th bit is set int p = arr[j] & (1 << i); if (p == 0) ans = ans & arr[j]; } // check for the set // contains elements // make a power of 2 // or not if (isPowerOf2(ans)) return true; } return false; } // Driver Code public static void Main() { int []arr = {12, 13, 7}; int n = arr.Length; if (checkSubsequence(arr, n)) Console.Write(\"YES\\n\"); else Console.Write(\"NO\\n\"); }} // This code is contributed by// Manish Shaw (manishshaw1)",
"e": 31566,
"s": 29844,
"text": null
},
{
"code": "<?php// PHP Program to check if// Bitwise AND of any subset// is power of two // Check for power of 2 or notfunction isPowerOf2($num){ return ($num && !($num & ($num - 1)));} // Check if there exist a// subset whose bitwise AND// is power of 2.function checkSubsequence($arr, $n){ $NUM_BITS = 32; // if there is only one // element in the set. if ($n == 1) return isPowerOf2($arr[0]); // Finding a number with // all bit sets. $total = 0; for($i = 0; $i < $NUM_BITS; $i++) $total = $total | (1 << $i); // check all the positions at // which the bit is set. for($i = 0; $i < $NUM_BITS; $i++) { $ans = $total; for ($j = 0; $j < $n; $j++) { // include all those // elements whose // i-th bit is set if ($arr[$j] & (1 << $i)) $ans = $ans & $arr[$j]; } // check for the set // contains elements // make a power of 2 or not if (isPowerOf2($ans)) return true; } return false;} // Driver Code $arr= array(12, 13, 7); $n = sizeof($arr) / sizeof($arr[0]); if (checkSubsequence($arr, $n)) echo \"YES\"; else echo \"NO\"; // This code is contributed by mits?>",
"e": 32831,
"s": 31566,
"text": null
},
{
"code": "<script> // Javascript Program to check if Bitwise AND of any// subset is power of two var NUM_BITS = 32; // Check for power of 2 or notfunction isPowerOf2(num){ return (num && !(num & (num - 1)));} // Check if there exist a subset whose bitwise AND// is power of 2.function checkSubsequence(arr, n){ // if there is only one element in the set. if (n == 1) return isPowerOf2(arr[0]); // Finding a number with all bit sets. var total = 0; for (var i = 0; i < NUM_BITS; i++) total = total | (1 << i); // check all the positions at which the bit is set. for (var i = 0; i < NUM_BITS; i++) { var ans = total; for (var j = 0; j < n; j++) { // include all those elements whose // i-th bit is set if (arr[j] & (1 << i)) ans = ans & arr[j]; } // check for the set contains elements // make a power of 2 or not if (isPowerOf2(ans)) return true; } return false;} // Driver Programvar arr = [ 12, 13, 7 ];var n = arr.length;if (checkSubsequence(arr, n)) document.write(\"YES<br>\");else document.write(\"NO<br>\"); // This code is contributed by itsok.</script>",
"e": 34034,
"s": 32831,
"text": null
},
{
"code": null,
"e": 34038,
"s": 34034,
"text": "YES"
},
{
"code": null,
"e": 34178,
"s": 34040,
"text": "Reference: https://stackoverflow.com/questions/35990794/subset-of-array-a-in-which-if-we-do-and-of-all-elements-of-that-subset-then-outp "
},
{
"code": null,
"e": 34191,
"s": 34178,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 34203,
"s": 34191,
"text": "manishshaw1"
},
{
"code": null,
"e": 34209,
"s": 34203,
"text": "itsok"
},
{
"code": null,
"e": 34226,
"s": 34209,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34233,
"s": 34226,
"text": "Arrays"
},
{
"code": null,
"e": 34243,
"s": 34233,
"text": "Bit Magic"
},
{
"code": null,
"e": 34250,
"s": 34243,
"text": "Arrays"
},
{
"code": null,
"e": 34260,
"s": 34250,
"text": "Bit Magic"
},
{
"code": null,
"e": 34358,
"s": 34260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34367,
"s": 34358,
"text": "Comments"
},
{
"code": null,
"e": 34380,
"s": 34367,
"text": "Old Comments"
},
{
"code": null,
"e": 34400,
"s": 34380,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 34449,
"s": 34400,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34487,
"s": 34449,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34512,
"s": 34487,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34570,
"s": 34512,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 34597,
"s": 34570,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 34643,
"s": 34597,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 34689,
"s": 34643,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 34757,
"s": 34689,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
}
] |
How to compare two dates with JavaScript?
|
To compare two dates with JavaScript, create two dates object and get the recent date. You can try to run the following code to compare two dates.
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var date1, date2;
date1 = new Date();
document.write(date1);
date2 = new Date( "Dec 15, 2014 21:20:15" );
document.write("<br>"+date2);
if (date1 > date2) {
document.write("<br>Date1 is the recent date.");
} else {
document.write("<br>Date 2 is the recent date.");
}
</script>
</body>
</html>
Sat Dec 15 2018 11:08:06 GMT+0530 (India Standard Time)
Mon Dec 15 2014 21:20:15 GMT+0530 (India Standard Time)
Date1 is the recent date.
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "To compare two dates with JavaScript, create two dates object and get the recent date. You can try to run the following code to compare two dates."
},
{
"code": null,
"e": 1220,
"s": 1209,
"text": " Live Demo"
},
{
"code": null,
"e": 1666,
"s": 1220,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n var date1, date2;\n date1 = new Date();\n document.write(date1);\n date2 = new Date( \"Dec 15, 2014 21:20:15\" );\n document.write(\"<br>\"+date2);\n if (date1 > date2) {\n document.write(\"<br>Date1 is the recent date.\");\n } else {\n document.write(\"<br>Date 2 is the recent date.\");\n }\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1804,
"s": 1666,
"text": "Sat Dec 15 2018 11:08:06 GMT+0530 (India Standard Time)\nMon Dec 15 2014 21:20:15 GMT+0530 (India Standard Time)\nDate1 is the recent date."
}
] |
Grouping Soccer Players with Similar Skillsets in FIFA 20 | Part 1: K-Means Clustering | by Jaemin Lee | Towards Data Science
|
Soccer (European football) has been one of my favorite sports ever since I was little. I used to bring a ball with me anywhere I went so that I could maximize my opportunity to play soccer.
I also like playing soccer games — FIFA. I thought it would be cool to analyze players in FIFA using machine learning.
In this tutorial, I am going to use the K-Means clustering algorithm to group soccer players in FIFA 20 with similar skillsets.
Clustering is one of the unsupervised learning techniques (PCA is another one).
We can cluster (or group) observations into the same subgroups so that observations within a subgroup are quite similar to each other and observations in different subgroups are quite different from each other.
The scatter plot above shows us that there are three distinct groups within the dataset.
K-Means clustering is one of the clustering algorithms.
The basic algorithm is this:
Specify K-clusters and initialize random centroids
Iterate until the cluster assignments stop changing. The method assigns each observation to exactly one of the K clusters
For each K cluster, calculate the cluster mean
Proceed through the list of observations and assign an observation to the cluster whose mean is nearest.
The goal is to form the clusters in a way that the observations within the same cluster are as similar as possible.
K-Means clustering calculates similarity using Squared Euclidean distance.
We are going to use Kaggle’s FIFA 20 dataset.
We are only going to selected numeric values and each player’s name.
df = df[['short_name','age', 'height_cm', 'weight_kg', 'overall', 'potential','value_eur', 'wage_eur', 'international_reputation', 'weak_foot','skill_moves', 'release_clause_eur', 'team_jersey_number','contract_valid_until', 'nation_jersey_number', 'pace', 'shooting','passing', 'dribbling', 'defending', 'physic', 'gk_diving','gk_handling', 'gk_kicking', 'gk_reflexes', 'gk_speed','gk_positioning', 'attacking_crossing', 'attacking_finishing','attacking_heading_accuracy', 'attacking_short_passing','attacking_volleys', 'skill_dribbling', 'skill_curve','skill_fk_accuracy', 'skill_long_passing', 'skill_ball_control','movement_acceleration', 'movement_sprint_speed', 'movement_agility','movement_reactions', 'movement_balance', 'power_shot_power','power_jumping', 'power_stamina', 'power_strength', 'power_long_shots','mentality_aggression', 'mentality_interceptions','mentality_positioning', 'mentality_vision', 'mentality_penalties','mentality_composure', 'defending_marking', 'defending_standing_tackle','defending_sliding_tackle', 'goalkeeping_diving','goalkeeping_handling', 'goalkeeping_kicking','goalkeeping_positioning', 'goalkeeping_reflexes']]
I am extract players whose overalls’ are above 86 as we don’t want to use 18000+ players to group.
df = df[df.overall > 86] # extracting players with overall above 86
Replace null values with the mean.
df = df.fillna(df.mean())
Normalize (standardize/rescale) the data.
We want to normalize the data as variables are measured on different scales.
from sklearn import preprocessingx = df.values # numpy arrayscaler = preprocessing.MinMaxScaler()x_scaled = scaler.fit_transform(x)X_norm = pd.DataFrame(x_scaled)
Use PCA to reduce 60 dimensions into 2 for the plot.
from sklearn.decomposition import PCApca = PCA(n_components = 2) # 2D PCA for the plotreduced = pd.DataFrame(pca.fit_transform(X_norm))
We are going to specify that there are 5 clusters.
from sklearn.cluster import KMeans# specify the number of clusterskmeans = KMeans(n_clusters=5)# fit the input datakmeans = kmeans.fit(reduced)# get the cluster labelslabels = kmeans.predict(reduced)# centroid valuescentroid = kmeans.cluster_centers_# cluster valuesclusters = kmeans.labels_.tolist()
Make a new data frame by adding players’ names and their clusters.
reduced['cluster'] = clustersreduced['name'] = namesreduced.columns = ['x', 'y', 'cluster', 'name']reduced.head()
import matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinesns.set(style="white")ax = sns.lmplot(x="x", y="y", hue='cluster', data = reduced, legend=False,fit_reg=False, size = 15, scatter_kws={"s": 250})texts = []for x, y, s in zip(reduced.x, reduced.y, reduced.name):texts.append(plt.text(x, y, s))ax.set(ylim=(-2, 2))plt.tick_params(labelsize=15)plt.xlabel("PC 1", fontsize = 20)plt.ylabel("PC 2", fontsize = 20)plt.show()
It’s cool to see how clusters are formed based on players’ positions!
I hope you find this tutorial useful and stay tuned for the next ones!
|
[
{
"code": null,
"e": 362,
"s": 172,
"text": "Soccer (European football) has been one of my favorite sports ever since I was little. I used to bring a ball with me anywhere I went so that I could maximize my opportunity to play soccer."
},
{
"code": null,
"e": 481,
"s": 362,
"text": "I also like playing soccer games — FIFA. I thought it would be cool to analyze players in FIFA using machine learning."
},
{
"code": null,
"e": 609,
"s": 481,
"text": "In this tutorial, I am going to use the K-Means clustering algorithm to group soccer players in FIFA 20 with similar skillsets."
},
{
"code": null,
"e": 689,
"s": 609,
"text": "Clustering is one of the unsupervised learning techniques (PCA is another one)."
},
{
"code": null,
"e": 900,
"s": 689,
"text": "We can cluster (or group) observations into the same subgroups so that observations within a subgroup are quite similar to each other and observations in different subgroups are quite different from each other."
},
{
"code": null,
"e": 989,
"s": 900,
"text": "The scatter plot above shows us that there are three distinct groups within the dataset."
},
{
"code": null,
"e": 1045,
"s": 989,
"text": "K-Means clustering is one of the clustering algorithms."
},
{
"code": null,
"e": 1074,
"s": 1045,
"text": "The basic algorithm is this:"
},
{
"code": null,
"e": 1125,
"s": 1074,
"text": "Specify K-clusters and initialize random centroids"
},
{
"code": null,
"e": 1247,
"s": 1125,
"text": "Iterate until the cluster assignments stop changing. The method assigns each observation to exactly one of the K clusters"
},
{
"code": null,
"e": 1294,
"s": 1247,
"text": "For each K cluster, calculate the cluster mean"
},
{
"code": null,
"e": 1399,
"s": 1294,
"text": "Proceed through the list of observations and assign an observation to the cluster whose mean is nearest."
},
{
"code": null,
"e": 1515,
"s": 1399,
"text": "The goal is to form the clusters in a way that the observations within the same cluster are as similar as possible."
},
{
"code": null,
"e": 1590,
"s": 1515,
"text": "K-Means clustering calculates similarity using Squared Euclidean distance."
},
{
"code": null,
"e": 1636,
"s": 1590,
"text": "We are going to use Kaggle’s FIFA 20 dataset."
},
{
"code": null,
"e": 1705,
"s": 1636,
"text": "We are only going to selected numeric values and each player’s name."
},
{
"code": null,
"e": 2860,
"s": 1705,
"text": "df = df[['short_name','age', 'height_cm', 'weight_kg', 'overall', 'potential','value_eur', 'wage_eur', 'international_reputation', 'weak_foot','skill_moves', 'release_clause_eur', 'team_jersey_number','contract_valid_until', 'nation_jersey_number', 'pace', 'shooting','passing', 'dribbling', 'defending', 'physic', 'gk_diving','gk_handling', 'gk_kicking', 'gk_reflexes', 'gk_speed','gk_positioning', 'attacking_crossing', 'attacking_finishing','attacking_heading_accuracy', 'attacking_short_passing','attacking_volleys', 'skill_dribbling', 'skill_curve','skill_fk_accuracy', 'skill_long_passing', 'skill_ball_control','movement_acceleration', 'movement_sprint_speed', 'movement_agility','movement_reactions', 'movement_balance', 'power_shot_power','power_jumping', 'power_stamina', 'power_strength', 'power_long_shots','mentality_aggression', 'mentality_interceptions','mentality_positioning', 'mentality_vision', 'mentality_penalties','mentality_composure', 'defending_marking', 'defending_standing_tackle','defending_sliding_tackle', 'goalkeeping_diving','goalkeeping_handling', 'goalkeeping_kicking','goalkeeping_positioning', 'goalkeeping_reflexes']]"
},
{
"code": null,
"e": 2959,
"s": 2860,
"text": "I am extract players whose overalls’ are above 86 as we don’t want to use 18000+ players to group."
},
{
"code": null,
"e": 3027,
"s": 2959,
"text": "df = df[df.overall > 86] # extracting players with overall above 86"
},
{
"code": null,
"e": 3062,
"s": 3027,
"text": "Replace null values with the mean."
},
{
"code": null,
"e": 3088,
"s": 3062,
"text": "df = df.fillna(df.mean())"
},
{
"code": null,
"e": 3130,
"s": 3088,
"text": "Normalize (standardize/rescale) the data."
},
{
"code": null,
"e": 3207,
"s": 3130,
"text": "We want to normalize the data as variables are measured on different scales."
},
{
"code": null,
"e": 3370,
"s": 3207,
"text": "from sklearn import preprocessingx = df.values # numpy arrayscaler = preprocessing.MinMaxScaler()x_scaled = scaler.fit_transform(x)X_norm = pd.DataFrame(x_scaled)"
},
{
"code": null,
"e": 3423,
"s": 3370,
"text": "Use PCA to reduce 60 dimensions into 2 for the plot."
},
{
"code": null,
"e": 3559,
"s": 3423,
"text": "from sklearn.decomposition import PCApca = PCA(n_components = 2) # 2D PCA for the plotreduced = pd.DataFrame(pca.fit_transform(X_norm))"
},
{
"code": null,
"e": 3610,
"s": 3559,
"text": "We are going to specify that there are 5 clusters."
},
{
"code": null,
"e": 3911,
"s": 3610,
"text": "from sklearn.cluster import KMeans# specify the number of clusterskmeans = KMeans(n_clusters=5)# fit the input datakmeans = kmeans.fit(reduced)# get the cluster labelslabels = kmeans.predict(reduced)# centroid valuescentroid = kmeans.cluster_centers_# cluster valuesclusters = kmeans.labels_.tolist()"
},
{
"code": null,
"e": 3978,
"s": 3911,
"text": "Make a new data frame by adding players’ names and their clusters."
},
{
"code": null,
"e": 4092,
"s": 3978,
"text": "reduced['cluster'] = clustersreduced['name'] = namesreduced.columns = ['x', 'y', 'cluster', 'name']reduced.head()"
},
{
"code": null,
"e": 4529,
"s": 4092,
"text": "import matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinesns.set(style=\"white\")ax = sns.lmplot(x=\"x\", y=\"y\", hue='cluster', data = reduced, legend=False,fit_reg=False, size = 15, scatter_kws={\"s\": 250})texts = []for x, y, s in zip(reduced.x, reduced.y, reduced.name):texts.append(plt.text(x, y, s))ax.set(ylim=(-2, 2))plt.tick_params(labelsize=15)plt.xlabel(\"PC 1\", fontsize = 20)plt.ylabel(\"PC 2\", fontsize = 20)plt.show()"
},
{
"code": null,
"e": 4599,
"s": 4529,
"text": "It’s cool to see how clusters are formed based on players’ positions!"
}
] |
Spotify Artist Recommender | by Michael Whittle | Towards Data Science
|
Recommender systems within applications and services are no longer a “nice to have”. Users are now becoming accustomed to having this functionality as standard. Audio streaming, video streaming, advertising, search engines, blogs, etc. just to name a few.
When it comes to recommender systems there are a few common techniques. My favourite technique is “cosine similarity”. It’s easy to understand and very fast. Even without a data science background, the concept shouldn’t be too difficult to grasp.
The basic concept is as follows.
Plot a numeric representation of the items you wish to compare (A and B above) and then calculate the cosine distance between the points. The theory behind it is the smaller the distance, the more similar they are.
Create a recommender system to find similar artists on Spotify.
I downloaded the dataset, “Spotify Dataset 1922–2021, ~600k Tracks” on Kaggle. The file I will be working with is called “data_by_artist_o.csv”.
import pandas as pdimport numpy as npfrom sklearn.metrics.pairwise import cosine_similarityfrom sklearn.preprocessing import StandardScalerdf_artists = pd.read_csv('./data_by_artist_o.csv', encoding='utf-8')df_artists.shape
This dataset has 28680 songs with 11 features/columns.
The data is actually in a pretty good state already and there aren’t any null values.
df_artists.isnull().sum()
df_artists.info()
df_artists.describe()
There are a few features that are non-numeric or don’t really add much value so we will remove those.
df_artists.drop(columns={'genres', 'key', 'mode', 'count'}, inplace=True)df_artists.head()
The issue we have now is that all those descriptive features are all in different scales. We need to scale the data so they are all comparable.
ss = StandardScaler()df_artists_scaled = ss.fit_transform(df_artists)df_artists_scaled = pd.DataFrame(data=df_artists_scaled, index=df_artists.index, columns=df_artists.columns)df_artists_scaled.head()
As you can see now the features are all within the range of -1 to 1.
Let’s see how this works with “Ed Sheeran” as the artist.
artist_array = np.array(df_artists_scaled.T['Ed Sheeran']).reshape(1,-1)artist_dataset_array = df_artists_scaled.drop(index='Ed Sheeran').valuescosine_similarity(artist_array, artist_dataset_array)
df_Ed_Sheeran = df_artists.drop(index='Ed Sheeran').copy()df_Ed_Sheeran['cosim_score'] = cosine_similarity(artist_array, artist_dataset_array).reshape(-1,1)df_Ed_Sheeran
Take a look at the newly created “cosim_score” at the end. That shows us show similar the artist is with the other artists using “cosine similarity”.
We now have the building blocks to create ourselves a handy function.
def get_cosim_artist_df(artist_name, df, n): ss = StandardScaler() df_scaled = ss.fit_transform(df) df = pd.DataFrame(data=df_scaled, index=df.index) artist_array = np.array(df.T[artist_name]).reshape(1,-1) dataset_array = df.drop(index=artist_name).values cosim_scores = cosine_similarity(artist_array, dataset_array).flatten()artist_names_array = df.drop(index=artist_name).index.values df_result = pd.DataFrame( data = { 'artist' : artist_names_array, 'cosim_' + artist_name : cosim_scores, } ) df_result = df_result.sort_values(by='cosim_' + artist_name, ascending=False).head(n) return df_result.reset_index(drop=True)
And let’s see it in action...
get_cosim_artist_df('Ed Sheeran', df_artists, 20)
According to our newly created function, the top 20 artists that are similar to “Ed Sheeran”...
I have to admit I don’t recognise most of those artists in the list. I opened up Spotify and listened to the top 3 which are over 93% cosine similar and I think it did a pretty good job. It would be interesting to know what you think in the comments.
This technique is not limited to audio and video streaming, which is probably the first use case that comes to mind. As long as you can structure your data into a pivot table this will work. I’ll give you one more example as food for thought. Let’s say you have a web site and you want to recommend either pages or documents to your users. You could create a pivot table with the page name or document title as the index (rows) and you could maybe create a list of “tags” as the columns. If the tag describes the page or document you would either mark it as a 0 or 1, or maybe even a weight if some tags are more important than others. Then you run it through exactly the same process as above as it will work like charm.
If you liked this article I’ve written some other articles I think you may find interesting. I’m working through explaining various machine learning concepts by example.
levelup.gitconnected.com
levelup.gitconnected.com
levelup.gitconnected.com
If you enjoyed this, please follow me on Medium
Interested in collaborating? Let’s connect on LinkedIn
|
[
{
"code": null,
"e": 428,
"s": 172,
"text": "Recommender systems within applications and services are no longer a “nice to have”. Users are now becoming accustomed to having this functionality as standard. Audio streaming, video streaming, advertising, search engines, blogs, etc. just to name a few."
},
{
"code": null,
"e": 675,
"s": 428,
"text": "When it comes to recommender systems there are a few common techniques. My favourite technique is “cosine similarity”. It’s easy to understand and very fast. Even without a data science background, the concept shouldn’t be too difficult to grasp."
},
{
"code": null,
"e": 708,
"s": 675,
"text": "The basic concept is as follows."
},
{
"code": null,
"e": 923,
"s": 708,
"text": "Plot a numeric representation of the items you wish to compare (A and B above) and then calculate the cosine distance between the points. The theory behind it is the smaller the distance, the more similar they are."
},
{
"code": null,
"e": 987,
"s": 923,
"text": "Create a recommender system to find similar artists on Spotify."
},
{
"code": null,
"e": 1132,
"s": 987,
"text": "I downloaded the dataset, “Spotify Dataset 1922–2021, ~600k Tracks” on Kaggle. The file I will be working with is called “data_by_artist_o.csv”."
},
{
"code": null,
"e": 1356,
"s": 1132,
"text": "import pandas as pdimport numpy as npfrom sklearn.metrics.pairwise import cosine_similarityfrom sklearn.preprocessing import StandardScalerdf_artists = pd.read_csv('./data_by_artist_o.csv', encoding='utf-8')df_artists.shape"
},
{
"code": null,
"e": 1411,
"s": 1356,
"text": "This dataset has 28680 songs with 11 features/columns."
},
{
"code": null,
"e": 1497,
"s": 1411,
"text": "The data is actually in a pretty good state already and there aren’t any null values."
},
{
"code": null,
"e": 1523,
"s": 1497,
"text": "df_artists.isnull().sum()"
},
{
"code": null,
"e": 1541,
"s": 1523,
"text": "df_artists.info()"
},
{
"code": null,
"e": 1563,
"s": 1541,
"text": "df_artists.describe()"
},
{
"code": null,
"e": 1665,
"s": 1563,
"text": "There are a few features that are non-numeric or don’t really add much value so we will remove those."
},
{
"code": null,
"e": 1756,
"s": 1665,
"text": "df_artists.drop(columns={'genres', 'key', 'mode', 'count'}, inplace=True)df_artists.head()"
},
{
"code": null,
"e": 1900,
"s": 1756,
"text": "The issue we have now is that all those descriptive features are all in different scales. We need to scale the data so they are all comparable."
},
{
"code": null,
"e": 2102,
"s": 1900,
"text": "ss = StandardScaler()df_artists_scaled = ss.fit_transform(df_artists)df_artists_scaled = pd.DataFrame(data=df_artists_scaled, index=df_artists.index, columns=df_artists.columns)df_artists_scaled.head()"
},
{
"code": null,
"e": 2171,
"s": 2102,
"text": "As you can see now the features are all within the range of -1 to 1."
},
{
"code": null,
"e": 2229,
"s": 2171,
"text": "Let’s see how this works with “Ed Sheeran” as the artist."
},
{
"code": null,
"e": 2427,
"s": 2229,
"text": "artist_array = np.array(df_artists_scaled.T['Ed Sheeran']).reshape(1,-1)artist_dataset_array = df_artists_scaled.drop(index='Ed Sheeran').valuescosine_similarity(artist_array, artist_dataset_array)"
},
{
"code": null,
"e": 2597,
"s": 2427,
"text": "df_Ed_Sheeran = df_artists.drop(index='Ed Sheeran').copy()df_Ed_Sheeran['cosim_score'] = cosine_similarity(artist_array, artist_dataset_array).reshape(-1,1)df_Ed_Sheeran"
},
{
"code": null,
"e": 2747,
"s": 2597,
"text": "Take a look at the newly created “cosim_score” at the end. That shows us show similar the artist is with the other artists using “cosine similarity”."
},
{
"code": null,
"e": 2817,
"s": 2747,
"text": "We now have the building blocks to create ourselves a handy function."
},
{
"code": null,
"e": 3541,
"s": 2817,
"text": "def get_cosim_artist_df(artist_name, df, n): ss = StandardScaler() df_scaled = ss.fit_transform(df) df = pd.DataFrame(data=df_scaled, index=df.index) artist_array = np.array(df.T[artist_name]).reshape(1,-1) dataset_array = df.drop(index=artist_name).values cosim_scores = cosine_similarity(artist_array, dataset_array).flatten()artist_names_array = df.drop(index=artist_name).index.values df_result = pd.DataFrame( data = { 'artist' : artist_names_array, 'cosim_' + artist_name : cosim_scores, } ) df_result = df_result.sort_values(by='cosim_' + artist_name, ascending=False).head(n) return df_result.reset_index(drop=True)"
},
{
"code": null,
"e": 3571,
"s": 3541,
"text": "And let’s see it in action..."
},
{
"code": null,
"e": 3621,
"s": 3571,
"text": "get_cosim_artist_df('Ed Sheeran', df_artists, 20)"
},
{
"code": null,
"e": 3717,
"s": 3621,
"text": "According to our newly created function, the top 20 artists that are similar to “Ed Sheeran”..."
},
{
"code": null,
"e": 3968,
"s": 3717,
"text": "I have to admit I don’t recognise most of those artists in the list. I opened up Spotify and listened to the top 3 which are over 93% cosine similar and I think it did a pretty good job. It would be interesting to know what you think in the comments."
},
{
"code": null,
"e": 4690,
"s": 3968,
"text": "This technique is not limited to audio and video streaming, which is probably the first use case that comes to mind. As long as you can structure your data into a pivot table this will work. I’ll give you one more example as food for thought. Let’s say you have a web site and you want to recommend either pages or documents to your users. You could create a pivot table with the page name or document title as the index (rows) and you could maybe create a list of “tags” as the columns. If the tag describes the page or document you would either mark it as a 0 or 1, or maybe even a weight if some tags are more important than others. Then you run it through exactly the same process as above as it will work like charm."
},
{
"code": null,
"e": 4860,
"s": 4690,
"text": "If you liked this article I’ve written some other articles I think you may find interesting. I’m working through explaining various machine learning concepts by example."
},
{
"code": null,
"e": 4885,
"s": 4860,
"text": "levelup.gitconnected.com"
},
{
"code": null,
"e": 4910,
"s": 4885,
"text": "levelup.gitconnected.com"
},
{
"code": null,
"e": 4935,
"s": 4910,
"text": "levelup.gitconnected.com"
},
{
"code": null,
"e": 4983,
"s": 4935,
"text": "If you enjoyed this, please follow me on Medium"
}
] |
What is a composite data type i.e. object in JavaScript?
|
A data type is known as a composite data type when it represents a number of similar or different data under a single declaration of variable i.e., a data type that has multiple values grouped together. There are mainly three types of composite data types named as below −
Object
Object
Array
Array
Function
Function
In this article, we will discuss the first type of composite data type i.e. object.
An object is a collection of properties i.e, an object can store the properties of anything in the key-value pairs. An object in javascript has keys and each key has its own value as shown in the example
let person={firstname:"Prince", lastname:"Varshney", age:23, haircolour:"Black"};
An object is used whenever we want to store more than one value for a single variable like in the above example we have stored the firstname, lastname, age, and haircolour of a person in a single variable named ‘person’. The property of an object can be of any data type i.e., it can be string, number, Boolean or it can be an array as well. Due to the specialty of having data of any data type the objects are very useful in processing large amounts of data. We can use an object to store the whole data of a batch of students, people of a society, or people in a country.
You can try to run the following code to learn how to declare objects in JavaScript
<html>
<head>
<title>Javascript objects</title>
</head>
<body>
<script>
let person={firstname:"Shivi", lastname:"Singh", age:23, haircolour:"Black"};
for (i in person){
document.write(i + ": " + person[i] + "<br />");
}
</script>
</body>
</html>
This will produce the following result -
firstname: Shivi
lastname: Singh
age: 23
haircolour: Black
We can also create an empty JavaScript object and add properties in the object later. To create an empty object, we have to use the “new” keyword like shown below −
<html>
<head>
<title>Javascript objects</title>
</head>
<body>
<script>
let person=new Object();
person.firstname="Shivi";
person.lastname="Singh";
person.age=23;
person.haircolour="Black";
for (i in person){
document.write(i + ": " + person[i] + "<br />");
}
</script>
</body>
</html>
This will produce the following result -
firstname: Shivi
lastname: Singh
age: 23
haircolour: Black
Each and every value of an object can be fetched so that we can use them further whenever we need them in our code further. The object values can be accessed by 2 methods −
We can access the object value using a dot(.) operator as shown in the below example −
<html>
<head>
<title>Javascript objects</title>
</head>
<body>
<script>
let person={firstname:"Prince", lastname:"Varshney", age:23, haircolour:"Black"};
document.write(person.firstname);
document.write("<br>");
document.write(person.age);
</script>
</body>
</html>
The output of the above example is given below −
Prince
23
We can also access the object value using a square bracket [] as shown in the below example −
<html>
<head>
<title>Javascript objects</title>
</head>
<body>
<script>
let person={firstname:"Prince", lastname:"Varshney", age:23, haircolour:"Black"};
document.write(person["firstname"]);
document.write("<br>");
document.write(person["age"]);
</script>
</body>
</html>
The output of the above example is given below -
Prince
23
|
[
{
"code": null,
"e": 1335,
"s": 1062,
"text": "A data type is known as a composite data type when it represents a number of similar or different data under a single declaration of variable i.e., a data type that has multiple values grouped together. There are mainly three types of composite data types named as below −"
},
{
"code": null,
"e": 1342,
"s": 1335,
"text": "Object"
},
{
"code": null,
"e": 1349,
"s": 1342,
"text": "Object"
},
{
"code": null,
"e": 1355,
"s": 1349,
"text": "Array"
},
{
"code": null,
"e": 1361,
"s": 1355,
"text": "Array"
},
{
"code": null,
"e": 1370,
"s": 1361,
"text": "Function"
},
{
"code": null,
"e": 1379,
"s": 1370,
"text": "Function"
},
{
"code": null,
"e": 1463,
"s": 1379,
"text": "In this article, we will discuss the first type of composite data type i.e. object."
},
{
"code": null,
"e": 1667,
"s": 1463,
"text": "An object is a collection of properties i.e, an object can store the properties of anything in the key-value pairs. An object in javascript has keys and each key has its own value as shown in the example"
},
{
"code": null,
"e": 1749,
"s": 1667,
"text": "let person={firstname:\"Prince\", lastname:\"Varshney\", age:23, haircolour:\"Black\"};"
},
{
"code": null,
"e": 2323,
"s": 1749,
"text": "An object is used whenever we want to store more than one value for a single variable like in the above example we have stored the firstname, lastname, age, and haircolour of a person in a single variable named ‘person’. The property of an object can be of any data type i.e., it can be string, number, Boolean or it can be an array as well. Due to the specialty of having data of any data type the objects are very useful in processing large amounts of data. We can use an object to store the whole data of a batch of students, people of a society, or people in a country."
},
{
"code": null,
"e": 2407,
"s": 2323,
"text": "You can try to run the following code to learn how to declare objects in JavaScript"
},
{
"code": null,
"e": 2722,
"s": 2407,
"text": "<html>\n <head>\n <title>Javascript objects</title>\n </head>\n <body>\n <script>\n let person={firstname:\"Shivi\", lastname:\"Singh\", age:23, haircolour:\"Black\"};\n for (i in person){\n document.write(i + \": \" + person[i] + \"<br />\");\n }\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2763,
"s": 2722,
"text": "This will produce the following result -"
},
{
"code": null,
"e": 2822,
"s": 2763,
"text": "firstname: Shivi\nlastname: Singh\nage: 23\nhaircolour: Black"
},
{
"code": null,
"e": 2987,
"s": 2822,
"text": "We can also create an empty JavaScript object and add properties in the object later. To create an empty object, we have to use the “new” keyword like shown below −"
},
{
"code": null,
"e": 3378,
"s": 2987,
"text": "<html>\n <head>\n <title>Javascript objects</title>\n </head>\n <body>\n <script>\n let person=new Object();\n person.firstname=\"Shivi\";\n person.lastname=\"Singh\";\n person.age=23;\n person.haircolour=\"Black\";\n for (i in person){\n document.write(i + \": \" + person[i] + \"<br />\");\n }\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3419,
"s": 3378,
"text": "This will produce the following result -"
},
{
"code": null,
"e": 3478,
"s": 3419,
"text": "firstname: Shivi\nlastname: Singh\nage: 23\nhaircolour: Black"
},
{
"code": null,
"e": 3651,
"s": 3478,
"text": "Each and every value of an object can be fetched so that we can use them further whenever we need them in our code further. The object values can be accessed by 2 methods −"
},
{
"code": null,
"e": 3738,
"s": 3651,
"text": "We can access the object value using a dot(.) operator as shown in the below example −"
},
{
"code": null,
"e": 4070,
"s": 3738,
"text": "<html>\n <head>\n <title>Javascript objects</title>\n </head>\n <body>\n <script>\n let person={firstname:\"Prince\", lastname:\"Varshney\", age:23, haircolour:\"Black\"};\n document.write(person.firstname);\n document.write(\"<br>\");\n document.write(person.age);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4119,
"s": 4070,
"text": "The output of the above example is given below −"
},
{
"code": null,
"e": 4129,
"s": 4119,
"text": "Prince\n23"
},
{
"code": null,
"e": 4223,
"s": 4129,
"text": "We can also access the object value using a square bracket [] as shown in the below example −"
},
{
"code": null,
"e": 4561,
"s": 4223,
"text": "<html>\n <head>\n <title>Javascript objects</title>\n </head>\n <body>\n <script>\n let person={firstname:\"Prince\", lastname:\"Varshney\", age:23, haircolour:\"Black\"};\n document.write(person[\"firstname\"]);\n document.write(\"<br>\");\n document.write(person[\"age\"]);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4610,
"s": 4561,
"text": "The output of the above example is given below -"
},
{
"code": null,
"e": 4620,
"s": 4610,
"text": "Prince\n23"
}
] |
Difference between Private and Public IP addresses
|
Private IP Address and Public IP Address are used to uniquely identify a machine on the internet. Private IP address is used with a local network and public IP address is used outside the network. Public IP address is provided by ISP, Internet Service Provider.
Following are the important differences between Private IP Address and Public IP Address.
10.0.0.0 – 10.255.255.255,
172.16.0.0 – 172.31.255.255,
192.168.0.0 – 192.168.255.255
|
[
{
"code": null,
"e": 1324,
"s": 1062,
"text": "Private IP Address and Public IP Address are used to uniquely identify a machine on the internet. Private IP address is used with a local network and public IP address is used outside the network. Public IP address is provided by ISP, Internet Service Provider."
},
{
"code": null,
"e": 1414,
"s": 1324,
"text": "Following are the important differences between Private IP Address and Public IP Address."
},
{
"code": null,
"e": 1500,
"s": 1414,
"text": "10.0.0.0 – 10.255.255.255,\n172.16.0.0 – 172.31.255.255,\n192.168.0.0 – 192.168.255.255"
}
] |
Cassandra - Create Data
|
You can insert data into the columns of a row in a table using the command INSERT. Given below is the syntax for creating data in a table.
INSERT INTO <tablename>
(<column1 name>, <column2 name>....)
VALUES (<value1>, <value2>....)
USING <option>
Let us assume there is a table called emp with columns (emp_id, emp_name, emp_city, emp_phone, emp_sal) and you have to insert the following data into the emp table.
Use the commands given below to fill the table with required data.
cqlsh:tutorialspoint> INSERT INTO emp (emp_id, emp_name, emp_city,
emp_phone, emp_sal) VALUES(1,'ram', 'Hyderabad', 9848022338, 50000);
cqlsh:tutorialspoint> INSERT INTO emp (emp_id, emp_name, emp_city,
emp_phone, emp_sal) VALUES(2,'robin', 'Hyderabad', 9848022339, 40000);
cqlsh:tutorialspoint> INSERT INTO emp (emp_id, emp_name, emp_city,
emp_phone, emp_sal) VALUES(3,'rahman', 'Chennai', 9848022330, 45000);
After inserting data, use SELECT statement to verify whether the data has been inserted or not. If you verify the emp table using SELECT statement, it will give you the following output.
cqlsh:tutorialspoint> SELECT * FROM emp;
emp_id | emp_city | emp_name | emp_phone | emp_sal
--------+-----------+----------+------------+---------
1 | Hyderabad | ram | 9848022338 | 50000
2 | Hyderabad | robin | 9848022339 | 40000
3 | Chennai | rahman | 9848022330 | 45000
(3 rows)
Here you can observe the table has populated with the data we inserted.
You can create data in a table using the execute() method of Session class. Follow the steps given below to create data in a table using java API.
Create an instance of Cluster.builder class of com.datastax.driver.core package as shown below.
//Creating Cluster.Builder object
Cluster.Builder builder1 = Cluster.builder();
Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder.
//Adding contact point to the Cluster.Builder object
Cluster.Builder builder2 = build.addContactPoint("127.0.0.1");
Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object.
//Building a cluster
Cluster cluster = builder.build();
You can build a cluster object using a single line of code as shown below.
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Create an instance of Session object using the connect() method of Cluster class as shown below.
Session session = cluster.connect( );
This method creates a new session and initializes it. If you already have a keyspace, then you can set it to the existing one by passing the KeySpace name in string format to this method as shown below.
Session session = cluster.connect(“ Your keyspace name ” );
Here we are using the KeySpace called tp. Therefore, create the session object as shown below.
Session session = cluster.connect(“ tp” );
You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh.
In the following example, we are inserting data in a table called emp. You have to store the query in a string variable and pass it to the execute() method as shown below.
String query1 = “INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)
VALUES(1,'ram', 'Hyderabad', 9848022338, 50000);” ;
String query2 = “INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)
VALUES(2,'robin', 'Hyderabad', 9848022339, 40000);” ;
String query3 = “INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)
VALUES(3,'rahman', 'Chennai', 9848022330, 45000);” ;
session.execute(query1);
session.execute(query2);
session.execute(query3);
Given below is the complete program to insert data into a table in Cassandra using Java API.
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
public class Create_Data {
public static void main(String args[]){
//queries
String query1 = "INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)"
+ " VALUES(1,'ram', 'Hyderabad', 9848022338, 50000);" ;
String query2 = "INSERT INTO emp (emp_id, emp_name, emp_city,
emp_phone, emp_sal)"
+ " VALUES(2,'robin', 'Hyderabad', 9848022339, 40000);" ;
String query3 = "INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)"
+ " VALUES(3,'rahman', 'Chennai', 9848022330, 45000);" ;
//Creating Cluster object
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
//Creating Session object
Session session = cluster.connect("tp");
//Executing the query
session.execute(query1);
session.execute(query2);
session.execute(query3);
System.out.println("Data created");
}
}
Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below.
$javac Create_Data.java
$java Create_Data
Under normal conditions, it should produce the following output −
Data created
27 Lectures
2 hours
Navdeep Kaur
34 Lectures
1.5 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2426,
"s": 2287,
"text": "You can insert data into the columns of a row in a table using the command INSERT. Given below is the syntax for creating data in a table."
},
{
"code": null,
"e": 2535,
"s": 2426,
"text": "INSERT INTO <tablename>\n(<column1 name>, <column2 name>....)\nVALUES (<value1>, <value2>....)\nUSING <option>\n"
},
{
"code": null,
"e": 2701,
"s": 2535,
"text": "Let us assume there is a table called emp with columns (emp_id, emp_name, emp_city, emp_phone, emp_sal) and you have to insert the following data into the emp table."
},
{
"code": null,
"e": 2768,
"s": 2701,
"text": "Use the commands given below to fill the table with required data."
},
{
"code": null,
"e": 3191,
"s": 2768,
"text": "cqlsh:tutorialspoint> INSERT INTO emp (emp_id, emp_name, emp_city,\n emp_phone, emp_sal) VALUES(1,'ram', 'Hyderabad', 9848022338, 50000);\n\ncqlsh:tutorialspoint> INSERT INTO emp (emp_id, emp_name, emp_city,\n emp_phone, emp_sal) VALUES(2,'robin', 'Hyderabad', 9848022339, 40000);\n\ncqlsh:tutorialspoint> INSERT INTO emp (emp_id, emp_name, emp_city,\n emp_phone, emp_sal) VALUES(3,'rahman', 'Chennai', 9848022330, 45000);\n"
},
{
"code": null,
"e": 3378,
"s": 3191,
"text": "After inserting data, use SELECT statement to verify whether the data has been inserted or not. If you verify the emp table using SELECT statement, it will give you the following output."
},
{
"code": null,
"e": 3697,
"s": 3378,
"text": "cqlsh:tutorialspoint> SELECT * FROM emp;\n\n emp_id | emp_city | emp_name | emp_phone | emp_sal\n--------+-----------+----------+------------+---------\n 1 | Hyderabad | ram | 9848022338 | 50000\n 2 | Hyderabad | robin | 9848022339 | 40000\n 3 | Chennai | rahman | 9848022330 | 45000\n \n(3 rows)\n"
},
{
"code": null,
"e": 3769,
"s": 3697,
"text": "Here you can observe the table has populated with the data we inserted."
},
{
"code": null,
"e": 3916,
"s": 3769,
"text": "You can create data in a table using the execute() method of Session class. Follow the steps given below to create data in a table using java API."
},
{
"code": null,
"e": 4012,
"s": 3916,
"text": "Create an instance of Cluster.builder class of com.datastax.driver.core package as shown below."
},
{
"code": null,
"e": 4093,
"s": 4012,
"text": "//Creating Cluster.Builder object\nCluster.Builder builder1 = Cluster.builder();\n"
},
{
"code": null,
"e": 4237,
"s": 4093,
"text": "Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder."
},
{
"code": null,
"e": 4354,
"s": 4237,
"text": "//Adding contact point to the Cluster.Builder object\nCluster.Builder builder2 = build.addContactPoint(\"127.0.0.1\");\n"
},
{
"code": null,
"e": 4539,
"s": 4354,
"text": "Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object."
},
{
"code": null,
"e": 4596,
"s": 4539,
"text": "//Building a cluster\nCluster cluster = builder.build();\n"
},
{
"code": null,
"e": 4671,
"s": 4596,
"text": "You can build a cluster object using a single line of code as shown below."
},
{
"code": null,
"e": 4746,
"s": 4671,
"text": "Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n"
},
{
"code": null,
"e": 4843,
"s": 4746,
"text": "Create an instance of Session object using the connect() method of Cluster class as shown below."
},
{
"code": null,
"e": 4882,
"s": 4843,
"text": "Session session = cluster.connect( );\n"
},
{
"code": null,
"e": 5085,
"s": 4882,
"text": "This method creates a new session and initializes it. If you already have a keyspace, then you can set it to the existing one by passing the KeySpace name in string format to this method as shown below."
},
{
"code": null,
"e": 5146,
"s": 5085,
"text": "Session session = cluster.connect(“ Your keyspace name ” );\n"
},
{
"code": null,
"e": 5241,
"s": 5146,
"text": "Here we are using the KeySpace called tp. Therefore, create the session object as shown below."
},
{
"code": null,
"e": 5285,
"s": 5241,
"text": "Session session = cluster.connect(“ tp” );\n"
},
{
"code": null,
"e": 5534,
"s": 5285,
"text": "You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh."
},
{
"code": null,
"e": 5706,
"s": 5534,
"text": "In the following example, we are inserting data in a table called emp. You have to store the query in a string variable and pass it to the execute() method as shown below."
},
{
"code": null,
"e": 6203,
"s": 5706,
"text": "String query1 = “INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)\n VALUES(1,'ram', 'Hyderabad', 9848022338, 50000);” ;\n \nString query2 = “INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)\n VALUES(2,'robin', 'Hyderabad', 9848022339, 40000);” ;\n \nString query3 = “INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)\n VALUES(3,'rahman', 'Chennai', 9848022330, 45000);” ;\n \nsession.execute(query1);\nsession.execute(query2);\nsession.execute(query3); \n"
},
{
"code": null,
"e": 6296,
"s": 6203,
"text": "Given below is the complete program to insert data into a table in Cassandra using Java API."
},
{
"code": null,
"e": 7419,
"s": 6296,
"text": "import com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Session;\n\npublic class Create_Data {\n\n public static void main(String args[]){\n\n //queries\n String query1 = \"INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)\"\n\t\t\n + \" VALUES(1,'ram', 'Hyderabad', 9848022338, 50000);\" ;\n \n String query2 = \"INSERT INTO emp (emp_id, emp_name, emp_city,\n emp_phone, emp_sal)\"\n \n + \" VALUES(2,'robin', 'Hyderabad', 9848022339, 40000);\" ;\n \n String query3 = \"INSERT INTO emp (emp_id, emp_name, emp_city, emp_phone, emp_sal)\"\n \n + \" VALUES(3,'rahman', 'Chennai', 9848022330, 45000);\" ;\n\n //Creating Cluster object\n Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n \n //Creating Session object\n Session session = cluster.connect(\"tp\");\n \n //Executing the query\n session.execute(query1);\n \n session.execute(query2);\n \n session.execute(query3);\n \n System.out.println(\"Data created\");\n }\n}"
},
{
"code": null,
"e": 7571,
"s": 7419,
"text": "Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below."
},
{
"code": null,
"e": 7614,
"s": 7571,
"text": "$javac Create_Data.java\n$java Create_Data\n"
},
{
"code": null,
"e": 7680,
"s": 7614,
"text": "Under normal conditions, it should produce the following output −"
},
{
"code": null,
"e": 7694,
"s": 7680,
"text": "Data created\n"
},
{
"code": null,
"e": 7727,
"s": 7694,
"text": "\n 27 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7741,
"s": 7727,
"text": " Navdeep Kaur"
},
{
"code": null,
"e": 7776,
"s": 7741,
"text": "\n 34 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7794,
"s": 7776,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7801,
"s": 7794,
"text": " Print"
},
{
"code": null,
"e": 7812,
"s": 7801,
"text": " Add Notes"
}
] |
CICS - DELETE
|
DELETE command is used to delete a record that is present in a file. Prior to this command, the record must be read with a READ UPDATE command. The parameters are same as described before. The syntax of Delete command is as follows −
EXEC CICS DELETE
FILE('name')
END-EXEC.
Following is the syntax to delete a record directly without reading it with Update option −
EXEC CICS DELETE
FILE('name')
RIDFLD(data-value)
END-EXEC.
Following is the example for Group Delete. This can be done using Generic option, where all the records that satisfy the generic criteria will be deleted. NUMREC will hold the number of records deleted. The field mentioned here should be a S9(4) comp.
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-STD-REC-LEN PIC S9(4) COMP.
01 WS-STD-KEY-LEN PIC S9(4) COMP.
01 WS-STD-REC-KEY PIC 9(3).
01 WS-STD-REC PIC X(70).
01 WS-NUM-REC-DEL PIC S9(4).
PROCEDURE DIVISION.
MOVE '11' TO WS-STD-REC-KEY.
MOVE 2 TO WS-STD-KEY-LEN.
EXEC CICS READ
FILE ('FL001')
RIDFLD (WS-STD-REC-KEY)
KEYLENGTH (WS-STD-KEY-LEN)
GENERIC
NUMREC (WS-NUM-REC-DEL)
END-EXEC.
The following table shows the list of exceptions that arise during a DELETE statement −
NOTOPEN
File is not open.
NOTFND
Record that is being searched doesn't exist in the dataset (DELETE with RIDFLD).
NOTAUTH
If the user does not have enough permissions to use the file.
INVREQ
Rewrite without prior READ with UPDATE.
FILENOTFOUND
File entry is not made in FCT.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2160,
"s": 1926,
"text": "DELETE command is used to delete a record that is present in a file. Prior to this command, the record must be read with a READ UPDATE command. The parameters are same as described before. The syntax of Delete command is as follows −"
},
{
"code": null,
"e": 2204,
"s": 2160,
"text": "EXEC CICS DELETE\n FILE('name')\nEND-EXEC.\n"
},
{
"code": null,
"e": 2296,
"s": 2204,
"text": "Following is the syntax to delete a record directly without reading it with Update option −"
},
{
"code": null,
"e": 2361,
"s": 2296,
"text": "EXEC CICS DELETE\n FILE('name')\n RIDFLD(data-value)\nEND-EXEC."
},
{
"code": null,
"e": 2613,
"s": 2361,
"text": "Following is the example for Group Delete. This can be done using Generic option, where all the records that satisfy the generic criteria will be deleted. NUMREC will hold the number of records deleted. The field mentioned here should be a S9(4) comp."
},
{
"code": null,
"e": 3183,
"s": 2613,
"text": "IDENTIFICATION DIVISION. \nPROGRAM-ID. HELLO. \nDATA DIVISION. \nWORKING-STORAGE SECTION.\n01 WS-STD-REC-LEN PIC S9(4) COMP.\n01 WS-STD-KEY-LEN PIC S9(4) COMP.\n01 WS-STD-REC-KEY PIC 9(3).\n01 WS-STD-REC PIC X(70).\n01 WS-NUM-REC-DEL PIC S9(4).\nPROCEDURE DIVISION.\nMOVE '11' TO WS-STD-REC-KEY.\nMOVE 2 TO WS-STD-KEY-LEN.\nEXEC CICS READ\n FILE ('FL001')\n RIDFLD (WS-STD-REC-KEY)\n KEYLENGTH (WS-STD-KEY-LEN)\n GENERIC\n NUMREC (WS-NUM-REC-DEL)\nEND-EXEC."
},
{
"code": null,
"e": 3271,
"s": 3183,
"text": "The following table shows the list of exceptions that arise during a DELETE statement −"
},
{
"code": null,
"e": 3279,
"s": 3271,
"text": "NOTOPEN"
},
{
"code": null,
"e": 3297,
"s": 3279,
"text": "File is not open."
},
{
"code": null,
"e": 3304,
"s": 3297,
"text": "NOTFND"
},
{
"code": null,
"e": 3385,
"s": 3304,
"text": "Record that is being searched doesn't exist in the dataset (DELETE with RIDFLD)."
},
{
"code": null,
"e": 3393,
"s": 3385,
"text": "NOTAUTH"
},
{
"code": null,
"e": 3455,
"s": 3393,
"text": "If the user does not have enough permissions to use the file."
},
{
"code": null,
"e": 3462,
"s": 3455,
"text": "INVREQ"
},
{
"code": null,
"e": 3502,
"s": 3462,
"text": "Rewrite without prior READ with UPDATE."
},
{
"code": null,
"e": 3515,
"s": 3502,
"text": "FILENOTFOUND"
},
{
"code": null,
"e": 3546,
"s": 3515,
"text": "File entry is not made in FCT."
},
{
"code": null,
"e": 3553,
"s": 3546,
"text": " Print"
},
{
"code": null,
"e": 3564,
"s": 3553,
"text": " Add Notes"
}
] |
VBScript Do..While statement
|
A Do..While loop is used when we want to repeat a set of statements as long as the condition is true. The Condition may be checked at the beginning of the loop or at the end of the loop.
The syntax of a Do..While loop in VBScript is −
Do While condition
[statement 1]
[statement 2]
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]
Loop
The below example uses Do..while loop to check the condition at the beginning of the loop. The statements inside the loop are executed only if the condition becomes True.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Do While i < 5
i = i + 1
Document.write("The value of i is : " & i)
Document.write("<br></br>")
Loop
</script>
</body>
</html>
When the above code is executed, it prints the following output on the console.
The value of i is : 1
The value of i is : 2
The value of i is : 3
The value of i is : 4
The value of i is : 5
There is also an alternate Syntax for Do..while loop which checks the condition at the end of the loop. The Major difference between these two syntax is explained below with an example.
Do
[statement 1]
[statement 2]
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]
Loop While condition
The below example uses Do..while loop to check the condition at the end of the loop. The Statements inside the loop are executed atleast once even if the condition is False.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
i = 10
Do
i = i + 1
Document.write("The value of i is : " & i)
Document.write("<br></br>")
Loop While i<3 'Condition is false.Hence loop is executed once.
</script>
</body>
</html>
When the above code is executed, it prints the following output in the console.
The value of i is : 11
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2267,
"s": 2080,
"text": "A Do..While loop is used when we want to repeat a set of statements as long as the condition is true. The Condition may be checked at the beginning of the loop or at the end of the loop."
},
{
"code": null,
"e": 2315,
"s": 2267,
"text": "The syntax of a Do..While loop in VBScript is −"
},
{
"code": null,
"e": 2480,
"s": 2315,
"text": "Do While condition\n [statement 1]\n [statement 2]\n ...\n [statement n]\n [Exit Do]\n [statement 1]\n [statement 2]\n ...\n [statement n]\nLoop \n"
},
{
"code": null,
"e": 2651,
"s": 2480,
"text": "The below example uses Do..while loop to check the condition at the beginning of the loop. The statements inside the loop are executed only if the condition becomes True."
},
{
"code": null,
"e": 2951,
"s": 2651,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\"> \n Do While i < 5\n i = i + 1\n Document.write(\"The value of i is : \" & i)\n Document.write(\"<br></br>\")\n Loop \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3031,
"s": 2951,
"text": "When the above code is executed, it prints the following output on the console."
},
{
"code": null,
"e": 3146,
"s": 3031,
"text": "The value of i is : 1\n\nThe value of i is : 2\n\nThe value of i is : 3\n\nThe value of i is : 4\n\nThe value of i is : 5\n"
},
{
"code": null,
"e": 3332,
"s": 3146,
"text": "There is also an alternate Syntax for Do..while loop which checks the condition at the end of the loop. The Major difference between these two syntax is explained below with an example."
},
{
"code": null,
"e": 3487,
"s": 3332,
"text": "Do \n [statement 1]\n [statement 2]\n ...\n [statement n]\n [Exit Do]\n [statement 1]\n [statement 2]\n ...\n [statement n]\nLoop While condition\n"
},
{
"code": null,
"e": 3661,
"s": 3487,
"text": "The below example uses Do..while loop to check the condition at the end of the loop. The Statements inside the loop are executed atleast once even if the condition is False."
},
{
"code": null,
"e": 4033,
"s": 3661,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\"> \n i = 10 \n Do \n i = i + 1\n Document.write(\"The value of i is : \" & i)\n Document.write(\"<br></br>\")\n Loop While i<3 'Condition is false.Hence loop is executed once.\n \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4113,
"s": 4033,
"text": "When the above code is executed, it prints the following output in the console."
},
{
"code": null,
"e": 4137,
"s": 4113,
"text": "The value of i is : 11\n"
},
{
"code": null,
"e": 4170,
"s": 4137,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4187,
"s": 4170,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4194,
"s": 4187,
"text": " Print"
},
{
"code": null,
"e": 4205,
"s": 4194,
"text": " Add Notes"
}
] |
Sort in specific order | Practice | GeeksforGeeks
|
Given an array A of positive integers. Your task is to sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order.
Example 1:
Input:
N = 7
Arr = {1, 2, 3, 5, 4, 7, 10}
Output:
7 5 3 1 2 4 10
Explanation:
Array elements 7 5 3 1 are odd
and sorted in descending order,
whereas 2 4 10 are even numbers
and sorted in ascending order.
Example 2:
Input:
N = 7
Arr = {0, 4, 5, 3, 7, 2, 1}
Output:
7 5 3 1 0 2 4
Your Task:
You don't need to read input or print anything. Your task is to complete the function leftIndex() which takes the array Arr[] and its size N as inputs and modifies the array Arr[].
Expected Time Complexity: O(N. Log(N))
Expected Auxiliary Space: O(N)
Constraints:
1 <= N <= 106
0 <= Ai <= 1018
0
codewithshoaib192 weeks ago
public void sortIt(long arr[], long n) { //code here. int oddn=0; int evenn=0; for(long i:arr){ if(i%2!=0){ oddn++; } else{ evenn++; } } long[]odd=new long[oddn]; long[]even=new long[evenn]; int j=0; int k=0; for(int i=0;i<n;i++){ if(arr[i]%2!=0){ odd[j]=arr[i]; j++; } } for(int i=0;i<n;i++){ if(arr[i]%2==0){ even[k]=arr[i]; k++; } } Arrays.sort(odd); Arrays.sort(even); reverse(odd); for(int i=0;i<odd.length;i++){ arr[i]=odd[i]; } for(int i=0;i<even.length;i++){ arr[(int) oddn+i]=even[i]; } } public static void reverse(long[] arr ){ int s=0, e=arr.length-1; while(s<=e){ swap(arr,s,e); s++; e--; } } public static void swap(long[] arr,int s,int e ){ long temp=arr[s]; arr[s]=arr[e]; arr[e]=temp; }
0
codewithshoaib192 weeks ago
public void sortIt(long arr[], long n) { //code here. int oddn=0; int evenn=0; for(long i:arr){ if(i%2!=0){ oddn++; } else{ evenn++; } } long[]odd=new long[oddn]; long[]even=new long[evenn]; int j=0; int k=0; for(int i=0;i<n;i++){ if(arr[i]%2!=0){ odd[j]=arr[i]; j++; } } for(int i=0;i<n;i++){ if(arr[i]%2==0){ even[k]=arr[i]; k++; } } Arrays.sort(odd); Arrays.sort(even); reverse(odd); for(int i=0;i<odd.length;i++){ arr[i]=odd[i]; } for(int i=0;i<even.length;i++){ arr[(int) oddn+i]=even[i]; } // System.out.println(Arrays.toString(odd)); // System.out.println(Arrays.toString(even)); // System.out.println(Arrays.toString(arr)); } public static void reverse(long[] arr ){ int s=0, e=arr.length-1; while(s<=e){ swap(arr,s,e); s++; e--; } } public static void swap(long[] arr,int s,int e ){ long temp=arr[s]; arr[s]=arr[e]; arr[e]=temp; }
0
mayank20212 weeks ago
C++ : 0.5/2.26 : without using any extra arrayvoid sortIt(long long arr[], long long n) { int i=0, j=n-1 ; while(i<j) { if(!(arr[i]&1) && (arr[j]&1) ) swap(arr[i], arr[j]), i++, j--; if(arr[i]&1) i++ ; if(!(arr[j]&1)) j--; } if(arr[i]&1) { sort(arr+i+1, arr+n); sort(arr, arr+i+1); reverse(arr, arr+i+1); } else { sort(arr, arr+i); sort(arr+i, arr+n); reverse(arr, arr+i); } }
0
yesbro2 weeks ago
class Solution
{
public void sortIt(long arr[], long n)
{
//code here.
ArrayList<Long> array1 = new ArrayList<Long>();
ArrayList<Long> array2 = new ArrayList<Long>();
Arrays.sort(arr);
for(int i=0;i<n;i++){
if(arr[i] % 2 == 0){
array1.add(arr[i]);
}
else{
array2.add(arr[i]);
}
}
int x = 0;
for(int i=array2.size()-1;i>=0;i--){
arr[x++] = array2.get(i);
}
for(int i=0;i<array1.size();i++){
arr[x++] = array1.get(i);
}
}
}
0
nithinkirthick3 weeks ago
Python 1.0/9.3
def sortIt(self, arr, n): #code here. odd=[i for i in arr if i%2>0] odd.sort(reverse=True) even=[i for i in arr if i%2==0] even.sort() for i ,v in enumerate(list(odd+even)): arr[i]=v
0
arvind16yadav4 weeks ago
/*JAVA CODE */
class Solution{ public void sortIt(long arr[], long n) { //code here. Arrays.sort(arr); long brr[] = new long[(int)n]; long left_counter = 0; long right_counter = n-1; for(long i = n-1; i>=0; i--){ if(arr[(int)i] % 2 == 0){ brr[(int)right_counter--] = arr[(int)i]; } else{ brr[(int)left_counter++] = arr[(int)i]; } } for(long i = 0; i < n; i++){ arr[(int)i] = brr[(int)i]; } }}
0
hasnainraza1998hr1 month ago
C++
void sortIt(long long arr[], long long n) { long long temp[n]; sort(arr,arr+n); int j = 0,k = n-1; for(int i=n-1;i>=0;i--){ if(arr[i]%2==0){ temp[k--]=arr[i]; } else{ temp[j++]=arr[i]; } } for(int i=0;i<n;i++){ arr[i]=temp[i]; } }
0
dangrio2 months ago
static bool compareOddEven(int a, int b){ if(a%2 == 0 && b%2==0) return a<b; if(a%2 != 0 && b%2 != 0) return b<a; if( a%2 != 0) return true; else return false; }
void sortIt(long long arr[], long long n) {sort(arr,arr+n,compareOddEven); }
0
dangrio2 months ago
Time Taken = 0.5s
for(int i=0;i<n;i++) if(arr[i]%2) arr[i] = (-1)*arr[i]; sort(arr,arr+n); int i = 0; while(arr[i]<0){ arr[i] = (-1)*arr[i]; i++; }
0
dangrio2 months ago
Time Taken = 0.5s
long long left = 0, right = n-1, k=0; while(left<right){ //find the first even number while(arr[left]%2 != 0){ left++, k++; } //Finding the odd number from the right side while(arr[right]%2 == 0) right--; if(left<right) swap(arr[left], arr[right]); } sort(arr,arr+k,greater<long long>()); sort(arr+k,arr+n);
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": 461,
"s": 238,
"text": "Given an array A of positive integers. Your task is to sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order."
},
{
"code": null,
"e": 474,
"s": 463,
"text": "Example 1:"
},
{
"code": null,
"e": 678,
"s": 474,
"text": "Input:\nN = 7\nArr = {1, 2, 3, 5, 4, 7, 10}\nOutput:\n7 5 3 1 2 4 10\nExplanation:\nArray elements 7 5 3 1 are odd\nand sorted in descending order,\nwhereas 2 4 10 are even numbers\nand sorted in ascending order."
},
{
"code": null,
"e": 691,
"s": 680,
"text": "Example 2:"
},
{
"code": null,
"e": 754,
"s": 691,
"text": "Input:\nN = 7\nArr = {0, 4, 5, 3, 7, 2, 1}\nOutput:\n7 5 3 1 0 2 4"
},
{
"code": null,
"e": 950,
"s": 756,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function leftIndex() which takes the array Arr[] and its size N as inputs and modifies the array Arr[]."
},
{
"code": null,
"e": 1021,
"s": 950,
"text": "\nExpected Time Complexity: O(N. Log(N))\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1066,
"s": 1023,
"text": "Constraints:\n1 <= N <= 106\n0 <= Ai <= 1018"
},
{
"code": null,
"e": 1068,
"s": 1066,
"text": "0"
},
{
"code": null,
"e": 1096,
"s": 1068,
"text": "codewithshoaib192 weeks ago"
},
{
"code": null,
"e": 2182,
"s": 1096,
"text": "public void sortIt(long arr[], long n) { //code here. int oddn=0; int evenn=0; for(long i:arr){ if(i%2!=0){ oddn++; } else{ evenn++; } } long[]odd=new long[oddn]; long[]even=new long[evenn]; int j=0; int k=0; for(int i=0;i<n;i++){ if(arr[i]%2!=0){ odd[j]=arr[i]; j++; } } for(int i=0;i<n;i++){ if(arr[i]%2==0){ even[k]=arr[i]; k++; } } Arrays.sort(odd); Arrays.sort(even); reverse(odd); for(int i=0;i<odd.length;i++){ arr[i]=odd[i]; } for(int i=0;i<even.length;i++){ arr[(int) oddn+i]=even[i]; } } public static void reverse(long[] arr ){ int s=0, e=arr.length-1; while(s<=e){ swap(arr,s,e); s++; e--; } } public static void swap(long[] arr,int s,int e ){ long temp=arr[s]; arr[s]=arr[e]; arr[e]=temp; }"
},
{
"code": null,
"e": 2184,
"s": 2182,
"text": "0"
},
{
"code": null,
"e": 2212,
"s": 2184,
"text": "codewithshoaib192 weeks ago"
},
{
"code": null,
"e": 3454,
"s": 2212,
"text": " public void sortIt(long arr[], long n) { //code here. int oddn=0; int evenn=0; for(long i:arr){ if(i%2!=0){ oddn++; } else{ evenn++; } } long[]odd=new long[oddn]; long[]even=new long[evenn]; int j=0; int k=0; for(int i=0;i<n;i++){ if(arr[i]%2!=0){ odd[j]=arr[i]; j++; } } for(int i=0;i<n;i++){ if(arr[i]%2==0){ even[k]=arr[i]; k++; } } Arrays.sort(odd); Arrays.sort(even); reverse(odd); for(int i=0;i<odd.length;i++){ arr[i]=odd[i]; } for(int i=0;i<even.length;i++){ arr[(int) oddn+i]=even[i]; } // System.out.println(Arrays.toString(odd)); // System.out.println(Arrays.toString(even)); // System.out.println(Arrays.toString(arr)); } public static void reverse(long[] arr ){ int s=0, e=arr.length-1; while(s<=e){ swap(arr,s,e); s++; e--; } } public static void swap(long[] arr,int s,int e ){ long temp=arr[s]; arr[s]=arr[e]; arr[e]=temp; }"
},
{
"code": null,
"e": 3456,
"s": 3454,
"text": "0"
},
{
"code": null,
"e": 3478,
"s": 3456,
"text": "mayank20212 weeks ago"
},
{
"code": null,
"e": 4074,
"s": 3478,
"text": "C++ : 0.5/2.26 : without using any extra arrayvoid sortIt(long long arr[], long long n) { int i=0, j=n-1 ; while(i<j) { if(!(arr[i]&1) && (arr[j]&1) ) swap(arr[i], arr[j]), i++, j--; if(arr[i]&1) i++ ; if(!(arr[j]&1)) j--; } if(arr[i]&1) { sort(arr+i+1, arr+n); sort(arr, arr+i+1); reverse(arr, arr+i+1); } else { sort(arr, arr+i); sort(arr+i, arr+n); reverse(arr, arr+i); } }"
},
{
"code": null,
"e": 4076,
"s": 4074,
"text": "0"
},
{
"code": null,
"e": 4094,
"s": 4076,
"text": "yesbro2 weeks ago"
},
{
"code": null,
"e": 4725,
"s": 4094,
"text": "class Solution\n{\n \n public void sortIt(long arr[], long n)\n {\n //code here.\n ArrayList<Long> array1 = new ArrayList<Long>();\n ArrayList<Long> array2 = new ArrayList<Long>();\n Arrays.sort(arr);\n for(int i=0;i<n;i++){\n if(arr[i] % 2 == 0){\n array1.add(arr[i]);\n }\n else{\n array2.add(arr[i]);\n }\n }\n int x = 0;\n for(int i=array2.size()-1;i>=0;i--){\n arr[x++] = array2.get(i);\n }\n for(int i=0;i<array1.size();i++){\n arr[x++] = array1.get(i);\n }\n }\n}"
},
{
"code": null,
"e": 4727,
"s": 4725,
"text": "0"
},
{
"code": null,
"e": 4753,
"s": 4727,
"text": "nithinkirthick3 weeks ago"
},
{
"code": null,
"e": 4768,
"s": 4753,
"text": "Python 1.0/9.3"
},
{
"code": null,
"e": 5001,
"s": 4768,
"text": " def sortIt(self, arr, n): #code here. odd=[i for i in arr if i%2>0] odd.sort(reverse=True) even=[i for i in arr if i%2==0] even.sort() for i ,v in enumerate(list(odd+even)): arr[i]=v"
},
{
"code": null,
"e": 5003,
"s": 5001,
"text": "0"
},
{
"code": null,
"e": 5028,
"s": 5003,
"text": "arvind16yadav4 weeks ago"
},
{
"code": null,
"e": 5043,
"s": 5028,
"text": "/*JAVA CODE */"
},
{
"code": null,
"e": 5615,
"s": 5043,
"text": "class Solution{ public void sortIt(long arr[], long n) { //code here. Arrays.sort(arr); long brr[] = new long[(int)n]; long left_counter = 0; long right_counter = n-1; for(long i = n-1; i>=0; i--){ if(arr[(int)i] % 2 == 0){ brr[(int)right_counter--] = arr[(int)i]; } else{ brr[(int)left_counter++] = arr[(int)i]; } } for(long i = 0; i < n; i++){ arr[(int)i] = brr[(int)i]; } }}"
},
{
"code": null,
"e": 5617,
"s": 5615,
"text": "0"
},
{
"code": null,
"e": 5646,
"s": 5617,
"text": "hasnainraza1998hr1 month ago"
},
{
"code": null,
"e": 5650,
"s": 5646,
"text": "C++"
},
{
"code": null,
"e": 6005,
"s": 5650,
"text": "void sortIt(long long arr[], long long n) { long long temp[n]; sort(arr,arr+n); int j = 0,k = n-1; for(int i=n-1;i>=0;i--){ if(arr[i]%2==0){ temp[k--]=arr[i]; } else{ temp[j++]=arr[i]; } } for(int i=0;i<n;i++){ arr[i]=temp[i]; } }"
},
{
"code": null,
"e": 6007,
"s": 6005,
"text": "0"
},
{
"code": null,
"e": 6027,
"s": 6007,
"text": "dangrio2 months ago"
},
{
"code": null,
"e": 6215,
"s": 6027,
"text": "static bool compareOddEven(int a, int b){ if(a%2 == 0 && b%2==0) return a<b; if(a%2 != 0 && b%2 != 0) return b<a; if( a%2 != 0) return true; else return false; }"
},
{
"code": null,
"e": 6296,
"s": 6215,
"text": "void sortIt(long long arr[], long long n) {sort(arr,arr+n,compareOddEven); }"
},
{
"code": null,
"e": 6300,
"s": 6298,
"text": "0"
},
{
"code": null,
"e": 6320,
"s": 6300,
"text": "dangrio2 months ago"
},
{
"code": null,
"e": 6338,
"s": 6320,
"text": "Time Taken = 0.5s"
},
{
"code": null,
"e": 6514,
"s": 6340,
"text": "for(int i=0;i<n;i++) if(arr[i]%2) arr[i] = (-1)*arr[i]; sort(arr,arr+n); int i = 0; while(arr[i]<0){ arr[i] = (-1)*arr[i]; i++; }"
},
{
"code": null,
"e": 6516,
"s": 6514,
"text": "0"
},
{
"code": null,
"e": 6536,
"s": 6516,
"text": "dangrio2 months ago"
},
{
"code": null,
"e": 6554,
"s": 6536,
"text": "Time Taken = 0.5s"
},
{
"code": null,
"e": 6962,
"s": 6556,
"text": "long long left = 0, right = n-1, k=0; while(left<right){ //find the first even number while(arr[left]%2 != 0){ left++, k++; } //Finding the odd number from the right side while(arr[right]%2 == 0) right--; if(left<right) swap(arr[left], arr[right]); } sort(arr,arr+k,greater<long long>()); sort(arr+k,arr+n);"
},
{
"code": null,
"e": 7108,
"s": 6962,
"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": 7144,
"s": 7108,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7154,
"s": 7144,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7164,
"s": 7154,
"text": "\nContest\n"
},
{
"code": null,
"e": 7227,
"s": 7164,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7375,
"s": 7227,
"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": 7583,
"s": 7375,
"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": 7689,
"s": 7583,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Sentence Correctness classifier using Transfer Learning with Huggingface BERT | by Ayush Chaurasia | Towards Data Science
|
Learn To build production level NLP applications simply using huggingface
Here’s the Link to live Dashboard
In this article, we’ll build a near state of the art sentence classifier leveraging the power of recent breakthroughs in the field of Natural Language Processing. We’ll focus on application of transfer learning in NLP to create high performance models with minimal effort on a range of NLP tasks.
In the last two years or so, NLP research has been quite rapid as compared to other domains of applied deep learning. models like Allen AI’s ELMO, OpenAI’s Open-GPT, and Google’s BERT allowed researchers to smash multiple benchmarks with minimal fine tuning for specific tasks. As a result, NLP research reproduction and experimentation has become more accessible.
BERT (Bidirectional Encoder Representations from Transformers), released in late 2018 by Google researchers is the model we’ll use to train our sentence classifier.
We’ll use transfer learning on the pre-trained BERT model. This approach is better than training a deep model like GRU or LSTM from scratch as:
the pre-trained BERT model weights already encode a lot of information about our language. As a result, it takes much less time to train our fine-tuned model. We’ll train our model with hyper-parameter sweeps to find the best combination within an hour on colab while training a single deep RNN model from scratch would take more than hundreds of hours on GPU!
As we are essentially performing transfer learning, we need significantly less data to build an accurate system. Compared to millions of data points required to train a model from scratch, we can accomplish the same task with only a few thousand data points.
BERT, based on transformer network, is Bi-directional network that produces the language encoding for various tasks such as modelling, classification etc.
Google said BERT helps better understand the nuances and context of words in searches and better match those queries with more relevant results. It is also used for featured snippets. Here’s an example.
Let’s look at another exciting application of this model, i.e , sentence classification.
Now, we’ll quickly move into training and experimentation, but if you want more details about theenvironment and datasets, check out this tutorial by Chris McCormick.
Let’s first install the huggingface library on colab:
!pip install transformers
This library comes with various pre-trained state of the art models. For our sentence classification we’ll use BertForSequenceClassification model.
We’ll use The Corpus of Linguistic Acceptability (CoLA) dataset for single sentence classification. It’s a set of sentences labeled as grammatically correct or incorrect. It was first published in May of 2018, and is one of the tests included in the “GLUE Benchmark” on which models like BERT are competing.
Let’s download and unzip the dataset
If everything executes without errors, you’ll get the following files:
As you can see that we already have a tokenized version of the dataset, but we need to tokenize it again because, in order to apply the pre-trained BERT, we must use the tokenizer provided by the model. This is because:
the model has a specific, fixed vocabulary and
the BERT tokenizer has a particular way of handling out-of-vocabulary words.
Let’s take a look at the format of the dataset by parsing it using pandas
A few things to notice here:
We just have 8551 data points using which train a SOTA deep model by using transfer learning.
The attributes that we care about are sentence and it label .
The acceptability judgement where 0=unacceptable and 1=acceptable.
Finally, let’s get a list of these sentences.
As mentioned earlier, the sentences that are to be fed into the BERT model must be tokenized using the BERT tokenizer. Let’s take a look at an example.
Using this tokenizer on a sentence would result into something like this:Original: Our friends won't buy this analysis, let alone the next one we propose.Tokenized: ['our', 'friends', 'won', "'", 't', 'buy', 'this', 'analysis', ',', 'let', 'alone', 'the', 'next', 'one', 'we', 'propose', '.']Token IDs: [2256, 2814, 2180, 1005, 1056, 4965, 2023, 4106, 1010, 2292, 2894, 1996, 2279, 2028, 2057, 16599, 1012]
Before we process the entire dataset using this tokenizer, there are a few conditions that we need to satisfy in order to setup the training data for BERT:
Add special tokens to the start and end of each sentence. At the end of every sentence, we need to append the special [SEP] token and for classification tasks, we must prepend the special [CLS] token to the beginning of every sentence.
Pad & truncate all sentences to a single constant length
Explicitly differentiate real tokens from padding tokens with the “attention mask”. The “Attention Mask” is simply an array of 1s and 0s indicating which tokens are padding and which aren’t
Here’s how the network architecture will operate on a particular input after all the pre-processing.
The first task is to decide the maximum length of a sentence.
Output
Max sentence length: 47
To follow a general convention that the sizes should be in powers of 2, we’ll choose the closest number that is a power of 2, i.e, 64.
Now, we’re ready to perform the real tokenization. But as we’re using transformers, we can use an inbuilt function tokenizer.encode_plus which automates all of the following tasks:
Split the sentence into tokens.Add the special [CLS] and [SEP] tokens.Map the tokens to their IDs.Pad or truncate all sentences to the same length.Create the attention masks which explicitly differentiate real tokens from [PAD] tokens.
Split the sentence into tokens.
Add the special [CLS] and [SEP] tokens.
Map the tokens to their IDs.
Pad or truncate all sentences to the same length.
Create the attention masks which explicitly differentiate real tokens from [PAD] tokens.
We’ll split the the data into train and test set. Divide up our training set to use 90% for training and 10% for validation.
The next steps require us to guess various hyper-parameter values. We’ll automate that taks by sweeping across all the value combinations of all parameters. For doing that, we’ll initialize a wandb object before starting the training loop. The hyper-parameter value for the current run is saved in wandb.config.parameter_name .
Here, we’re using RandomSampler to sample trainset and SequentialSampler to sample validation set.
We’ll be using pre-trained BertForSequenceClassification. We’ll add a single dense or fully-connected layer to perform the task of binary classification. We’ll separate each part of the program as a separate function block.
The num_labels parameter describes the number of final output neurons.
We’ll use an implementation of Adam optimizer with am inbuilt weight-decay mechanism provided by huggingface. The learning rate will be provided by wandb.config
We’ll also initialize a learning rate scheduler to perform learning rate decay. The training epochs is also a hyper-parameter so we’ll initialize that using wandb.config .
There’s only one step left before we train our model. We’ll setup a configuration file that’ll list out all the values a hyper-parameter can take. Then we’ll initialize our wandb sweep agent to log, compare and visualize the performance of each combination.
The metric we’re looking to maximize is the val_accuracy which we’ll log in the training loop.
In the BERT paper, the authors described the best set of hyper-parameters to perform transfer learning and we’re using that same sets of values for our hyper-parameters.
Now we have a sweep id which is required to run a sweep. We now only need a train function that will be repeatedly invoked for each sweep.
On running a wandb sweep, you get a few automatic visualizations along with the ones that we’ve logged manually. It is now time to make deductions.
Some of the most essential information about the model performance can be deduced directly from the parameter correlation graph.
Here, we can see how all of the runs performed in the task of maximizing the validation accuracy. We can deduce the best hyper-parameter combination is batch size of 16, learning rate of 3e-5 and trained for 3 epochs which will result in accuracy of about 84%.
If you want a simpler visualization that just compares the time taken by each run as well as how it performs in optimizing the desired metric, you can refer another useful visualization in the dashboard which compares the validation accuracy Vs the time of a particular run.
Now let’s take a look at the visualizations of the metrics that we logged.
Now you have the BERT trained on best set of hyper-parameter values for performing sentence classification along with various statistical visualizations to support choice of parameters.
This post demonstrates that with a pre-trained BERT model you can quickly create a model with minimum fine-tuning and data using the huggingface interface, depending on the specific NLP task you are interested in.
I hope this has been nice read. All of the results in this article can be reproduced using this colab notebook and the visualizations comparing various run can be viewed in this wandb sweeps page.
|
[
{
"code": null,
"e": 246,
"s": 172,
"text": "Learn To build production level NLP applications simply using huggingface"
},
{
"code": null,
"e": 280,
"s": 246,
"text": "Here’s the Link to live Dashboard"
},
{
"code": null,
"e": 577,
"s": 280,
"text": "In this article, we’ll build a near state of the art sentence classifier leveraging the power of recent breakthroughs in the field of Natural Language Processing. We’ll focus on application of transfer learning in NLP to create high performance models with minimal effort on a range of NLP tasks."
},
{
"code": null,
"e": 942,
"s": 577,
"text": "In the last two years or so, NLP research has been quite rapid as compared to other domains of applied deep learning. models like Allen AI’s ELMO, OpenAI’s Open-GPT, and Google’s BERT allowed researchers to smash multiple benchmarks with minimal fine tuning for specific tasks. As a result, NLP research reproduction and experimentation has become more accessible."
},
{
"code": null,
"e": 1107,
"s": 942,
"text": "BERT (Bidirectional Encoder Representations from Transformers), released in late 2018 by Google researchers is the model we’ll use to train our sentence classifier."
},
{
"code": null,
"e": 1251,
"s": 1107,
"text": "We’ll use transfer learning on the pre-trained BERT model. This approach is better than training a deep model like GRU or LSTM from scratch as:"
},
{
"code": null,
"e": 1612,
"s": 1251,
"text": "the pre-trained BERT model weights already encode a lot of information about our language. As a result, it takes much less time to train our fine-tuned model. We’ll train our model with hyper-parameter sweeps to find the best combination within an hour on colab while training a single deep RNN model from scratch would take more than hundreds of hours on GPU!"
},
{
"code": null,
"e": 1871,
"s": 1612,
"text": "As we are essentially performing transfer learning, we need significantly less data to build an accurate system. Compared to millions of data points required to train a model from scratch, we can accomplish the same task with only a few thousand data points."
},
{
"code": null,
"e": 2026,
"s": 1871,
"text": "BERT, based on transformer network, is Bi-directional network that produces the language encoding for various tasks such as modelling, classification etc."
},
{
"code": null,
"e": 2229,
"s": 2026,
"text": "Google said BERT helps better understand the nuances and context of words in searches and better match those queries with more relevant results. It is also used for featured snippets. Here’s an example."
},
{
"code": null,
"e": 2318,
"s": 2229,
"text": "Let’s look at another exciting application of this model, i.e , sentence classification."
},
{
"code": null,
"e": 2485,
"s": 2318,
"text": "Now, we’ll quickly move into training and experimentation, but if you want more details about theenvironment and datasets, check out this tutorial by Chris McCormick."
},
{
"code": null,
"e": 2539,
"s": 2485,
"text": "Let’s first install the huggingface library on colab:"
},
{
"code": null,
"e": 2565,
"s": 2539,
"text": "!pip install transformers"
},
{
"code": null,
"e": 2713,
"s": 2565,
"text": "This library comes with various pre-trained state of the art models. For our sentence classification we’ll use BertForSequenceClassification model."
},
{
"code": null,
"e": 3021,
"s": 2713,
"text": "We’ll use The Corpus of Linguistic Acceptability (CoLA) dataset for single sentence classification. It’s a set of sentences labeled as grammatically correct or incorrect. It was first published in May of 2018, and is one of the tests included in the “GLUE Benchmark” on which models like BERT are competing."
},
{
"code": null,
"e": 3058,
"s": 3021,
"text": "Let’s download and unzip the dataset"
},
{
"code": null,
"e": 3129,
"s": 3058,
"text": "If everything executes without errors, you’ll get the following files:"
},
{
"code": null,
"e": 3349,
"s": 3129,
"text": "As you can see that we already have a tokenized version of the dataset, but we need to tokenize it again because, in order to apply the pre-trained BERT, we must use the tokenizer provided by the model. This is because:"
},
{
"code": null,
"e": 3396,
"s": 3349,
"text": "the model has a specific, fixed vocabulary and"
},
{
"code": null,
"e": 3473,
"s": 3396,
"text": "the BERT tokenizer has a particular way of handling out-of-vocabulary words."
},
{
"code": null,
"e": 3547,
"s": 3473,
"text": "Let’s take a look at the format of the dataset by parsing it using pandas"
},
{
"code": null,
"e": 3576,
"s": 3547,
"text": "A few things to notice here:"
},
{
"code": null,
"e": 3670,
"s": 3576,
"text": "We just have 8551 data points using which train a SOTA deep model by using transfer learning."
},
{
"code": null,
"e": 3732,
"s": 3670,
"text": "The attributes that we care about are sentence and it label ."
},
{
"code": null,
"e": 3799,
"s": 3732,
"text": "The acceptability judgement where 0=unacceptable and 1=acceptable."
},
{
"code": null,
"e": 3845,
"s": 3799,
"text": "Finally, let’s get a list of these sentences."
},
{
"code": null,
"e": 3997,
"s": 3845,
"text": "As mentioned earlier, the sentences that are to be fed into the BERT model must be tokenized using the BERT tokenizer. Let’s take a look at an example."
},
{
"code": null,
"e": 4407,
"s": 3997,
"text": "Using this tokenizer on a sentence would result into something like this:Original: Our friends won't buy this analysis, let alone the next one we propose.Tokenized: ['our', 'friends', 'won', \"'\", 't', 'buy', 'this', 'analysis', ',', 'let', 'alone', 'the', 'next', 'one', 'we', 'propose', '.']Token IDs: [2256, 2814, 2180, 1005, 1056, 4965, 2023, 4106, 1010, 2292, 2894, 1996, 2279, 2028, 2057, 16599, 1012]"
},
{
"code": null,
"e": 4563,
"s": 4407,
"text": "Before we process the entire dataset using this tokenizer, there are a few conditions that we need to satisfy in order to setup the training data for BERT:"
},
{
"code": null,
"e": 4799,
"s": 4563,
"text": "Add special tokens to the start and end of each sentence. At the end of every sentence, we need to append the special [SEP] token and for classification tasks, we must prepend the special [CLS] token to the beginning of every sentence."
},
{
"code": null,
"e": 4856,
"s": 4799,
"text": "Pad & truncate all sentences to a single constant length"
},
{
"code": null,
"e": 5046,
"s": 4856,
"text": "Explicitly differentiate real tokens from padding tokens with the “attention mask”. The “Attention Mask” is simply an array of 1s and 0s indicating which tokens are padding and which aren’t"
},
{
"code": null,
"e": 5147,
"s": 5046,
"text": "Here’s how the network architecture will operate on a particular input after all the pre-processing."
},
{
"code": null,
"e": 5209,
"s": 5147,
"text": "The first task is to decide the maximum length of a sentence."
},
{
"code": null,
"e": 5216,
"s": 5209,
"text": "Output"
},
{
"code": null,
"e": 5241,
"s": 5216,
"text": "Max sentence length: 47"
},
{
"code": null,
"e": 5376,
"s": 5241,
"text": "To follow a general convention that the sizes should be in powers of 2, we’ll choose the closest number that is a power of 2, i.e, 64."
},
{
"code": null,
"e": 5557,
"s": 5376,
"text": "Now, we’re ready to perform the real tokenization. But as we’re using transformers, we can use an inbuilt function tokenizer.encode_plus which automates all of the following tasks:"
},
{
"code": null,
"e": 5793,
"s": 5557,
"text": "Split the sentence into tokens.Add the special [CLS] and [SEP] tokens.Map the tokens to their IDs.Pad or truncate all sentences to the same length.Create the attention masks which explicitly differentiate real tokens from [PAD] tokens."
},
{
"code": null,
"e": 5825,
"s": 5793,
"text": "Split the sentence into tokens."
},
{
"code": null,
"e": 5865,
"s": 5825,
"text": "Add the special [CLS] and [SEP] tokens."
},
{
"code": null,
"e": 5894,
"s": 5865,
"text": "Map the tokens to their IDs."
},
{
"code": null,
"e": 5944,
"s": 5894,
"text": "Pad or truncate all sentences to the same length."
},
{
"code": null,
"e": 6033,
"s": 5944,
"text": "Create the attention masks which explicitly differentiate real tokens from [PAD] tokens."
},
{
"code": null,
"e": 6158,
"s": 6033,
"text": "We’ll split the the data into train and test set. Divide up our training set to use 90% for training and 10% for validation."
},
{
"code": null,
"e": 6486,
"s": 6158,
"text": "The next steps require us to guess various hyper-parameter values. We’ll automate that taks by sweeping across all the value combinations of all parameters. For doing that, we’ll initialize a wandb object before starting the training loop. The hyper-parameter value for the current run is saved in wandb.config.parameter_name ."
},
{
"code": null,
"e": 6585,
"s": 6486,
"text": "Here, we’re using RandomSampler to sample trainset and SequentialSampler to sample validation set."
},
{
"code": null,
"e": 6809,
"s": 6585,
"text": "We’ll be using pre-trained BertForSequenceClassification. We’ll add a single dense or fully-connected layer to perform the task of binary classification. We’ll separate each part of the program as a separate function block."
},
{
"code": null,
"e": 6880,
"s": 6809,
"text": "The num_labels parameter describes the number of final output neurons."
},
{
"code": null,
"e": 7041,
"s": 6880,
"text": "We’ll use an implementation of Adam optimizer with am inbuilt weight-decay mechanism provided by huggingface. The learning rate will be provided by wandb.config"
},
{
"code": null,
"e": 7213,
"s": 7041,
"text": "We’ll also initialize a learning rate scheduler to perform learning rate decay. The training epochs is also a hyper-parameter so we’ll initialize that using wandb.config ."
},
{
"code": null,
"e": 7471,
"s": 7213,
"text": "There’s only one step left before we train our model. We’ll setup a configuration file that’ll list out all the values a hyper-parameter can take. Then we’ll initialize our wandb sweep agent to log, compare and visualize the performance of each combination."
},
{
"code": null,
"e": 7566,
"s": 7471,
"text": "The metric we’re looking to maximize is the val_accuracy which we’ll log in the training loop."
},
{
"code": null,
"e": 7736,
"s": 7566,
"text": "In the BERT paper, the authors described the best set of hyper-parameters to perform transfer learning and we’re using that same sets of values for our hyper-parameters."
},
{
"code": null,
"e": 7875,
"s": 7736,
"text": "Now we have a sweep id which is required to run a sweep. We now only need a train function that will be repeatedly invoked for each sweep."
},
{
"code": null,
"e": 8023,
"s": 7875,
"text": "On running a wandb sweep, you get a few automatic visualizations along with the ones that we’ve logged manually. It is now time to make deductions."
},
{
"code": null,
"e": 8152,
"s": 8023,
"text": "Some of the most essential information about the model performance can be deduced directly from the parameter correlation graph."
},
{
"code": null,
"e": 8413,
"s": 8152,
"text": "Here, we can see how all of the runs performed in the task of maximizing the validation accuracy. We can deduce the best hyper-parameter combination is batch size of 16, learning rate of 3e-5 and trained for 3 epochs which will result in accuracy of about 84%."
},
{
"code": null,
"e": 8688,
"s": 8413,
"text": "If you want a simpler visualization that just compares the time taken by each run as well as how it performs in optimizing the desired metric, you can refer another useful visualization in the dashboard which compares the validation accuracy Vs the time of a particular run."
},
{
"code": null,
"e": 8763,
"s": 8688,
"text": "Now let’s take a look at the visualizations of the metrics that we logged."
},
{
"code": null,
"e": 8949,
"s": 8763,
"text": "Now you have the BERT trained on best set of hyper-parameter values for performing sentence classification along with various statistical visualizations to support choice of parameters."
},
{
"code": null,
"e": 9163,
"s": 8949,
"text": "This post demonstrates that with a pre-trained BERT model you can quickly create a model with minimum fine-tuning and data using the huggingface interface, depending on the specific NLP task you are interested in."
}
] |
K-th Smallest Prime Fraction in C++
|
Suppose we have one sorted list, there is 1 and some prime numbers, now for every p < q in the list, we will consider fraction p/q, then we have to find which is the kth smallest fraction. We have to return an array as answer, so ans[0] will be p and ans[1] will be q.
So if the input is like [1,3,5,7], and k = 2, then the answer will be 1/5, as the fractions are 1/3, 1/5, 1/7, 3/5, 3/7, 5/7, the second smallest is 1/5.
To solve this, we will follow these steps −
Define Data, this will take a, b and a/b
Define an array ret of size 2
n := size of A
define one priority queue pq
for initialize i := 0, when i < n, update (increase i by 1), do −insert Data(A[0], A[i], 0) into pq
insert Data(A[0], A[i], 0) into pq
while K is non-zero, do −temp = top element of pqdelete element from pqif K is same as 0, then −ret[0] := a of tempret[1] := b of tempreturn retif temp.idx + 1 < n, then −idx := idx of temp + 1insert Data(A[idx], temp.b, idx) into pqdecrease K by 1
temp = top element of pq
delete element from pq
if K is same as 0, then −ret[0] := a of tempret[1] := b of tempreturn ret
ret[0] := a of temp
ret[1] := b of temp
return ret
if temp.idx + 1 < n, then −idx := idx of temp + 1insert Data(A[idx], temp.b, idx) into pq
idx := idx of temp + 1
insert Data(A[idx], temp.b, idx) into pq
decrease K by 1
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
struct Data{
double val, a, b;
int idx;
Data(double a, double b, int c){
val = a / b;
this->a = a;
this->b = b;
idx = c;
}
};
struct Comparator{
bool operator()(Data a, Data b){
return !(a.val < b.val);
}
};
class Solution {
public:
vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {
vector <int> ret(2);
int n = A.size();
priority_queue <Data, vector <Data>, Comparator> pq;
for(int i = 0; i < n; i++){
pq.push(Data(double(A[0]), double(A[i]), 0));
}
while(K--){
Data temp = pq.top();
pq.pop();
if(K == 0){
ret[0] = temp.a;
ret[1] = temp.b;
return ret;
}
if(temp.idx + 1 < n){
int idx = temp.idx + 1;
pq.push(Data(double(A[idx]), double(temp.b), idx));
}
}
return ret;
}
};
main(){
Solution ob;
vector<int> v = {1,3,5,7};
print_vector(ob.kthSmallestPrimeFraction(v, 2));
}
{1,3,5,7}
2
[1, 5, ]
|
[
{
"code": null,
"e": 1331,
"s": 1062,
"text": "Suppose we have one sorted list, there is 1 and some prime numbers, now for every p < q in the list, we will consider fraction p/q, then we have to find which is the kth smallest fraction. We have to return an array as answer, so ans[0] will be p and ans[1] will be q."
},
{
"code": null,
"e": 1485,
"s": 1331,
"text": "So if the input is like [1,3,5,7], and k = 2, then the answer will be 1/5, as the fractions are 1/3, 1/5, 1/7, 3/5, 3/7, 5/7, the second smallest is 1/5."
},
{
"code": null,
"e": 1529,
"s": 1485,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1570,
"s": 1529,
"text": "Define Data, this will take a, b and a/b"
},
{
"code": null,
"e": 1600,
"s": 1570,
"text": "Define an array ret of size 2"
},
{
"code": null,
"e": 1615,
"s": 1600,
"text": "n := size of A"
},
{
"code": null,
"e": 1644,
"s": 1615,
"text": "define one priority queue pq"
},
{
"code": null,
"e": 1744,
"s": 1644,
"text": "for initialize i := 0, when i < n, update (increase i by 1), do −insert Data(A[0], A[i], 0) into pq"
},
{
"code": null,
"e": 1779,
"s": 1744,
"text": "insert Data(A[0], A[i], 0) into pq"
},
{
"code": null,
"e": 2028,
"s": 1779,
"text": "while K is non-zero, do −temp = top element of pqdelete element from pqif K is same as 0, then −ret[0] := a of tempret[1] := b of tempreturn retif temp.idx + 1 < n, then −idx := idx of temp + 1insert Data(A[idx], temp.b, idx) into pqdecrease K by 1"
},
{
"code": null,
"e": 2053,
"s": 2028,
"text": "temp = top element of pq"
},
{
"code": null,
"e": 2076,
"s": 2053,
"text": "delete element from pq"
},
{
"code": null,
"e": 2150,
"s": 2076,
"text": "if K is same as 0, then −ret[0] := a of tempret[1] := b of tempreturn ret"
},
{
"code": null,
"e": 2170,
"s": 2150,
"text": "ret[0] := a of temp"
},
{
"code": null,
"e": 2190,
"s": 2170,
"text": "ret[1] := b of temp"
},
{
"code": null,
"e": 2201,
"s": 2190,
"text": "return ret"
},
{
"code": null,
"e": 2291,
"s": 2201,
"text": "if temp.idx + 1 < n, then −idx := idx of temp + 1insert Data(A[idx], temp.b, idx) into pq"
},
{
"code": null,
"e": 2314,
"s": 2291,
"text": "idx := idx of temp + 1"
},
{
"code": null,
"e": 2355,
"s": 2314,
"text": "insert Data(A[idx], temp.b, idx) into pq"
},
{
"code": null,
"e": 2371,
"s": 2355,
"text": "decrease K by 1"
},
{
"code": null,
"e": 2382,
"s": 2371,
"text": "return ret"
},
{
"code": null,
"e": 2452,
"s": 2382,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2463,
"s": 2452,
"text": " Live Demo"
},
{
"code": null,
"e": 3672,
"s": 2463,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nstruct Data{\n double val, a, b;\n int idx;\n Data(double a, double b, int c){\n val = a / b;\n this->a = a;\n this->b = b;\n idx = c;\n }\n};\nstruct Comparator{\n bool operator()(Data a, Data b){\n return !(a.val < b.val);\n }\n};\nclass Solution {\npublic:\n vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {\n vector <int> ret(2);\n int n = A.size();\n priority_queue <Data, vector <Data>, Comparator> pq;\n for(int i = 0; i < n; i++){\n pq.push(Data(double(A[0]), double(A[i]), 0));\n }\n while(K--){\n Data temp = pq.top();\n pq.pop();\n if(K == 0){\n ret[0] = temp.a;\n ret[1] = temp.b;\n return ret;\n }\n if(temp.idx + 1 < n){\n int idx = temp.idx + 1;\n pq.push(Data(double(A[idx]), double(temp.b), idx));\n }\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,3,5,7};\n print_vector(ob.kthSmallestPrimeFraction(v, 2));\n}"
},
{
"code": null,
"e": 3684,
"s": 3672,
"text": "{1,3,5,7}\n2"
},
{
"code": null,
"e": 3693,
"s": 3684,
"text": "[1, 5, ]"
}
] |
How to convert a Drawable to a Bitmap in Android using Kotlin?
|
This example demonstrates how to convert a Drawable to a Bitmap in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="4dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnConvert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Convert Drawable to Bitmap" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val imageView: ImageView = findViewById(R.id.imageView)
val btnConvert: Button = findViewById(R.id.btnConvert)
btnConvert.setOnClickListener {
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)
imageView.setImageBitmap(bitmap)
Toast.makeText(applicationContext, "Image converted to Bitmap",
Toast.LENGTH_SHORT).show()
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "This example demonstrates how to convert a Drawable to a Bitmap in Android using Kotlin."
},
{
"code": null,
"e": 1279,
"s": 1151,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1344,
"s": 1279,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2013,
"s": 1344,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n<ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n<Button\n android:id=\"@+id/btnConvert\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"Convert Drawable to Bitmap\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2068,
"s": 2013,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2886,
"s": 2068,
"text": "import android.graphics.BitmapFactory\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.ImageView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val imageView: ImageView = findViewById(R.id.imageView)\n val btnConvert: Button = findViewById(R.id.btnConvert)\n btnConvert.setOnClickListener {\n val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)\n imageView.setImageBitmap(bitmap)\n Toast.makeText(applicationContext, \"Image converted to Bitmap\",\n Toast.LENGTH_SHORT).show()\n }\n }\n}"
},
{
"code": null,
"e": 2941,
"s": 2886,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3612,
"s": 2941,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3960,
"s": 3612,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
\overline - Tex Command
|
\overline - Used to create overline symbol over the argument.
{ \overline #1}
\overline command draws overline symbol over the argument.
\overline{AB}
AB ̄
\overline a
a ̄
\overline{\text{a long argument}}
a long argument ̄
\overline{AB}
AB ̄
\overline{AB}
\overline a
a ̄
\overline a
\overline{\text{a long argument}}
a long argument ̄
\overline{\text{a long argument}}
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8048,
"s": 7986,
"text": "\\overline - Used to create overline symbol over the argument."
},
{
"code": null,
"e": 8064,
"s": 8048,
"text": "{ \\overline #1}"
},
{
"code": null,
"e": 8123,
"s": 8064,
"text": "\\overline command draws overline symbol over the argument."
},
{
"code": null,
"e": 8221,
"s": 8123,
"text": "\n\\overline{AB}\n\nAB ̄\n\n\n\\overline a\n\na ̄\n\n\n\\overline{\\text{a long argument}}\n\na long argument ̄\n\n\n"
},
{
"code": null,
"e": 8243,
"s": 8221,
"text": "\\overline{AB}\n\nAB ̄\n\n"
},
{
"code": null,
"e": 8257,
"s": 8243,
"text": "\\overline{AB}"
},
{
"code": null,
"e": 8276,
"s": 8257,
"text": "\\overline a\n\na ̄\n\n"
},
{
"code": null,
"e": 8288,
"s": 8276,
"text": "\\overline a"
},
{
"code": null,
"e": 8343,
"s": 8288,
"text": "\\overline{\\text{a long argument}}\n\na long argument ̄\n\n"
},
{
"code": null,
"e": 8377,
"s": 8343,
"text": "\\overline{\\text{a long argument}}"
},
{
"code": null,
"e": 8409,
"s": 8377,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8422,
"s": 8409,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8455,
"s": 8422,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8468,
"s": 8455,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8500,
"s": 8468,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8536,
"s": 8500,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8571,
"s": 8536,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8588,
"s": 8571,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8621,
"s": 8588,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8635,
"s": 8621,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8667,
"s": 8635,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8682,
"s": 8667,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8689,
"s": 8682,
"text": " Print"
},
{
"code": null,
"e": 8700,
"s": 8689,
"text": " Add Notes"
}
] |
Lodash | _.sampleSize() Method - GeeksforGeeks
|
08 May, 2020
The _.sampleSize() method is used to give an array of n random elements from the given array.
Syntax:
_.sampleSize(array, n)
Parameters: This method accept two parameters as mentioned above and described below:
array: This parameter holds the sample collection.
n: This parameter holds the number of elements to sample.
Return Value: This method returns an array of n random elements.
Example 1:
const _ = require('lodash'); let x = [1, 2, 7, 10, 13, 15]; let result = _.sampleSize(x, 2); console.log(result);
Here, const _ = require('lodash') is used to import the lodash library into the file.
Output:
[10, 13]
Example 2:
const _ = require('lodash'); let x = ['mango', 'apple', 'banana', 'orange', 'grapes']; let result = _.sampleSize(x, 3); console.log(result);
Output:
[ 'grapes', 'orange', 'banana' ]
Example 2:
const _ = require('lodash'); let x = [1, 'a', {'name': 'sampleSize'}, [1, 2, 3]]; let result = _.sampleSize(x, 3); console.log(result);
Output:
[ { name: 'sampleSize' }, 'a', 1 ]
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#sampleSize
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n08 May, 2020"
},
{
"code": null,
"e": 25314,
"s": 25220,
"text": "The _.sampleSize() method is used to give an array of n random elements from the given array."
},
{
"code": null,
"e": 25322,
"s": 25314,
"text": "Syntax:"
},
{
"code": null,
"e": 25345,
"s": 25322,
"text": "_.sampleSize(array, n)"
},
{
"code": null,
"e": 25431,
"s": 25345,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25482,
"s": 25431,
"text": "array: This parameter holds the sample collection."
},
{
"code": null,
"e": 25540,
"s": 25482,
"text": "n: This parameter holds the number of elements to sample."
},
{
"code": null,
"e": 25605,
"s": 25540,
"text": "Return Value: This method returns an array of n random elements."
},
{
"code": null,
"e": 25616,
"s": 25605,
"text": "Example 1:"
},
{
"code": "const _ = require('lodash'); let x = [1, 2, 7, 10, 13, 15]; let result = _.sampleSize(x, 2); console.log(result);",
"e": 25733,
"s": 25616,
"text": null
},
{
"code": null,
"e": 25819,
"s": 25733,
"text": "Here, const _ = require('lodash') is used to import the lodash library into the file."
},
{
"code": null,
"e": 25827,
"s": 25819,
"text": "Output:"
},
{
"code": null,
"e": 25836,
"s": 25827,
"text": "[10, 13]"
},
{
"code": null,
"e": 25847,
"s": 25836,
"text": "Example 2:"
},
{
"code": "const _ = require('lodash'); let x = ['mango', 'apple', 'banana', 'orange', 'grapes']; let result = _.sampleSize(x, 3); console.log(result);",
"e": 25991,
"s": 25847,
"text": null
},
{
"code": null,
"e": 25999,
"s": 25991,
"text": "Output:"
},
{
"code": null,
"e": 26033,
"s": 25999,
"text": "[ 'grapes', 'orange', 'banana' ]\n"
},
{
"code": null,
"e": 26044,
"s": 26033,
"text": "Example 2:"
},
{
"code": "const _ = require('lodash'); let x = [1, 'a', {'name': 'sampleSize'}, [1, 2, 3]]; let result = _.sampleSize(x, 3); console.log(result);",
"e": 26183,
"s": 26044,
"text": null
},
{
"code": null,
"e": 26191,
"s": 26183,
"text": "Output:"
},
{
"code": null,
"e": 26227,
"s": 26191,
"text": "[ { name: 'sampleSize' }, 'a', 1 ]\n"
},
{
"code": null,
"e": 26329,
"s": 26227,
"text": "Note: This will not work in normal JavaScript because it requires the library lodash to be installed."
},
{
"code": null,
"e": 26383,
"s": 26329,
"text": "Reference: https://lodash.com/docs/4.17.15#sampleSize"
},
{
"code": null,
"e": 26401,
"s": 26383,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 26412,
"s": 26401,
"text": "JavaScript"
},
{
"code": null,
"e": 26429,
"s": 26412,
"text": "Web Technologies"
},
{
"code": null,
"e": 26527,
"s": 26429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26536,
"s": 26527,
"text": "Comments"
},
{
"code": null,
"e": 26549,
"s": 26536,
"text": "Old Comments"
},
{
"code": null,
"e": 26610,
"s": 26549,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26651,
"s": 26610,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26705,
"s": 26651,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 26762,
"s": 26705,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 26824,
"s": 26762,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 26866,
"s": 26824,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26899,
"s": 26866,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26961,
"s": 26899,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27004,
"s": 26961,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Stemming & Lemmatization
|
Stemming is a technique used to extract the base form of the words by removing affixes from them. It is just like cutting down the branches of a tree to its stems. For example, the stem of the words eating, eats, eaten is eat.
Search engines use stemming for indexing the words. That’s why rather than storing all forms of a word, a search engine can store only the stems. In this way, stemming reduces the size of the index and increases retrieval accuracy.
In NLTK, stemmerI, which have stem() method, interface has all the stemmers which we are going to cover next. Let us understand it with the following diagram
It is one of the most common stemming algorithms which is basically designed to remove and replace well-known suffixes of English words.
NLTK has PorterStemmer class with the help of which we can easily implement Porter Stemmer algorithms for the word we want to stem. This class knows several regular word forms and suffixes with the help of which it can transform the input word to a final stem. The resulting stem is often a shorter word having the same root meaning. Let us see an example −
First, we need to import the natural language toolkit(nltk).
import nltk
Now, import the PorterStemmer class to implement the Porter Stemmer algorithm.
from nltk.stem import PorterStemmer
Next, create an instance of Porter Stemmer class as follows −
word_stemmer = PorterStemmer()
Now, input the word you want to stem.
word_stemmer.stem('writing')
'write'
word_stemmer.stem('eating')
'eat'
import nltk
from nltk.stem import PorterStemmer
word_stemmer = PorterStemmer()
word_stemmer.stem('writing')
'write'
It was developed at Lancaster University and it is another very common stemming algorithms.
NLTK has LancasterStemmer class with the help of which we can easily implement Lancaster Stemmer algorithms for the word we want to stem. Let us see an example −
First, we need to import the natural language toolkit(nltk).
import nltk
Now, import the LancasterStemmer class to implement Lancaster Stemmer algorithm
from nltk.stem import LancasterStemmer
Next, create an instance of LancasterStemmer class as follows −
Lanc_stemmer = LancasterStemmer()
Now, input the word you want to stem.
Lanc_stemmer.stem('eats')
'eat'
import nltk
from nltk.stem import LancatserStemmer
Lanc_stemmer = LancasterStemmer()
Lanc_stemmer.stem('eats')
'eat'
With the help of this stemming algorithm, we can construct our own stemmer.
NLTK has RegexpStemmer class with the help of which we can easily implement Regular Expression Stemmer algorithms. It basically takes a single regular expression and removes any prefix or suffix that matches the expression. Let us see an example −
First, we need to import the natural language toolkit(nltk).
import nltk
Now, import the RegexpStemmer class to implement the Regular Expression Stemmer algorithm.
from nltk.stem import RegexpStemmer
Next, create an instance of RegexpStemmer class and provides the suffix or prefix you want to remove from the word as follows −
Reg_stemmer = RegexpStemmer(‘ing’)
Now, input the word you want to stem.
Reg_stemmer.stem('eating')
'eat'
Reg_stemmer.stem('ingeat')
'eat'
Reg_stemmer.stem('eats')
'eat'
import nltk
from nltk.stem import RegexpStemmer
Reg_stemmer = RegexpStemmer()
Reg_stemmer.stem('ingeat')
'eat'
It is another very useful stemming algorithm.
NLTK has SnowballStemmer class with the help of which we can easily implement Snowball Stemmer algorithms. It supports 15 non-English languages. In order to use this steaming class, we need to create an instance with the name of the language we are using and then call the stem() method. Let us see an example −
First, we need to import the natural language toolkit(nltk).
import nltk
Now, import the SnowballStemmer class to implement Snowball Stemmer algorithm
from nltk.stem import SnowballStemmer
Let us see the languages it supports −
SnowballStemmer.languages
(
'arabic',
'danish',
'dutch',
'english',
'finnish',
'french',
'german',
'hungarian',
'italian',
'norwegian',
'porter',
'portuguese',
'romanian',
'russian',
'spanish',
'swedish'
)
Next, create an instance of SnowballStemmer class with the language you want to use. Here, we are creating the stemmer for ‘French’ language.
French_stemmer = SnowballStemmer(‘french’)
Now, call the stem() method and input the word you want to stem.
French_stemmer.stem (‘Bonjoura’)
'bonjour'
import nltk
from nltk.stem import SnowballStemmer
French_stemmer = SnowballStemmer(‘french’)
French_stemmer.stem (‘Bonjoura’)
'bonjour'
Lemmatization technique is like stemming. The output we will get after lemmatization is called ‘lemma’, which is a root word rather than root stem, the output of stemming. After lemmatization, we will be getting a valid word that means the same thing.
NLTK provides WordNetLemmatizer class which is a thin wrapper around the wordnet corpus. This class uses morphy() function to the WordNet CorpusReader class to find a lemma. Let us understand it with an example −
First, we need to import the natural language toolkit(nltk).
import nltk
Now, import the WordNetLemmatizer class to implement the lemmatization technique.
from nltk.stem import WordNetLemmatizer
Next, create an instance of WordNetLemmatizer class.
lemmatizer = WordNetLemmatizer()
Now, call the lemmatize() method and input the word of which you want to find lemma.
lemmatizer.lemmatize('eating')
'eating'
lemmatizer.lemmatize('books')
'book'
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
lemmatizer.lemmatize('books')
'book'
Let us understand the difference between Stemming and Lemmatization with the help of the following example −
import nltk
from nltk.stem import PorterStemmer
word_stemmer = PorterStemmer()
word_stemmer.stem('believes')
believ
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
lemmatizer.lemmatize(' believes ')
believ
The output of both programs tells the major difference between stemming and lemmatization. PorterStemmer class chops off the ‘es’ from the word. On the other hand, WordNetLemmatizer class finds a valid word. In simple words, stemming technique only looks at the form of the word whereas lemmatization technique looks at the meaning of the word. It means after applying lemmatization, we will always get a valid word.
59 Lectures
2.5 hours
Mike West
17 Lectures
1 hours
Pranjal Srivastava
6 Lectures
1 hours
Prabh Kirpa Classes
12 Lectures
1 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2611,
"s": 2384,
"text": "Stemming is a technique used to extract the base form of the words by removing affixes from them. It is just like cutting down the branches of a tree to its stems. For example, the stem of the words eating, eats, eaten is eat."
},
{
"code": null,
"e": 2843,
"s": 2611,
"text": "Search engines use stemming for indexing the words. That’s why rather than storing all forms of a word, a search engine can store only the stems. In this way, stemming reduces the size of the index and increases retrieval accuracy."
},
{
"code": null,
"e": 3001,
"s": 2843,
"text": "In NLTK, stemmerI, which have stem() method, interface has all the stemmers which we are going to cover next. Let us understand it with the following diagram"
},
{
"code": null,
"e": 3138,
"s": 3001,
"text": "It is one of the most common stemming algorithms which is basically designed to remove and replace well-known suffixes of English words."
},
{
"code": null,
"e": 3496,
"s": 3138,
"text": "NLTK has PorterStemmer class with the help of which we can easily implement Porter Stemmer algorithms for the word we want to stem. This class knows several regular word forms and suffixes with the help of which it can transform the input word to a final stem. The resulting stem is often a shorter word having the same root meaning. Let us see an example −"
},
{
"code": null,
"e": 3557,
"s": 3496,
"text": "First, we need to import the natural language toolkit(nltk)."
},
{
"code": null,
"e": 3570,
"s": 3557,
"text": "import nltk\n"
},
{
"code": null,
"e": 3649,
"s": 3570,
"text": "Now, import the PorterStemmer class to implement the Porter Stemmer algorithm."
},
{
"code": null,
"e": 3686,
"s": 3649,
"text": "from nltk.stem import PorterStemmer\n"
},
{
"code": null,
"e": 3748,
"s": 3686,
"text": "Next, create an instance of Porter Stemmer class as follows −"
},
{
"code": null,
"e": 3780,
"s": 3748,
"text": "word_stemmer = PorterStemmer()\n"
},
{
"code": null,
"e": 3818,
"s": 3780,
"text": "Now, input the word you want to stem."
},
{
"code": null,
"e": 3848,
"s": 3818,
"text": "word_stemmer.stem('writing')\n"
},
{
"code": null,
"e": 3857,
"s": 3848,
"text": "'write'\n"
},
{
"code": null,
"e": 3886,
"s": 3857,
"text": "word_stemmer.stem('eating')\n"
},
{
"code": null,
"e": 3893,
"s": 3886,
"text": "'eat'\n"
},
{
"code": null,
"e": 4001,
"s": 3893,
"text": "import nltk\nfrom nltk.stem import PorterStemmer\nword_stemmer = PorterStemmer()\nword_stemmer.stem('writing')"
},
{
"code": null,
"e": 4010,
"s": 4001,
"text": "'write'\n"
},
{
"code": null,
"e": 4102,
"s": 4010,
"text": "It was developed at Lancaster University and it is another very common stemming algorithms."
},
{
"code": null,
"e": 4264,
"s": 4102,
"text": "NLTK has LancasterStemmer class with the help of which we can easily implement Lancaster Stemmer algorithms for the word we want to stem. Let us see an example −"
},
{
"code": null,
"e": 4325,
"s": 4264,
"text": "First, we need to import the natural language toolkit(nltk)."
},
{
"code": null,
"e": 4338,
"s": 4325,
"text": "import nltk\n"
},
{
"code": null,
"e": 4418,
"s": 4338,
"text": "Now, import the LancasterStemmer class to implement Lancaster Stemmer algorithm"
},
{
"code": null,
"e": 4458,
"s": 4418,
"text": "from nltk.stem import LancasterStemmer\n"
},
{
"code": null,
"e": 4522,
"s": 4458,
"text": "Next, create an instance of LancasterStemmer class as follows −"
},
{
"code": null,
"e": 4557,
"s": 4522,
"text": "Lanc_stemmer = LancasterStemmer()\n"
},
{
"code": null,
"e": 4595,
"s": 4557,
"text": "Now, input the word you want to stem."
},
{
"code": null,
"e": 4622,
"s": 4595,
"text": "Lanc_stemmer.stem('eats')\n"
},
{
"code": null,
"e": 4629,
"s": 4622,
"text": "'eat'\n"
},
{
"code": null,
"e": 4740,
"s": 4629,
"text": "import nltk\nfrom nltk.stem import LancatserStemmer\nLanc_stemmer = LancasterStemmer()\nLanc_stemmer.stem('eats')"
},
{
"code": null,
"e": 4747,
"s": 4740,
"text": "'eat'\n"
},
{
"code": null,
"e": 4823,
"s": 4747,
"text": "With the help of this stemming algorithm, we can construct our own stemmer."
},
{
"code": null,
"e": 5071,
"s": 4823,
"text": "NLTK has RegexpStemmer class with the help of which we can easily implement Regular Expression Stemmer algorithms. It basically takes a single regular expression and removes any prefix or suffix that matches the expression. Let us see an example −"
},
{
"code": null,
"e": 5132,
"s": 5071,
"text": "First, we need to import the natural language toolkit(nltk)."
},
{
"code": null,
"e": 5145,
"s": 5132,
"text": "import nltk\n"
},
{
"code": null,
"e": 5236,
"s": 5145,
"text": "Now, import the RegexpStemmer class to implement the Regular Expression Stemmer algorithm."
},
{
"code": null,
"e": 5273,
"s": 5236,
"text": "from nltk.stem import RegexpStemmer\n"
},
{
"code": null,
"e": 5401,
"s": 5273,
"text": "Next, create an instance of RegexpStemmer class and provides the suffix or prefix you want to remove from the word as follows −"
},
{
"code": null,
"e": 5437,
"s": 5401,
"text": "Reg_stemmer = RegexpStemmer(‘ing’)\n"
},
{
"code": null,
"e": 5475,
"s": 5437,
"text": "Now, input the word you want to stem."
},
{
"code": null,
"e": 5503,
"s": 5475,
"text": "Reg_stemmer.stem('eating')\n"
},
{
"code": null,
"e": 5510,
"s": 5503,
"text": "'eat'\n"
},
{
"code": null,
"e": 5538,
"s": 5510,
"text": "Reg_stemmer.stem('ingeat')\n"
},
{
"code": null,
"e": 5570,
"s": 5538,
"text": "'eat'\nReg_stemmer.stem('eats')\n"
},
{
"code": null,
"e": 5577,
"s": 5570,
"text": "'eat'\n"
},
{
"code": null,
"e": 5682,
"s": 5577,
"text": "import nltk\nfrom nltk.stem import RegexpStemmer\nReg_stemmer = RegexpStemmer()\nReg_stemmer.stem('ingeat')"
},
{
"code": null,
"e": 5689,
"s": 5682,
"text": "'eat'\n"
},
{
"code": null,
"e": 5735,
"s": 5689,
"text": "It is another very useful stemming algorithm."
},
{
"code": null,
"e": 6047,
"s": 5735,
"text": "NLTK has SnowballStemmer class with the help of which we can easily implement Snowball Stemmer algorithms. It supports 15 non-English languages. In order to use this steaming class, we need to create an instance with the name of the language we are using and then call the stem() method. Let us see an example −"
},
{
"code": null,
"e": 6108,
"s": 6047,
"text": "First, we need to import the natural language toolkit(nltk)."
},
{
"code": null,
"e": 6121,
"s": 6108,
"text": "import nltk\n"
},
{
"code": null,
"e": 6199,
"s": 6121,
"text": "Now, import the SnowballStemmer class to implement Snowball Stemmer algorithm"
},
{
"code": null,
"e": 6238,
"s": 6199,
"text": "from nltk.stem import SnowballStemmer\n"
},
{
"code": null,
"e": 6277,
"s": 6238,
"text": "Let us see the languages it supports −"
},
{
"code": null,
"e": 6304,
"s": 6277,
"text": "SnowballStemmer.languages\n"
},
{
"code": null,
"e": 6533,
"s": 6304,
"text": "(\n 'arabic',\n 'danish',\n 'dutch',\n 'english',\n 'finnish',\n 'french',\n 'german',\n 'hungarian',\n 'italian',\n 'norwegian',\n 'porter',\n 'portuguese',\n 'romanian',\n 'russian',\n 'spanish',\n 'swedish'\n)\n"
},
{
"code": null,
"e": 6675,
"s": 6533,
"text": "Next, create an instance of SnowballStemmer class with the language you want to use. Here, we are creating the stemmer for ‘French’ language."
},
{
"code": null,
"e": 6719,
"s": 6675,
"text": "French_stemmer = SnowballStemmer(‘french’)\n"
},
{
"code": null,
"e": 6784,
"s": 6719,
"text": "Now, call the stem() method and input the word you want to stem."
},
{
"code": null,
"e": 6818,
"s": 6784,
"text": "French_stemmer.stem (‘Bonjoura’)\n"
},
{
"code": null,
"e": 6829,
"s": 6818,
"text": "'bonjour'\n"
},
{
"code": null,
"e": 6955,
"s": 6829,
"text": "import nltk\nfrom nltk.stem import SnowballStemmer\nFrench_stemmer = SnowballStemmer(‘french’)\nFrench_stemmer.stem (‘Bonjoura’)"
},
{
"code": null,
"e": 6966,
"s": 6955,
"text": "'bonjour'\n"
},
{
"code": null,
"e": 7218,
"s": 6966,
"text": "Lemmatization technique is like stemming. The output we will get after lemmatization is called ‘lemma’, which is a root word rather than root stem, the output of stemming. After lemmatization, we will be getting a valid word that means the same thing."
},
{
"code": null,
"e": 7431,
"s": 7218,
"text": "NLTK provides WordNetLemmatizer class which is a thin wrapper around the wordnet corpus. This class uses morphy() function to the WordNet CorpusReader class to find a lemma. Let us understand it with an example −"
},
{
"code": null,
"e": 7492,
"s": 7431,
"text": "First, we need to import the natural language toolkit(nltk)."
},
{
"code": null,
"e": 7505,
"s": 7492,
"text": "import nltk\n"
},
{
"code": null,
"e": 7587,
"s": 7505,
"text": "Now, import the WordNetLemmatizer class to implement the lemmatization technique."
},
{
"code": null,
"e": 7628,
"s": 7587,
"text": "from nltk.stem import WordNetLemmatizer\n"
},
{
"code": null,
"e": 7681,
"s": 7628,
"text": "Next, create an instance of WordNetLemmatizer class."
},
{
"code": null,
"e": 7715,
"s": 7681,
"text": "lemmatizer = WordNetLemmatizer()\n"
},
{
"code": null,
"e": 7800,
"s": 7715,
"text": "Now, call the lemmatize() method and input the word of which you want to find lemma."
},
{
"code": null,
"e": 7832,
"s": 7800,
"text": "lemmatizer.lemmatize('eating')\n"
},
{
"code": null,
"e": 7842,
"s": 7832,
"text": "'eating'\n"
},
{
"code": null,
"e": 7873,
"s": 7842,
"text": "lemmatizer.lemmatize('books')\n"
},
{
"code": null,
"e": 7881,
"s": 7873,
"text": "'book'\n"
},
{
"code": null,
"e": 7996,
"s": 7881,
"text": "import nltk\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\nlemmatizer.lemmatize('books')"
},
{
"code": null,
"e": 8004,
"s": 7996,
"text": "'book'\n"
},
{
"code": null,
"e": 8113,
"s": 8004,
"text": "Let us understand the difference between Stemming and Lemmatization with the help of the following example −"
},
{
"code": null,
"e": 8222,
"s": 8113,
"text": "import nltk\nfrom nltk.stem import PorterStemmer\nword_stemmer = PorterStemmer()\nword_stemmer.stem('believes')"
},
{
"code": null,
"e": 8230,
"s": 8222,
"text": "believ\n"
},
{
"code": null,
"e": 8350,
"s": 8230,
"text": "import nltk\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\nlemmatizer.lemmatize(' believes ')"
},
{
"code": null,
"e": 8358,
"s": 8350,
"text": "believ\n"
},
{
"code": null,
"e": 8775,
"s": 8358,
"text": "The output of both programs tells the major difference between stemming and lemmatization. PorterStemmer class chops off the ‘es’ from the word. On the other hand, WordNetLemmatizer class finds a valid word. In simple words, stemming technique only looks at the form of the word whereas lemmatization technique looks at the meaning of the word. It means after applying lemmatization, we will always get a valid word."
},
{
"code": null,
"e": 8810,
"s": 8775,
"text": "\n 59 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8821,
"s": 8810,
"text": " Mike West"
},
{
"code": null,
"e": 8854,
"s": 8821,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8874,
"s": 8854,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 8906,
"s": 8874,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8927,
"s": 8906,
"text": " Prabh Kirpa Classes"
},
{
"code": null,
"e": 8960,
"s": 8927,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8983,
"s": 8960,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 8990,
"s": 8983,
"text": " Print"
},
{
"code": null,
"e": 9001,
"s": 8990,
"text": " Add Notes"
}
] |
delete() and free() in C++
|
The delete operator is used to deallocate the memory. User has privilege to deallocate the created pointer variable by this delete operator.
Here is the syntax of delete operator in C++ language,
delete pointer_variable;
Here is the syntax to delete the block of allocated memory,
delete[ ] pointer_variable;
Here is an example of delete operator in C++ language,
Live Demo
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int[28];
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
if (!ptr3)
cout << "Allocation of memory failed\n";
else {
for (int i = 10; i < 15; i++)
ptr3[i] = i+1;
cout << "Value of store in block of memory: ";
for (int i = 10; i < 15; i++)
cout << ptr3[i] << " ";
}
delete ptr1;
delete ptr2;
delete[] ptr3;
return 0;
}
Value of pointer variable 1 : 28
Value of pointer variable 2 : 299.121
Value of store in block of memory: 11 12 13 14 15
In the above program, three pointer variables are declared as ptr1, ptr2 and ptr3. The pointer variables ptr1 and ptr2 are initialized with the value using new() and ptr3 is storing the allocated block of memory by new() function.
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int[28];
*ptr1 = 28;
Elements of array are printed by user and sum of elements is printed. To delete the allocated memory; delete ptr1, delete pt2 and delete[] ptr3 are used.
delete ptr1;
delete ptr2;
delete[] ptr3;
The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of pointer which means it still points the same memory location.
Here is the syntax of free() in C language,
void free(void *pointer_name);
Here,
pointer_name − Any name given to the pointer.
Here is an example of free() in C language,
Live Demo
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
free(p);
return 0;
}
Enter elements of array : 32 23 21 28
Sum : 104
In the above program, four variables are declared and one of them is a pointer variable *p which is storing the memory allocated.
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
The elements of array are given by the user and sum of their values are printed. The code to free the pointer is as follows −
free(p);
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "The delete operator is used to deallocate the memory. User has privilege to deallocate the created pointer variable by this delete operator."
},
{
"code": null,
"e": 1258,
"s": 1203,
"text": "Here is the syntax of delete operator in C++ language,"
},
{
"code": null,
"e": 1283,
"s": 1258,
"text": "delete pointer_variable;"
},
{
"code": null,
"e": 1343,
"s": 1283,
"text": "Here is the syntax to delete the block of allocated memory,"
},
{
"code": null,
"e": 1371,
"s": 1343,
"text": "delete[ ] pointer_variable;"
},
{
"code": null,
"e": 1426,
"s": 1371,
"text": "Here is an example of delete operator in C++ language,"
},
{
"code": null,
"e": 1437,
"s": 1426,
"text": " Live Demo"
},
{
"code": null,
"e": 2050,
"s": 1437,
"text": "#include <iostream>\nusing namespace std;\nint main () {\n int *ptr1 = NULL;\n ptr1 = new int;\n float *ptr2 = new float(299.121);\n int *ptr3 = new int[28];\n *ptr1 = 28;\n cout << \"Value of pointer variable 1 : \" << *ptr1 << endl;\n cout << \"Value of pointer variable 2 : \" << *ptr2 << endl;\n if (!ptr3)\n cout << \"Allocation of memory failed\\n\";\n else {\n for (int i = 10; i < 15; i++)\n ptr3[i] = i+1;\n cout << \"Value of store in block of memory: \";\n for (int i = 10; i < 15; i++)\n cout << ptr3[i] << \" \";\n }\n delete ptr1;\n delete ptr2;\n delete[] ptr3;\n return 0;\n}"
},
{
"code": null,
"e": 2171,
"s": 2050,
"text": "Value of pointer variable 1 : 28\nValue of pointer variable 2 : 299.121\nValue of store in block of memory: 11 12 13 14 15"
},
{
"code": null,
"e": 2402,
"s": 2171,
"text": "In the above program, three pointer variables are declared as ptr1, ptr2 and ptr3. The pointer variables ptr1 and ptr2 are initialized with the value using new() and ptr3 is storing the allocated block of memory by new() function."
},
{
"code": null,
"e": 2507,
"s": 2402,
"text": "int *ptr1 = NULL;\nptr1 = new int;\nfloat *ptr2 = new float(299.121);\nint *ptr3 = new int[28];\n*ptr1 = 28;"
},
{
"code": null,
"e": 2661,
"s": 2507,
"text": "Elements of array are printed by user and sum of elements is printed. To delete the allocated memory; delete ptr1, delete pt2 and delete[] ptr3 are used."
},
{
"code": null,
"e": 2702,
"s": 2661,
"text": "delete ptr1;\ndelete ptr2;\ndelete[] ptr3;"
},
{
"code": null,
"e": 2872,
"s": 2702,
"text": "The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of pointer which means it still points the same memory location."
},
{
"code": null,
"e": 2916,
"s": 2872,
"text": "Here is the syntax of free() in C language,"
},
{
"code": null,
"e": 2947,
"s": 2916,
"text": "void free(void *pointer_name);"
},
{
"code": null,
"e": 2953,
"s": 2947,
"text": "Here,"
},
{
"code": null,
"e": 2999,
"s": 2953,
"text": "pointer_name − Any name given to the pointer."
},
{
"code": null,
"e": 3043,
"s": 2999,
"text": "Here is an example of free() in C language,"
},
{
"code": null,
"e": 3054,
"s": 3043,
"text": " Live Demo"
},
{
"code": null,
"e": 3438,
"s": 3054,
"text": "#include <stdio.h>\n#include <stdlib.h>\nint main() {\n int n = 4, i, *p, s = 0;\n p = (int*) malloc(n * sizeof(int));\n if(p == NULL) {\n printf(\"\\nError! memory not allocated.\");\n exit(0);\n }\n printf(\"\\nEnter elements of array : \");\n for(i = 0; i < n; ++i) {\n scanf(\"%d\", p + i);\n s += *(p + i);\n }\n printf(\"\\nSum : %d\", s);\n free(p);\n return 0;\n}"
},
{
"code": null,
"e": 3486,
"s": 3438,
"text": "Enter elements of array : 32 23 21 28\nSum : 104"
},
{
"code": null,
"e": 3616,
"s": 3486,
"text": "In the above program, four variables are declared and one of them is a pointer variable *p which is storing the memory allocated."
},
{
"code": null,
"e": 3677,
"s": 3616,
"text": "int n = 4, i, *p, s = 0;\np = (int*) malloc(n * sizeof(int));"
},
{
"code": null,
"e": 3803,
"s": 3677,
"text": "The elements of array are given by the user and sum of their values are printed. The code to free the pointer is as follows −"
},
{
"code": null,
"e": 3812,
"s": 3803,
"text": "free(p);"
}
] |
How to find the maximum value for each column of a matrix in R?
|
To find the maximum value for each column of a matrix, we need to use apply function. For example, if we have a matrix M that contains 2 rows and 2 columns with values 1, 2 in the first row and 3, 4 in the second row then the maximum for each of the columns in that matrix can be found by using the syntax; apply(M,2,max), hence the result will be 3, 4.
Live Demo
M1−-matrix(1:36,ncol=6)
M1
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 7 13 19 25 31
[2,] 2 8 14 20 26 32
[3,] 3 9 15 21 27 33
[4,] 4 10 16 22 28 34
[5,] 5 11 17 23 29 35
[6,] 6 12 18 24 30 36
apply(M1,2,max)
[1] 6 12 18 24 30 36
Live Demo
M2<-matrix(1:100,ncol=10)
M2
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
apply(M2,2,max)
[1] 10 20 30 40 50 60 70 80 90 100
Live Demo
M3<-matrix(sample(rnorm(10),25,replace=TRUE),ncol=5)
M3
[,1] [,2] [,3] [,4] [,5]
[1,] -0.8410610 -0.8410610 -1.1271937 -0.8410610 -0.1262492
[2,] -1.1271937 -0.3367099 -0.8410610 -0.2109494 -0.2109494
[3,] -0.1262492 -1.0366269 -0.2109494 -0.3367099 -0.2109494
[4,] -0.2109494 -0.3367099 -0.3367099 -0.3367099 -1.9793046
[5,] -1.2250289 -0.1262492 -0.1262492 -1.0366269 -1.1271937
apply(M3,2,max)
[1] -0.1262492 -0.1262492 -0.1262492 -0.2109494 -0.1262492
Live Demo
M4<-matrix(sample(rnorm(100,10,1),25),ncol=5)
M4
[,1] [,2] [,3] [,4] [,5]
[1,] 8.880632 9.932590 12.152003 10.745158 12.644492
[2,] 8.743728 9.223513 9.937427 9.327102 9.490583
[3,] 7.502350 10.231251 9.350336 10.823048 9.282358
[4,] 9.830723 9.045965 10.197617 9.194218 9.420975
[5,] 9.974345 10.835077 9.982087 10.112384 9.404278
apply(M4,2,max)
[1] 9.974345 10.835077 12.152003 10.823048 12.644492
Live Demo
M5<-matrix(sample(rpois(100,10),64),ncol=8)
M5
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 16 4 9 9 10 5 15 9
[2,] 3 6 11 6 15 17 5 9
[3,] 7 10 9 6 16 14 6 2
[4,] 12 10 9 5 10 9 7 11
[5,] 11 9 10 9 12 10 17 6
[6,] 11 10 7 10 9 12 8 9
[7,] 11 7 6 11 8 9 9 8
[8,] 9 12 12 9 12 12 14 12
apply(M5,2,max)
[1] 16 12 12 11 16 17 17 12
Live Demo
M6<-matrix(sample(1:10,100,replace=TRUE),ncol=10)
M6
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 7 1 7 3 5 7 8 7 10 4
[2,] 6 9 7 4 6 5 5 10 9 7
[3,] 10 4 2 2 8 9 9 4 4 1
[4,] 3 1 7 3 3 7 10 8 7 4
[5,] 5 10 7 8 10 3 5 1 8 4
[6,] 7 3 10 4 5 1 5 5 3 4
[7,] 6 4 4 2 1 9 3 6 6 2
[8,] 10 4 2 8 6 10 6 2 5 8
[9,] 6 9 10 7 3 4 6 6 5 4
[10,] 7 10 5 3 6 7 3 8 9 2
apply(M6,2,max)
[1] 10 10 10 8 10 10 10 10 10 8
Live Demo
M7<-matrix(sample(runif(10,2,5),25,replace=TRUE),ncol=5)
M7
[,1] [,2] [,3] [,4] [,5]
[1,] 2.637646 4.744968 3.122147 4.563885 4.744968
[2,] 3.418107 2.637646 3.331060 3.122147 2.845479
[3,] 2.190630 3.331060 2.637646 2.190630 4.834246
[4,] 4.834246 4.563885 2.845479 2.845479 3.418107
[5,] 2.845479 2.190630 2.190630 4.744968 2.637646
apply(M7,2,max)
[1] 4.834246 4.744968 3.331060 4.744968 4.834246
Live Demo
M8<-matrix(sample(5001:9999,64),ncol=8)
M8
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 5294 5567 9539 5907 9808 6692 6810 9809
[2,] 9005 5150 9502 7604 8849 8504 6631 6261
[3,] 6694 5162 7813 5995 9684 8647 7094 9828
[4,] 5055 7450 7588 8006 8480 5145 9741 8959
[5,] 8300 5964 8411 6109 5320 8649 5777 9473
[6,] 9054 5585 7304 6827 6231 5199 8518 8958
[7,] 5912 8356 6741 9949 6363 9488 7093 6813
[8,] 6312 7701 5741 6947 6012 6579 6873 7793
apply(M8,2,max)
[1] 9054 8356 9539 9949 9808 9488 9741 9828
|
[
{
"code": null,
"e": 1416,
"s": 1062,
"text": "To find the maximum value for each column of a matrix, we need to use apply function. For example, if we have a matrix M that contains 2 rows and 2 columns with values 1, 2 in the first row and 3, 4 in the second row then the maximum for each of the columns in that matrix can be found by using the syntax; apply(M,2,max), hence the result will be 3, 4."
},
{
"code": null,
"e": 1427,
"s": 1416,
"text": " Live Demo"
},
{
"code": null,
"e": 1454,
"s": 1427,
"text": "M1−-matrix(1:36,ncol=6)\nM1"
},
{
"code": null,
"e": 1685,
"s": 1454,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 1 7 13 19 25 31\n[2,] 2 8 14 20 26 32\n[3,] 3 9 15 21 27 33\n[4,] 4 10 16 22 28 34\n[5,] 5 11 17 23 29 35\n[6,] 6 12 18 24 30 36"
},
{
"code": null,
"e": 1701,
"s": 1685,
"text": "apply(M1,2,max)"
},
{
"code": null,
"e": 1722,
"s": 1701,
"text": "[1] 6 12 18 24 30 36"
},
{
"code": null,
"e": 1733,
"s": 1722,
"text": " Live Demo"
},
{
"code": null,
"e": 1762,
"s": 1733,
"text": "M2<-matrix(1:100,ncol=10)\nM2"
},
{
"code": null,
"e": 2357,
"s": 1762,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2373,
"s": 2357,
"text": "apply(M2,2,max)"
},
{
"code": null,
"e": 2408,
"s": 2373,
"text": "[1] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2419,
"s": 2408,
"text": " Live Demo"
},
{
"code": null,
"e": 2475,
"s": 2419,
"text": "M3<-matrix(sample(rnorm(10),25,replace=TRUE),ncol=5)\nM3"
},
{
"code": null,
"e": 2833,
"s": 2475,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] -0.8410610 -0.8410610 -1.1271937 -0.8410610 -0.1262492\n[2,] -1.1271937 -0.3367099 -0.8410610 -0.2109494 -0.2109494\n[3,] -0.1262492 -1.0366269 -0.2109494 -0.3367099 -0.2109494\n[4,] -0.2109494 -0.3367099 -0.3367099 -0.3367099 -1.9793046\n[5,] -1.2250289 -0.1262492 -0.1262492 -1.0366269 -1.1271937"
},
{
"code": null,
"e": 2849,
"s": 2833,
"text": "apply(M3,2,max)"
},
{
"code": null,
"e": 2908,
"s": 2849,
"text": "[1] -0.1262492 -0.1262492 -0.1262492 -0.2109494 -0.1262492"
},
{
"code": null,
"e": 2919,
"s": 2908,
"text": " Live Demo"
},
{
"code": null,
"e": 2968,
"s": 2919,
"text": "M4<-matrix(sample(rnorm(100,10,1),25),ncol=5)\nM4"
},
{
"code": null,
"e": 3278,
"s": 2968,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 8.880632 9.932590 12.152003 10.745158 12.644492\n[2,] 8.743728 9.223513 9.937427 9.327102 9.490583\n[3,] 7.502350 10.231251 9.350336 10.823048 9.282358\n[4,] 9.830723 9.045965 10.197617 9.194218 9.420975\n[5,] 9.974345 10.835077 9.982087 10.112384 9.404278"
},
{
"code": null,
"e": 3294,
"s": 3278,
"text": "apply(M4,2,max)"
},
{
"code": null,
"e": 3347,
"s": 3294,
"text": "[1] 9.974345 10.835077 12.152003 10.823048 12.644492"
},
{
"code": null,
"e": 3358,
"s": 3347,
"text": " Live Demo"
},
{
"code": null,
"e": 3405,
"s": 3358,
"text": "M5<-matrix(sample(rpois(100,10),64),ncol=8)\nM5"
},
{
"code": null,
"e": 3803,
"s": 3405,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n[1,] 16 4 9 9 10 5 15 9\n[2,] 3 6 11 6 15 17 5 9\n[3,] 7 10 9 6 16 14 6 2\n[4,] 12 10 9 5 10 9 7 11\n[5,] 11 9 10 9 12 10 17 6\n[6,] 11 10 7 10 9 12 8 9\n[7,] 11 7 6 11 8 9 9 8\n[8,] 9 12 12 9 12 12 14 12"
},
{
"code": null,
"e": 3819,
"s": 3803,
"text": "apply(M5,2,max)"
},
{
"code": null,
"e": 3847,
"s": 3819,
"text": "[1] 16 12 12 11 16 17 17 12"
},
{
"code": null,
"e": 3858,
"s": 3847,
"text": " Live Demo"
},
{
"code": null,
"e": 3911,
"s": 3858,
"text": "M6<-matrix(sample(1:10,100,replace=TRUE),ncol=10)\nM6"
},
{
"code": null,
"e": 4486,
"s": 3911,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 7 1 7 3 5 7 8 7 10 4\n[2,] 6 9 7 4 6 5 5 10 9 7\n[3,] 10 4 2 2 8 9 9 4 4 1\n[4,] 3 1 7 3 3 7 10 8 7 4\n[5,] 5 10 7 8 10 3 5 1 8 4\n[6,] 7 3 10 4 5 1 5 5 3 4\n[7,] 6 4 4 2 1 9 3 6 6 2\n[8,] 10 4 2 8 6 10 6 2 5 8\n[9,] 6 9 10 7 3 4 6 6 5 4\n[10,] 7 10 5 3 6 7 3 8 9 2"
},
{
"code": null,
"e": 4502,
"s": 4486,
"text": "apply(M6,2,max)"
},
{
"code": null,
"e": 4534,
"s": 4502,
"text": "[1] 10 10 10 8 10 10 10 10 10 8"
},
{
"code": null,
"e": 4545,
"s": 4534,
"text": " Live Demo"
},
{
"code": null,
"e": 4605,
"s": 4545,
"text": "M7<-matrix(sample(runif(10,2,5),25,replace=TRUE),ncol=5)\nM7"
},
{
"code": null,
"e": 4902,
"s": 4605,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 2.637646 4.744968 3.122147 4.563885 4.744968\n[2,] 3.418107 2.637646 3.331060 3.122147 2.845479\n[3,] 2.190630 3.331060 2.637646 2.190630 4.834246\n[4,] 4.834246 4.563885 2.845479 2.845479 3.418107\n[5,] 2.845479 2.190630 2.190630 4.744968 2.637646"
},
{
"code": null,
"e": 4918,
"s": 4902,
"text": "apply(M7,2,max)"
},
{
"code": null,
"e": 4967,
"s": 4918,
"text": "[1] 4.834246 4.744968 3.331060 4.744968 4.834246"
},
{
"code": null,
"e": 4978,
"s": 4967,
"text": " Live Demo"
},
{
"code": null,
"e": 5021,
"s": 4978,
"text": "M8<-matrix(sample(5001:9999,64),ncol=8)\nM8"
},
{
"code": null,
"e": 5426,
"s": 5021,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]\n[1,] 5294 5567 9539 5907 9808 6692 6810 9809\n[2,] 9005 5150 9502 7604 8849 8504 6631 6261\n[3,] 6694 5162 7813 5995 9684 8647 7094 9828\n[4,] 5055 7450 7588 8006 8480 5145 9741 8959\n[5,] 8300 5964 8411 6109 5320 8649 5777 9473\n[6,] 9054 5585 7304 6827 6231 5199 8518 8958\n[7,] 5912 8356 6741 9949 6363 9488 7093 6813\n[8,] 6312 7701 5741 6947 6012 6579 6873 7793"
},
{
"code": null,
"e": 5442,
"s": 5426,
"text": "apply(M8,2,max)"
},
{
"code": null,
"e": 5486,
"s": 5442,
"text": "[1] 9054 8356 9539 9949 9808 9488 9741 9828"
}
] |
Python - Column deletion from list of lists
|
In a list of lists an element at the same index of each of the sublist represents a column like structure. In this article we will see how we can delete a column from a list of lists. Which means we have to delete the element at the same index position from each of the sublist.
We use the pop method which removes the element at a particular position. A for loop is designed to iterate through elements at specific index and removes them using pop.
Live Demo
# List of lists
listA = [[3, 9, 5, 1],
[4, 6, 1, 2],
[1, 6, 12, 18]]
# printing original list
print("Given list \n",listA)
# Apply pop
[i.pop(2) for i in listA]
# Result
print("List after deleting the column :\n ",listA)
Running the above code gives us the following result −
Given list
[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]
List after deleting the column :
[[3, 9, 1], [4, 6, 2], [1, 6, 18]]
In this approach we use the del function which is similar to above approach. We mention the index at which the column has to be deleted.
Live Demo
# List of lists
listA = [[3, 9, 5, 1],
[4, 6, 1, 2],
[1, 6, 12, 18]]
# printing original list
print("Given list \n",listA)
# Apply del
for i in listA:
del i[2]
# Result
print("List after deleting the column :\n ",listA)
Running the above code gives us the following result −
Given list
[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]
List after deleting the column :
[[3, 9, 1], [4, 6, 2], [1, 6, 18]]
|
[
{
"code": null,
"e": 1341,
"s": 1062,
"text": "In a list of lists an element at the same index of each of the sublist represents a column like structure. In this article we will see how we can delete a column from a list of lists. Which means we have to delete the element at the same index position from each of the sublist."
},
{
"code": null,
"e": 1512,
"s": 1341,
"text": "We use the pop method which removes the element at a particular position. A for loop is designed to iterate through elements at specific index and removes them using pop."
},
{
"code": null,
"e": 1523,
"s": 1512,
"text": " Live Demo"
},
{
"code": null,
"e": 1747,
"s": 1523,
"text": "# List of lists\nlistA = [[3, 9, 5, 1],\n[4, 6, 1, 2],\n[1, 6, 12, 18]]\n\n# printing original list\nprint(\"Given list \\n\",listA)\n\n# Apply pop\n[i.pop(2) for i in listA]\n\n# Result\nprint(\"List after deleting the column :\\n \",listA)"
},
{
"code": null,
"e": 1802,
"s": 1747,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1926,
"s": 1802,
"text": "Given list\n[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]\nList after deleting the column :\n[[3, 9, 1], [4, 6, 2], [1, 6, 18]]"
},
{
"code": null,
"e": 2063,
"s": 1926,
"text": "In this approach we use the del function which is similar to above approach. We mention the index at which the column has to be deleted."
},
{
"code": null,
"e": 2074,
"s": 2063,
"text": " Live Demo"
},
{
"code": null,
"e": 2297,
"s": 2074,
"text": "# List of lists\nlistA = [[3, 9, 5, 1],\n[4, 6, 1, 2],\n[1, 6, 12, 18]]\n\n# printing original list\nprint(\"Given list \\n\",listA)\n\n# Apply del\nfor i in listA:\ndel i[2]\n\n# Result\nprint(\"List after deleting the column :\\n \",listA)"
},
{
"code": null,
"e": 2352,
"s": 2297,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2476,
"s": 2352,
"text": "Given list\n[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]\nList after deleting the column :\n[[3, 9, 1], [4, 6, 2], [1, 6, 18]]"
}
] |
Count values from comma-separated field in MySQL?
|
You can count values from comma-separated field using CHAR_LENGTH() method from MySQL. The syntax is as follows −
SELECT *, (CHAR_LENGTH(yourColumnName) - CHAR_LENGTH(REPLACE(yourColumnName, ',','')) + 1) as anyVariableName from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table CountValuesCommaSeparated
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> CommaSeparatedValue text,
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (1.76 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)
values('101,104,1900,46675,7895');
Query OK, 1 row affected (0.16 sec)
mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)
values('1010,18949,37465');
Query OK, 1 row affected (0.21 sec)
mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)
values('2010,1201,2743874,7485');
Query OK, 1 row affected (0.42 sec)
mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)
values('4757,457587,48586,378575,3874765,487565');
Query OK, 1 row affected (0.26 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from CountValuesCommaSeparated;
The following is the output −
+----+-----------------------------------------+
| Id | CommaSeparatedValue |
+----+-----------------------------------------+
| 1 | 101,104,1900,46675,7895 |
| 2 | 1010,18949,37465 |
| 3 | 2010,1201,2743874,7485 |
| 4 | 4757,457587,48586,378575,3874765,487565 |
+----+-----------------------------------------+
4 rows in set (0.00 sec)
Here is the query to count values from comma separated fields:
mysql> select *,
-> (CHAR_LENGTH(CommaSeparatedValue) -
CHAR_LENGTH(REPLACE(CommaSeparatedValue, ',', '')) + 1) as TotalValue
-> from CountValuesCommaSeparated;
The following is the output −
+----+-----------------------------------------+------------+
| Id | CommaSeparatedValue | TotalValue |
+----+-----------------------------------------+------------+
| 1 | 101,104,1900,46675,7895 | 5 |
| 2 | 1010,18949,37465 | 3 |
| 3 | 2010,1201,2743874,7485 | 4 |
| 4 | 4757,457587,48586,378575,3874765,487565 | 6 |
+----+-----------------------------------------+------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "You can count values from comma-separated field using CHAR_LENGTH() method from MySQL. The syntax is as follows −"
},
{
"code": null,
"e": 1306,
"s": 1176,
"text": "SELECT *, (CHAR_LENGTH(yourColumnName) - CHAR_LENGTH(REPLACE(yourColumnName, ',','')) + 1) as anyVariableName from yourTableName;"
},
{
"code": null,
"e": 1405,
"s": 1306,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1597,
"s": 1405,
"text": "mysql> create table CountValuesCommaSeparated\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> CommaSeparatedValue text,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (1.76 sec)"
},
{
"code": null,
"e": 1678,
"s": 1597,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2237,
"s": 1678,
"text": "mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)\nvalues('101,104,1900,46675,7895');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)\nvalues('1010,18949,37465');\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)\nvalues('2010,1201,2743874,7485');\nQuery OK, 1 row affected (0.42 sec)\n\nmysql> insert into CountValuesCommaSeparated(CommaSeparatedValue)\nvalues('4757,457587,48586,378575,3874765,487565');\nQuery OK, 1 row affected (0.26 sec)"
},
{
"code": null,
"e": 2322,
"s": 2237,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2369,
"s": 2322,
"text": "mysql> select *from CountValuesCommaSeparated;"
},
{
"code": null,
"e": 2399,
"s": 2369,
"text": "The following is the output −"
},
{
"code": null,
"e": 2816,
"s": 2399,
"text": "+----+-----------------------------------------+\n| Id | CommaSeparatedValue |\n+----+-----------------------------------------+\n| 1 | 101,104,1900,46675,7895 |\n| 2 | 1010,18949,37465 |\n| 3 | 2010,1201,2743874,7485 |\n| 4 | 4757,457587,48586,378575,3874765,487565 |\n+----+-----------------------------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2879,
"s": 2816,
"text": "Here is the query to count values from comma separated fields:"
},
{
"code": null,
"e": 3046,
"s": 2879,
"text": "mysql> select *,\n -> (CHAR_LENGTH(CommaSeparatedValue) -\nCHAR_LENGTH(REPLACE(CommaSeparatedValue, ',', '')) + 1) as TotalValue\n -> from CountValuesCommaSeparated;"
},
{
"code": null,
"e": 3076,
"s": 3046,
"text": "The following is the output −"
},
{
"code": null,
"e": 3597,
"s": 3076,
"text": "+----+-----------------------------------------+------------+\n| Id | CommaSeparatedValue | TotalValue |\n+----+-----------------------------------------+------------+\n| 1 | 101,104,1900,46675,7895 | 5 |\n| 2 | 1010,18949,37465 | 3 |\n| 3 | 2010,1201,2743874,7485 | 4 |\n| 4 | 4757,457587,48586,378575,3874765,487565 | 6 |\n+----+-----------------------------------------+------------+\n4 rows in set (0.00 sec)"
}
] |
Design and Analysis 0-1 Knapsack
|
In this tutorial, earlier we have discussed Fractional Knapsack problem using Greedy approach. We have shown that Greedy approach gives an optimal solution for Fractional Knapsack. However, this chapter will cover 0-1 Knapsack problem and its analysis.
In 0-1 Knapsack, items cannot be broken which means the thief should take the item as a whole or should leave it. This is reason behind calling it as 0-1 Knapsack.
Hence, in case of 0-1 Knapsack, the value of xi can be either 0 or 1, where other constraints remain the same.
0-1 Knapsack cannot be solved by Greedy approach. Greedy approach does not ensure an optimal solution. In many instances, Greedy approach may give an optimal solution.
The following examples will establish our statement.
Let us consider that the capacity of the knapsack is W = 25 and the items are as shown in the following table.
Without considering the profit per unit weight (pi/wi), if we apply Greedy approach to solve this problem, first item A will be selected as it will contribute maximum profit among all the elements.
After selecting item A, no more item will be selected. Hence, for this given set of items total profit is 24. Whereas, the optimal solution can be achieved by selecting items, B and C, where the total profit is 18 + 18 = 36.
Instead of selecting the items based on the overall benefit, in this example the items are selected based on ratio pi/wi. Let us consider that the capacity of the knapsack is W = 60 and the items are as shown in the following table.
Using the Greedy approach, first item A is selected. Then, the next item B is chosen. Hence, the total profit is 100 + 280 = 380. However, the optimal solution of this instance can be achieved by selecting items, B and C, where the total profit is 280 + 120 = 400.
Hence, it can be concluded that Greedy approach may not give an optimal solution.
To solve 0-1 Knapsack, Dynamic Programming approach is required.
A thief is robbing a store and can carry a maximal weight of W into his knapsack. There are n items and weight of ith item is wi and the profit of selecting this item is pi. What items should the thief take?
Let i be the highest-numbered item in an optimal solution S for W dollars. Then S' = S - {i} is an optimal solution for W - wi dollars and the value to the solution S is Vi plus the value of the sub-problem.
We can express this fact in the following formula: define c[i, w] to be the solution for items 1,2, ... , i and the maximum weight w.
The algorithm takes the following inputs
The maximum weight W
The maximum weight W
The number of items n
The number of items n
The two sequences v = <v1, v2, ..., vn> and w = <w1, w2, ..., wn>
The two sequences v = <v1, v2, ..., vn> and w = <w1, w2, ..., wn>
Dynamic-0-1-knapsack (v, w, n, W)
for w = 0 to W do
c[0, w] = 0
for i = 1 to n do
c[i, 0] = 0
for w = 1 to W do
if wi ≤ w then
if vi + c[i-1, w-wi] then
c[i, w] = vi + c[i-1, w-wi]
else c[i, w] = c[i-1, w]
else
c[i, w] = c[i-1, w]
The set of items to take can be deduced from the table, starting at c[n, w] and tracing backwards where the optimal values came from.
If c[i, w] = c[i-1, w], then item i is not part of the solution, and we continue tracing with c[i-1, w]. Otherwise, item i is part of the solution, and we continue tracing with c[i-1, w-W].
This algorithm takes θ(n, w) times as table c has (n + 1).(w + 1) entries, where each entry requires θ(1) time to compute.
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2852,
"s": 2599,
"text": "In this tutorial, earlier we have discussed Fractional Knapsack problem using Greedy approach. We have shown that Greedy approach gives an optimal solution for Fractional Knapsack. However, this chapter will cover 0-1 Knapsack problem and its analysis."
},
{
"code": null,
"e": 3016,
"s": 2852,
"text": "In 0-1 Knapsack, items cannot be broken which means the thief should take the item as a whole or should leave it. This is reason behind calling it as 0-1 Knapsack."
},
{
"code": null,
"e": 3127,
"s": 3016,
"text": "Hence, in case of 0-1 Knapsack, the value of xi can be either 0 or 1, where other constraints remain the same."
},
{
"code": null,
"e": 3295,
"s": 3127,
"text": "0-1 Knapsack cannot be solved by Greedy approach. Greedy approach does not ensure an optimal solution. In many instances, Greedy approach may give an optimal solution."
},
{
"code": null,
"e": 3348,
"s": 3295,
"text": "The following examples will establish our statement."
},
{
"code": null,
"e": 3459,
"s": 3348,
"text": "Let us consider that the capacity of the knapsack is W = 25 and the items are as shown in the following table."
},
{
"code": null,
"e": 3657,
"s": 3459,
"text": "Without considering the profit per unit weight (pi/wi), if we apply Greedy approach to solve this problem, first item A will be selected as it will contribute maximum profit among all the elements."
},
{
"code": null,
"e": 3882,
"s": 3657,
"text": "After selecting item A, no more item will be selected. Hence, for this given set of items total profit is 24. Whereas, the optimal solution can be achieved by selecting items, B and C, where the total profit is 18 + 18 = 36."
},
{
"code": null,
"e": 4115,
"s": 3882,
"text": "Instead of selecting the items based on the overall benefit, in this example the items are selected based on ratio pi/wi. Let us consider that the capacity of the knapsack is W = 60 and the items are as shown in the following table."
},
{
"code": null,
"e": 4380,
"s": 4115,
"text": "Using the Greedy approach, first item A is selected. Then, the next item B is chosen. Hence, the total profit is 100 + 280 = 380. However, the optimal solution of this instance can be achieved by selecting items, B and C, where the total profit is 280 + 120 = 400."
},
{
"code": null,
"e": 4462,
"s": 4380,
"text": "Hence, it can be concluded that Greedy approach may not give an optimal solution."
},
{
"code": null,
"e": 4527,
"s": 4462,
"text": "To solve 0-1 Knapsack, Dynamic Programming approach is required."
},
{
"code": null,
"e": 4735,
"s": 4527,
"text": "A thief is robbing a store and can carry a maximal weight of W into his knapsack. There are n items and weight of ith item is wi and the profit of selecting this item is pi. What items should the thief take?"
},
{
"code": null,
"e": 4943,
"s": 4735,
"text": "Let i be the highest-numbered item in an optimal solution S for W dollars. Then S' = S - {i} is an optimal solution for W - wi dollars and the value to the solution S is Vi plus the value of the sub-problem."
},
{
"code": null,
"e": 5077,
"s": 4943,
"text": "We can express this fact in the following formula: define c[i, w] to be the solution for items 1,2, ... , i and the maximum weight w."
},
{
"code": null,
"e": 5118,
"s": 5077,
"text": "The algorithm takes the following inputs"
},
{
"code": null,
"e": 5139,
"s": 5118,
"text": "The maximum weight W"
},
{
"code": null,
"e": 5160,
"s": 5139,
"text": "The maximum weight W"
},
{
"code": null,
"e": 5182,
"s": 5160,
"text": "The number of items n"
},
{
"code": null,
"e": 5204,
"s": 5182,
"text": "The number of items n"
},
{
"code": null,
"e": 5270,
"s": 5204,
"text": "The two sequences v = <v1, v2, ..., vn> and w = <w1, w2, ..., wn>"
},
{
"code": null,
"e": 5336,
"s": 5270,
"text": "The two sequences v = <v1, v2, ..., vn> and w = <w1, w2, ..., wn>"
},
{
"code": null,
"e": 5640,
"s": 5336,
"text": "Dynamic-0-1-knapsack (v, w, n, W) \nfor w = 0 to W do \n c[0, w] = 0 \nfor i = 1 to n do \n c[i, 0] = 0 \n for w = 1 to W do \n if wi ≤ w then \n if vi + c[i-1, w-wi] then \n c[i, w] = vi + c[i-1, w-wi] \n else c[i, w] = c[i-1, w] \n else \n c[i, w] = c[i-1, w] \n"
},
{
"code": null,
"e": 5774,
"s": 5640,
"text": "The set of items to take can be deduced from the table, starting at c[n, w] and tracing backwards where the optimal values came from."
},
{
"code": null,
"e": 5964,
"s": 5774,
"text": "If c[i, w] = c[i-1, w], then item i is not part of the solution, and we continue tracing with c[i-1, w]. Otherwise, item i is part of the solution, and we continue tracing with c[i-1, w-W]."
},
{
"code": null,
"e": 6087,
"s": 5964,
"text": "This algorithm takes θ(n, w) times as table c has (n + 1).(w + 1) entries, where each entry requires θ(1) time to compute."
},
{
"code": null,
"e": 6122,
"s": 6087,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6141,
"s": 6122,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6174,
"s": 6141,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6193,
"s": 6174,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6226,
"s": 6193,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6245,
"s": 6226,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6280,
"s": 6245,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6293,
"s": 6280,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 6325,
"s": 6293,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6338,
"s": 6325,
"text": " Zach Miller"
},
{
"code": null,
"e": 6371,
"s": 6338,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6385,
"s": 6371,
"text": " Sasha Miller"
},
{
"code": null,
"e": 6392,
"s": 6385,
"text": " Print"
},
{
"code": null,
"e": 6403,
"s": 6392,
"text": " Add Notes"
}
] |
Convert Sorted Array to Binary Search Tree in Python
|
Suppose we have one sorted array A. We have to generate one height-balanced binary search. In this problem, a height-balanced binary tree is actually a binary tree in which the depth of the two subtrees of every node never differs by more than 1. Suppose the array is like [-10, -3, 0, 5, 9]. So one possible output will be like: [0, -3, 9, -10, null, 5]
To solve this, we will follow these steps.
If A is empty, then return Null
find the mid element, and make it root
Divide the array into two sub-arrays, left part of the mid element, and right part of the mid element
recursively perform the same task for the left subarray and right subarray.
Let us see the following implementation to get a better understanding −
Live Demo
class TreeNode:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def insert(temp,data):
que = []
que.append(temp)
while (len(que)):
temp = que[0]
que.pop(0)
if (not temp.left):
if data is not None:
temp.left = TreeNode(data)
else:
temp.left = TreeNode(0)
break
else:
que.append(temp.left)
if (not temp.right):
if data is not None:
temp.right = TreeNode(data)
else:
temp.right = TreeNode(0)
break
else:
que.append(temp.right)
def make_tree(elements):
Tree = TreeNode(elements[0])
for element in elements[1:]:
insert(Tree, element)
return Tree
def height(root):
if root is None:
return 0
else :
# Compute the height of left and right subtree
l_height = height(root.left)
r_height = height(root.right)
#Find the greater one, and return it
if l_height > r_height :
return l_height+1
else:
return r_height+1
def print_given_level(root, level):
if root is None:
return
if level == 1:
print(root.data,end = ',')
elif level > 1 :
print_given_level(root.left , level-1)
print_given_level(root.right , level-1)
def level_order(root):
print('[', end = '')
h = height(root)
for i in range(1, h+1):
print_given_level(root, i)
print(']')
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
mid = nums[len(nums)//2]
root = TreeNode(mid)
root.left = self.sortedArrayToBST(nums[:len(nums)//2])
root.right = self.sortedArrayToBST(nums[len(nums)//2 +1 :])
return root
nums = [-10,-3,0,5,9]
ob1 = Solution()
bst = ob1.sortedArrayToBST(nums)
level_order(bst)
nums = [-10,-3,0,5,9]
[0,-3,9,-10,5,]
|
[
{
"code": null,
"e": 1417,
"s": 1062,
"text": "Suppose we have one sorted array A. We have to generate one height-balanced binary search. In this problem, a height-balanced binary tree is actually a binary tree in which the depth of the two subtrees of every node never differs by more than 1. Suppose the array is like [-10, -3, 0, 5, 9]. So one possible output will be like: [0, -3, 9, -10, null, 5]"
},
{
"code": null,
"e": 1460,
"s": 1417,
"text": "To solve this, we will follow these steps."
},
{
"code": null,
"e": 1492,
"s": 1460,
"text": "If A is empty, then return Null"
},
{
"code": null,
"e": 1531,
"s": 1492,
"text": "find the mid element, and make it root"
},
{
"code": null,
"e": 1633,
"s": 1531,
"text": "Divide the array into two sub-arrays, left part of the mid element, and right part of the mid element"
},
{
"code": null,
"e": 1709,
"s": 1633,
"text": "recursively perform the same task for the left subarray and right subarray."
},
{
"code": null,
"e": 1781,
"s": 1709,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1792,
"s": 1781,
"text": " Live Demo"
},
{
"code": null,
"e": 3740,
"s": 1792,
"text": "class TreeNode:\n def __init__(self, data, left = None, right = None):\n self.data = data\n self.left = left\n self.right = right\ndef insert(temp,data):\n que = []\n que.append(temp)\n while (len(que)):\n temp = que[0]\n que.pop(0)\n if (not temp.left):\n if data is not None:\n temp.left = TreeNode(data)\n else:\n temp.left = TreeNode(0)\n break\n else:\n que.append(temp.left)\n if (not temp.right):\n if data is not None:\n temp.right = TreeNode(data)\n else:\n temp.right = TreeNode(0)\n break\n else:\n que.append(temp.right)\ndef make_tree(elements):\n Tree = TreeNode(elements[0])\n for element in elements[1:]:\n insert(Tree, element)\n return Tree\ndef height(root):\n if root is None:\n return 0\n else :\n # Compute the height of left and right subtree\n l_height = height(root.left)\n r_height = height(root.right)\n #Find the greater one, and return it\n if l_height > r_height :\n return l_height+1\n else:\n return r_height+1\ndef print_given_level(root, level):\n if root is None:\n return\n if level == 1:\n print(root.data,end = ',')\n elif level > 1 :\n print_given_level(root.left , level-1)\n print_given_level(root.right , level-1)\ndef level_order(root):\n print('[', end = '')\n h = height(root)\n for i in range(1, h+1):\n print_given_level(root, i)\n print(']')\nclass Solution(object):\n def sortedArrayToBST(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n if not nums:\n return None\n mid = nums[len(nums)//2]\n root = TreeNode(mid)\n root.left = self.sortedArrayToBST(nums[:len(nums)//2])\n root.right = self.sortedArrayToBST(nums[len(nums)//2 +1 :])\n return root\nnums = [-10,-3,0,5,9]\nob1 = Solution()\nbst = ob1.sortedArrayToBST(nums)\nlevel_order(bst)"
},
{
"code": null,
"e": 3762,
"s": 3740,
"text": "nums = [-10,-3,0,5,9]"
},
{
"code": null,
"e": 3778,
"s": 3762,
"text": "[0,-3,9,-10,5,]"
}
] |
Postfix to Infix - GeeksforGeeks
|
08 Jul, 2021
Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands. Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands. Postfix notation, also known as reverse Polish notation, is a syntax for mathematical expressions in which the mathematical operator is always placed after the operands. Though postfix expressions are easily and efficiently evaluated by computers, they can be difficult for humans to read. Complex expressions using standard parenthesized infix notation are often more readable than the corresponding postfix expressions. Consequently, we would sometimes like to allow end users to work with infix notation and then convert it to postfix notation for computer processing. Sometimes, moreover, expressions are stored or generated in postfix, and we would like to convert them to infix for the purpose of reading and editingExamples:
Input : abc++
Output : (a + (b + c))
Input : ab*c+
Output : ((a*b)+c)
We have already discussed Infix to Postfix. Below is algorithm for Postfix to Infix.Algorithm 1.While there are input symbol left ...1.1 Read the next symbol from the input. 2.If the symbol is an operand ...2.1 Push it onto the stack. 3.Otherwise, ...3.1 the symbol is an operator. ...3.2 Pop the top 2 values from the stack. ...3.3 Put the operator, with the values as arguments and form a string. ...3.4 Push the resulted string back to stack. 4.If there is only one value in the stack ...4.1 That value in the stack is the desired infix string. Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find infix for// a given postfix.#include <bits/stdc++.h>using namespace std; bool isOperand(char x){ return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');} // Get Infix for a given postfix// expressionstring getInfix(string exp){ stack<string> s; for (int i=0; exp[i]!='\0'; i++) { // Push operands if (isOperand(exp[i])) { string op(1, exp[i]); s.push(op); } // We assume that input is // a valid postfix and expect // an operator. else { string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); s.push("(" + op2 + exp[i] + op1 + ")"); } } // There must be a single element // in stack now which is the required // infix. return s.top();} // Driver codeint main(){ string exp = "ab*c+"; cout << getInfix(exp); return 0;}
// Java program to find infix for// a given postfix.import java.util.*; class GFG{ static boolean isOperand(char x){ return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');} // Get Infix for a given postfix// expressionstatic String getInfix(String exp){ Stack<String> s = new Stack<String>(); for (int i = 0; i < exp.length(); i++) { // Push operands if (isOperand(exp.charAt(i))) { s.push(exp.charAt(i) + ""); } // We assume that input is // a valid postfix and expect // an operator. else { String op1 = s.peek(); s.pop(); String op2 = s.peek(); s.pop(); s.push("(" + op2 + exp.charAt(i) + op1 + ")"); } } // There must be a single element // in stack now which is the required // infix. return s.peek();} // Driver codepublic static void main(String args[]){ String exp = "ab*c+"; System.out.println( getInfix(exp));}} // This code is contributed by Arnab Kundu
# Python3 program to find infix for# a given postfix.def isOperand(x): return ((x >= 'a' and x <= 'z') or (x >= 'A' and x <= 'Z')) # Get Infix for a given postfix# expressiondef getInfix(exp) : s = [] for i in exp: # Push operands if (isOperand(i)) : s.insert(0, i) # We assume that input is a # valid postfix and expect # an operator. else: op1 = s[0] s.pop(0) op2 = s[0] s.pop(0) s.insert(0, "(" + op2 + i + op1 + ")") # There must be a single element in # stack now which is the required # infix. return s[0] # Driver Codeif __name__ == '__main__': exp = "ab*c+" print(getInfix(exp.strip())) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program to find infix for// a given postfix.using System;using System.Collections; class GFG{ static Boolean isOperand(char x){ return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');} // Get Infix for a given postfix// expressionstatic String getInfix(String exp){ Stack s = new Stack(); for (int i = 0; i < exp.Length; i++) { // Push operands if (isOperand(exp[i])) { s.Push(exp[i] + ""); } // We assume that input is // a valid postfix and expect // an operator. else { String op1 = (String) s.Peek(); s.Pop(); String op2 = (String) s.Peek(); s.Pop(); s.Push("(" + op2 + exp[i] + op1 + ")"); } } // There must be a single element // in stack now which is the required // infix. return (String)s.Peek();} // Driver codepublic static void Main(String []args){ String exp = "ab*c+"; Console.WriteLine( getInfix(exp));}} // This code is contributed by Arnab Kundu
<?php class Stack { protected $stack; protected $limit; function CreateStack($limit){ $this->stack = array(); $this->limit = $limit; } function push($item) { // trap for stack overflow if (count($this->stack) < $this->limit) { // prepend item to the start of the array array_unshift($this->stack, $item); } else { throw new RunTimeException('Stack is full!'); } } function pop() { if ($this->isEmpty()) { // trap for stack underflow throw new RunTimeException('Stack is empty!'); } else { // pop item from the start of the array return array_shift($this->stack); } } function top() { return current($this->stack); } function isEmpty() { return empty($this->stack); } function Prec($ch) { switch ($ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } function isOperand($ch) { return ($ch >= 'a' && $ch <= 'z') || ($ch >= 'A' && $ch <= 'Z'); } function isOperator($x) { switch ($x) { case '+': case '-': case '/': case '*': return true; } return false; } public function getInfix($exp) { $this->CreateStack(sizeof($exp)); for ($i=0; $exp[$i]!= null; $i++) { // Push operands if ($this->isOperand($exp[$i])) { $op = $exp[$i]; $this->push($op); } // We assume that input is // a valid postfix and expect // an operator. else { $op1 = $this->top(); $this->pop(); $op2 = $this->top(); $this->pop(); $this->push("(". $op2 . $exp[$i] . $op1 . ")"); //$this->push($temp); } } // There must be a single element // in stack now which is the required // infix. return $this->top();}}$myExample = new Stack();echo $input = "ab*c+";$exp = str_split($input,sizeof($input));echo '<br>'.$data = $myExample->getInfix($exp);?>
<script> // JavaScript program to find infix for// a given postfix. function isOperand(x){ return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');} // Get Infix for a given postfix// expressionfunction getInfix(exp){ let s = []; for (let i = 0; i < exp.length; i++) { // Push operands if (isOperand(exp[i])) { s.push(exp[i] + ""); } // We assume that input is // a valid postfix and expect // an operator. else { let op1 = s.pop(); let op2 = s.pop(); s.pop(); s.push("(" + op2 + exp[i] + op1 + ")"); } } // There must be a single element // in stack now which is the required // infix. return s[s.length-1];} // Driver codelet exp = "ab*c+";document.write( getInfix(exp)); // This code is contributed by avanitrachhadiya2155 </script>
((a*b)+c)
AakashChandrakantAware
andrew1234
SHUBHAMSINGH10
avanitrachhadiya2155
expression-evaluation
Mathematical
Stack
Strings
Strings
Mathematical
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Inorder Tree Traversal without Recursion
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 24593,
"s": 24565,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 25547,
"s": 24593,
"text": "Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands. Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands. Postfix notation, also known as reverse Polish notation, is a syntax for mathematical expressions in which the mathematical operator is always placed after the operands. Though postfix expressions are easily and efficiently evaluated by computers, they can be difficult for humans to read. Complex expressions using standard parenthesized infix notation are often more readable than the corresponding postfix expressions. Consequently, we would sometimes like to allow end users to work with infix notation and then convert it to postfix notation for computer processing. Sometimes, moreover, expressions are stored or generated in postfix, and we would like to convert them to infix for the purpose of reading and editingExamples: "
},
{
"code": null,
"e": 25619,
"s": 25547,
"text": "Input : abc++\nOutput : (a + (b + c))\n\nInput : ab*c+\nOutput : ((a*b)+c)"
},
{
"code": null,
"e": 26218,
"s": 25621,
"text": "We have already discussed Infix to Postfix. Below is algorithm for Postfix to Infix.Algorithm 1.While there are input symbol left ...1.1 Read the next symbol from the input. 2.If the symbol is an operand ...2.1 Push it onto the stack. 3.Otherwise, ...3.1 the symbol is an operator. ...3.2 Pop the top 2 values from the stack. ...3.3 Put the operator, with the values as arguments and form a string. ...3.4 Push the resulted string back to stack. 4.If there is only one value in the stack ...4.1 That value in the stack is the desired infix string. Below is the implementation of above approach: "
},
{
"code": null,
"e": 26222,
"s": 26218,
"text": "C++"
},
{
"code": null,
"e": 26227,
"s": 26222,
"text": "Java"
},
{
"code": null,
"e": 26235,
"s": 26227,
"text": "Python3"
},
{
"code": null,
"e": 26238,
"s": 26235,
"text": "C#"
},
{
"code": null,
"e": 26242,
"s": 26238,
"text": "PHP"
},
{
"code": null,
"e": 26253,
"s": 26242,
"text": "Javascript"
},
{
"code": "// CPP program to find infix for// a given postfix.#include <bits/stdc++.h>using namespace std; bool isOperand(char x){ return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');} // Get Infix for a given postfix// expressionstring getInfix(string exp){ stack<string> s; for (int i=0; exp[i]!='\\0'; i++) { // Push operands if (isOperand(exp[i])) { string op(1, exp[i]); s.push(op); } // We assume that input is // a valid postfix and expect // an operator. else { string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); s.push(\"(\" + op2 + exp[i] + op1 + \")\"); } } // There must be a single element // in stack now which is the required // infix. return s.top();} // Driver codeint main(){ string exp = \"ab*c+\"; cout << getInfix(exp); return 0;}",
"e": 27212,
"s": 26253,
"text": null
},
{
"code": "// Java program to find infix for// a given postfix.import java.util.*; class GFG{ static boolean isOperand(char x){ return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');} // Get Infix for a given postfix// expressionstatic String getInfix(String exp){ Stack<String> s = new Stack<String>(); for (int i = 0; i < exp.length(); i++) { // Push operands if (isOperand(exp.charAt(i))) { s.push(exp.charAt(i) + \"\"); } // We assume that input is // a valid postfix and expect // an operator. else { String op1 = s.peek(); s.pop(); String op2 = s.peek(); s.pop(); s.push(\"(\" + op2 + exp.charAt(i) + op1 + \")\"); } } // There must be a single element // in stack now which is the required // infix. return s.peek();} // Driver codepublic static void main(String args[]){ String exp = \"ab*c+\"; System.out.println( getInfix(exp));}} // This code is contributed by Arnab Kundu",
"e": 28281,
"s": 27212,
"text": null
},
{
"code": "# Python3 program to find infix for# a given postfix.def isOperand(x): return ((x >= 'a' and x <= 'z') or (x >= 'A' and x <= 'Z')) # Get Infix for a given postfix# expressiondef getInfix(exp) : s = [] for i in exp: # Push operands if (isOperand(i)) : s.insert(0, i) # We assume that input is a # valid postfix and expect # an operator. else: op1 = s[0] s.pop(0) op2 = s[0] s.pop(0) s.insert(0, \"(\" + op2 + i + op1 + \")\") # There must be a single element in # stack now which is the required # infix. return s[0] # Driver Codeif __name__ == '__main__': exp = \"ab*c+\" print(getInfix(exp.strip())) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 29170,
"s": 28281,
"text": null
},
{
"code": "// C# program to find infix for// a given postfix.using System;using System.Collections; class GFG{ static Boolean isOperand(char x){ return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');} // Get Infix for a given postfix// expressionstatic String getInfix(String exp){ Stack s = new Stack(); for (int i = 0; i < exp.Length; i++) { // Push operands if (isOperand(exp[i])) { s.Push(exp[i] + \"\"); } // We assume that input is // a valid postfix and expect // an operator. else { String op1 = (String) s.Peek(); s.Pop(); String op2 = (String) s.Peek(); s.Pop(); s.Push(\"(\" + op2 + exp[i] + op1 + \")\"); } } // There must be a single element // in stack now which is the required // infix. return (String)s.Peek();} // Driver codepublic static void Main(String []args){ String exp = \"ab*c+\"; Console.WriteLine( getInfix(exp));}} // This code is contributed by Arnab Kundu",
"e": 30246,
"s": 29170,
"text": null
},
{
"code": "<?php class Stack { protected $stack; protected $limit; function CreateStack($limit){ $this->stack = array(); $this->limit = $limit; } function push($item) { // trap for stack overflow if (count($this->stack) < $this->limit) { // prepend item to the start of the array array_unshift($this->stack, $item); } else { throw new RunTimeException('Stack is full!'); } } function pop() { if ($this->isEmpty()) { // trap for stack underflow throw new RunTimeException('Stack is empty!'); } else { // pop item from the start of the array return array_shift($this->stack); } } function top() { return current($this->stack); } function isEmpty() { return empty($this->stack); } function Prec($ch) { switch ($ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } function isOperand($ch) { return ($ch >= 'a' && $ch <= 'z') || ($ch >= 'A' && $ch <= 'Z'); } function isOperator($x) { switch ($x) { case '+': case '-': case '/': case '*': return true; } return false; } public function getInfix($exp) { $this->CreateStack(sizeof($exp)); for ($i=0; $exp[$i]!= null; $i++) { // Push operands if ($this->isOperand($exp[$i])) { $op = $exp[$i]; $this->push($op); } // We assume that input is // a valid postfix and expect // an operator. else { $op1 = $this->top(); $this->pop(); $op2 = $this->top(); $this->pop(); $this->push(\"(\". $op2 . $exp[$i] . $op1 . \")\"); //$this->push($temp); } } // There must be a single element // in stack now which is the required // infix. return $this->top();}}$myExample = new Stack();echo $input = \"ab*c+\";$exp = str_split($input,sizeof($input));echo '<br>'.$data = $myExample->getInfix($exp);?>",
"e": 32519,
"s": 30246,
"text": null
},
{
"code": "<script> // JavaScript program to find infix for// a given postfix. function isOperand(x){ return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');} // Get Infix for a given postfix// expressionfunction getInfix(exp){ let s = []; for (let i = 0; i < exp.length; i++) { // Push operands if (isOperand(exp[i])) { s.push(exp[i] + \"\"); } // We assume that input is // a valid postfix and expect // an operator. else { let op1 = s.pop(); let op2 = s.pop(); s.pop(); s.push(\"(\" + op2 + exp[i] + op1 + \")\"); } } // There must be a single element // in stack now which is the required // infix. return s[s.length-1];} // Driver codelet exp = \"ab*c+\";document.write( getInfix(exp)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 33456,
"s": 32519,
"text": null
},
{
"code": null,
"e": 33466,
"s": 33456,
"text": "((a*b)+c)"
},
{
"code": null,
"e": 33491,
"s": 33468,
"text": "AakashChandrakantAware"
},
{
"code": null,
"e": 33502,
"s": 33491,
"text": "andrew1234"
},
{
"code": null,
"e": 33517,
"s": 33502,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 33538,
"s": 33517,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 33560,
"s": 33538,
"text": "expression-evaluation"
},
{
"code": null,
"e": 33573,
"s": 33560,
"text": "Mathematical"
},
{
"code": null,
"e": 33579,
"s": 33573,
"text": "Stack"
},
{
"code": null,
"e": 33587,
"s": 33579,
"text": "Strings"
},
{
"code": null,
"e": 33595,
"s": 33587,
"text": "Strings"
},
{
"code": null,
"e": 33608,
"s": 33595,
"text": "Mathematical"
},
{
"code": null,
"e": 33614,
"s": 33608,
"text": "Stack"
},
{
"code": null,
"e": 33712,
"s": 33614,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33721,
"s": 33712,
"text": "Comments"
},
{
"code": null,
"e": 33734,
"s": 33721,
"text": "Old Comments"
},
{
"code": null,
"e": 33758,
"s": 33734,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33801,
"s": 33758,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33815,
"s": 33801,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33860,
"s": 33815,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 33909,
"s": 33860,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33957,
"s": 33909,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33977,
"s": 33957,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 33993,
"s": 33977,
"text": "Stack in Python"
},
{
"code": null,
"e": 34034,
"s": 33993,
"text": "Inorder Tree Traversal without Recursion"
}
] |
An open-source solution to deploy enterprise-level R Shiny applications | by Mingchu Xu | Towards Data Science
|
For many R users, R Shiny has become a popular platform to build interactive web applications for data science. It allows people to easily visualize data analysis from R without messing with many lines of code. You can explore some powerful and visually attractive apps in R Shiny Gallery.
As a bioinformatics scientist, I provide biologists with state-of-the-art data analysis and visualization solutions of high-throughput experimental data. With the number of collaborators growing, I need to build a host of R Shiny apps to ensure a modularized, standardized, and reproducible workflow. However, if I want to scale up my project and put the system to wider use, I have to face several questions:
How to run R Shiny apps on remote computer or cloud smoothly?How to deploy and manage multiple R Shiny apps from a single portal?How can R Shiny apps dynamically read and write files in the host system?Within R Shiny apps, can different users access different datasets?
How to run R Shiny apps on remote computer or cloud smoothly?
How to deploy and manage multiple R Shiny apps from a single portal?
How can R Shiny apps dynamically read and write files in the host system?
Within R Shiny apps, can different users access different datasets?
These can certainly be achieved by Shiny Server Pro provided by RStudio. Nevertheless, I searched online resources, went through trials and errors, and found docker + ShinyProxy as a nice open-source solution, which enabled me to successfully deploy a fleet of R Shiny apps with the desired functionalities.
While the whole process is not technically demanding, I haven’t seen a step-by-step tutorial on how to build these from scratch. Here, I aim to show you the journey of deploying two example R Shiny apps with user-specific data access, and hopefully, it would inspire your projects.
📝 Note: This tutorial describes how to deploy the multi-app system on a local computer. But the steps can be generally applied to the deployment on a remote computer or the cloud. I will include special notes when cautions are needed for the remote deployment.
i️ All the files needed in this tutorial are hosted on my GitHub repository. There are five numbered subdirectories in the repo, corresponding to the five steps (Section 02–06) in this tutorial of building the final system. As we go through the tutorial, I’ll also show you the links to the specific folders or files.
We should have already installed R and RStudio. To build our example R Shiny apps, we also need to install shiny and tidyverseby calling install.packages().
Next, we will install docker. Since I am using macOS, I used this link to install Docker Desktop. To install it on other operating systems, you can find information here.
Why do we use docker?
The philosophy of docker is to encapsulate software code and all its dependencies so that it can run uniformly and consistently on any infrastructure, namely, the containerization strategy. R Shiny apps usually have many package dependencies. We’ll first test its running on a local computer and then make them work remotely. Without containerization by docker, we’ll have to make sure all the computers that run the apps have the same running environment. That means we’ll spend much effort installing and configuring numerous software and packages. And when a package gets updated on the test computer, it has to be updated in all the other ones. We can see it will easily become painful to manage multiple R shiny apps in this way. With docker, we can pack the apps, their dependencies, and the running environment as a whole image. The image can be copied to other computers and we can just start running the apps (as long as that computer has docker installed). Without being disrupted by tedious installations and configurations, this type of practice greatly speeds up the workflow of software development and deployment.
Since this is just a proof-of-concept tutorial, we’ll build two simple R Shiny apps. They can be easily scaled up for your larger projects since the general structure and filesystems are the same.
The first app “Hist_App” reads a numeric vector stored in a file and plots its distribution. As shown in Figure 1, we can choose one of the four datasets and adjust the number of bins. ( 💻 Source files)
The second app “Scatter_App” reads a two-column dataframe stored in a file and draws the scatter plot of the two variables. Similarly, we can choose one of the four datasets and change the color of the points. ( 💻 Source files). In both apps, the data files are located in the./data/ folder.
We can test these two apps locally by clicking “Run App” in the RStudio when we open the app.R file.
Now we have built two R Shiny apps, but they can only run on our local machines. To make them work on other computers, we’ll take advantage of the docker containerization strategy I’ve explained above to build docker images.
To build a docker image, we need a base image to start with. We can copy files and install additional software or packages into the base image to build a new image. Docker Hub is a place where numerous pre-built docker images are publicly available. There is a community repository called ‘rocker’ that routinely updates common R-related docker images. The image we’ll use is rocker/shiny-verse . We use the following command in the terminal to pull the image to the local machine:
docker pull rocker/shiny-verse
As you may guess, rocker/shiny-verse is an environment already installed with R, R Shiny server, and several common packages including tidyverse. rocker/shiny-verse is built upon its base image rocker/shiny by installing tidyverse etc.. rocker/shiny is again built from rocker/r-ver, which is the base R environment. Now you can see how it works: the docker image is built layer by layer. When we need to build a docker image, we don’t start from scratch (e.g. from the base operating system, or base R). We can just start with something pre-cooked and add our recipe on top of that. The figure below tries to explain this concept.
Usually, we need additional R packages to run our apps. Hence, we can install those packages on top of rocker/shiny-verse to build a shiny-more image. And finally, app files are copied and configured to build the shiny-app image that ready for running. Fortunately, our two apps don’t require more R packages, thus the shiny-more image is not necessary. We can directly build shiny-app from rocker/shiny-verse.
📝 Note: Though the step from rocker/shiny-verse to shiny-more is skipped in this tutorial, I included the files needed to build this intermediate image in the GitHub since you’ll need them. Technically, one can still go directly from rocker/shiny-verse to shiny-app even if more packages are needed, but by doing it this way, every time the app gets updated, it takes minutes to install all the packages again. Therefore, the best practice is to build the images layer by layer.
We need two files to build the shiny-app image: Dockerfile, which is always needed to build a docker image; shiny-server.sh, which runs the R Shiny server. As you can see from the GitHub directory, in the folder of each app, these two files are added on top of previous files. Now, in the terminal, within the ./Hist_App folder, run the following command:
docker build . -t shiny-hist
This will build the shiny-hist image from rocker/shiny-verse. The base image is specified in the first line of Dockerfile: FROM rocker/shiny-verse:latest. The remaining lines are just commands to ask docker to do copying/installations/configurations. In the terminal, run docker images. Now we should see both rocker/shiny-verse and shiny-hist are there. Then, run:
docker run --rm -p 3838:3838 shiny-hist
This will start our histogram app on the computer at port 3838. Open the web browser, and go to localhost:3838. We’ll have an R Shiny app running in docker!
The steps are the same to run the scatterplot app: within the ./Scatter_App folder, run docker build . -t shiny-scatter (remember to change the image tag), and run docker run —-rm -p 3838:3838 shiny-scatter. The scatterplot app will be accessed at port 3838.
Now, we can run R Shiny app docker images on the local computer. But how to make them run on the remote machines? You may notice that rocker/shiny-verse has a rocker/ part. This is the repository name on the Docker Hub. The shiny-hist and shiny-scatter we’ve built are just local images and have not been pushed to Docker Hub. To make a push, sign up a Docker Hub account and login through the Docker Desktop or in the terminal:
docker login -u "username" docker.io
After re-tagging the apps with the repository name, we can push our docker images online:
docker tag shiny-hist username/shiny-hist docker tag shiny-scatter username/shiny-scatterdocker push username/shiny-histdocker push username/shiny-scatter
On other computers with docker installed, we can just pull the images to the local and run the apps.
We’ve already built two R Shiny apps and can utilize docker to deploy them on different computers easily. The next challenge is: how we can access and manage multiple apps from a single portal and add authentication to different users. This is when ShinyProxy comes into play. ShinyProxy is an open-source solution specifically developed to combine R Shiny and docker and provide additional multi-app functionalities including user authentication (even LDAP authentication). This allows a series of R Shiny apps to be deployed and used by multiple users in an enterprise context.
Let’s say we want to access the two apps we’ve built from a single web page and only two users are allowed to log in: Alice and Bob. To achieve this, we need to have three new files in the same folder. Two files Dockerfile and application.yaml are in the GitHub directory. We should also download the shinyproxy-2.3.1.jar file from the ShinyProxy download page since it is a large file.
Before building the ShinyProxy image and running the apps, we should take a look at the application.yaml file to understand how it is configured to run. The lineauthentication: simple indicates we can directly set the usernames and passwords in the user section. Here, two users (“Alice”, “Bob”), and their passwords are set. The R Shiny docker images are configured in the specs section: we can set the ID, display name, and descriptions of the apps, and most importantly, container-image should be shiny-hist or shiny-scatter, so ShinyProxy knows to run the correct image.
Another new concept is the docker network. This makes docker more powerful by connecting multiple containers. We can see in the application.yaml that docker: internal-networking: true and each image has container-network: sp-test-net. It makes the two apps run in a single docker network and managed by ShinyProxy. Moreover, ShinyProxy itself can run as a container. This section aims to build a total image that entails shiny-hist, shiny-scatter, and ShinyProxy all together. Again, anything can be packed and run as a container! The following figure illustrates the ShinyProxy design:
Therefore, before building the ShinyProxy image, we need to build the docker network first:
docker network create sp-test-net
📝 Note: If you try to build a docker network on a remote server, especially when using a VPN, you may need to specify the IP subnet mask to avoid IP address conflicts. The command I used is docker network create --driver=bridge --subnet 172.17.253.9/30 sp-test-net. Please see this link for detailed explanations.
The network name should be the same as the one we specified in application.yaml. Next, we build the ShinyProxy image to connect multiple R Shiny apps (The command should be run in the directory with application.yaml, shinyproxy-2.3.1.jar, and Dockerfile):
docker build . -t shinyproxy-run
Finally, we run the shinyproxy-run and go to localhost:8080 on the web browser to see the results:
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock --net sp-test-net -p 8080:8080 shinyproxy-run
We should see a login page. By logging in with “Alice” or “Bob” and passwords, we are directed to the portal page with the two apps available.
📝 Note: There are lots of options to configure in the application.yaml file to exert the full potential of ShinyProxy. Detailed documentation can be found on this page.
Having finished the previous steps, we can now deploy and manage multiple R Shiny apps from a single portal. But there is another flaw in our multi-app system: Currently, all the datasets are stored within the ./data folder of each app. This presents a difficulty for dynamic data access. If the datasets used by R Shiny apps are updated, we have to re-build the corresponding app docker image to make the new data accessible to the user. When the updates are frequent, it becomes infeasible to let users see instant data changes. Moreover, we may also want the apps to generate files in the host system, which is impossible if the docker container can only manipulate itself. Fortunately, docker can use volume to create a “docker area” in the host machine and mount it to the container, hence the container can access and manipulate the files in the host system.
To explore this feature, we should first move the data files out of the app folder. The tree structure of the previous section is like below:
04-shinyproxy/├── Dockerfile├── Hist_App│ ├── Dockerfile│ ├── Hist_App.Rproj│ ├── app.R│ ├── data│ │ ├── alice_vector_1.txt│ │ ├── alice_vector_2.txt│ │ ├── bob_vector_1.txt│ │ └── bob_vector_2.txt│ └── shiny-server.sh├── Scatter_App│ ├── Dockerfile│ ├── Scatter_App.Rproj│ ├── app.R│ ├── data│ │ ├── alice_df_1.txt│ │ ├── alice_df_2.txt│ │ ├── bob_df_1.txt│ │ └── bob_df_2.txt│ └── shiny-server.sh├── application.yml└── shinyproxy-2.3.1.jar
Let’s re-organize the structure by creating a directory outside of the app folders for storing the data files used by both apps:
05-data-on-host/├── Data│ ├── DF│ │ ├── alice_df_1.txt│ │ ├── alice_df_2.txt│ │ ├── bob_df_1.txt│ │ └── bob_df_2.txt│ └── Vector│ ├── alice_vector_1.txt│ ├── alice_vector_2.txt│ ├── bob_vector_1.txt│ └── bob_vector_2.txt├── Dockerfile├── Hist_App│ ├── Dockerfile│ ├── Hist_App.Rproj│ ├── app.R│ └── shiny-server.sh├── Scatter_App│ ├── Dockerfile│ ├── Scatter_App.Rproj│ ├── app.R│ └── shiny-server.sh├── application.yml└── shinyproxy-2.3.1.jar
Now if we try to run docker build in the ./Hist_App folder for the histogram app, there will be errors, since the ./Hist_App/data folder no longer exists. Instead, we should make changes in the Dockerfile and app.R (See the exact changes here).
We first deleted the lineCOPY data /srv/shiny-server/data in the Dockerfile, then changed the ./data/ to /Data/Vector/ in the app.R to tell the app that the data files are now stored at a different location. After rebuilding the docker image with a different tag:
# within ./Hist_App folderdocker build . -t shiny-hist-data
We run the following command:
docker run --rm -v /Users/mingchuxu/Documents/projects/ShinyProxy-template/05-data-on-host/Data/:/Data -p 3838:3838 shiny-hist-data## Note: The absolute path to /Data in your computer is different, please change it accordingly.
We can see the histogram app runs on localhost:3838 successfully. How does the app know the right location of data files? The trick is from the -v option in the command above. This option tells docker that we want to mount the host directory/Users/mingchuxu/Documents/projects/ShinyProxy-template/05-data-on-hist/Data as the /Data in the container (The option accepts the <host-dir>:<container-dir> format). That’s why when we specify /Data/Vector/ in the app.R, the histogram app knows to go to /Users/mingchuxu/Documents/projects/ShinyProxy-template/05-data-on-hist/Data/Vector in the host system to find the data files.
We can make the same changes in the scatterplot folder (See the exact changes here), build a new docker image, and run it with the host directory mounted. The scatterplot app should also be running at localhost:3838:
# within ./Scatter_App folderdocker build . -t shiny-scatter-datadocker run --rm -v /Users/mingchuxu/Documents/projects/ShinyProxy-template/05-data-on-host/Data/:/Data -p 3838:3838 shiny-scatter-data## Note: The absolute path to /Data in your computer is different, please change it accordingly.
The next step is to combine the docker volume feature with ShinyProxy. In application.yaml, the option container-volumes is equivalent to the -v option in docker run, allowing us to configure it accordingly. Let’s modify the application.yaml file (See the exact changes here), then build and run a new ShinyProxy image:
docker build . -t shinyproxy-run-datadocker run --rm -v /var/run/docker.sock:/var/run/docker.sock --net sp-test-net -p 8080:8080 shinyproxy-run-data
Now from localhost:8080, we can run multiple R Shiny apps that read data from our host machine. The following figure illustrates the improved design compared with Figure 4. We are free to move the ./Data folder to anywhere on our computer. Just remember to modify the container-volumes option in application.yaml each time we change the absolute path and rebuild the ShinyProxy image.
Having finished the previous steps, we are now facing the last problem: how to make Alice and Bob access user-specific data? This can be solved by utilizing the environment variable created upon ShinyProxy login: SHINYPROXY_USERNAME.
First, let’s add one more level to the hierarchy of Data/ folder. As shown in the tree structure below, alice*txt are put into Alice/ and bob*txt into Bob/. This allows R Shiny apps to access different folders based on different ShinyProxy login usernames.
Data├── DF│ ├── Alice│ │ ├── alice_df_1.txt│ │ └── alice_df_2.txt│ └── Bob│ ├── bob_df_1.txt│ └── bob_df_2.txt└── Vector ├── Alice │ ├── alice_vector_1.txt │ └── alice_vector_2.txt └── Bob ├── bob_vector_1.txt └── bob_vector_2.txt
Next, we should make a series of modifications. Please see this GitHub commit for all the changes needed. Specifically, in the app.R file of each app, we need to add username <- Sys.getenv("SHINYPROXY_USERNAME") to get the login username, and modify the directory path by paste0() in both ui and server; in the shiny-server.sh file of each app, we should add the following two lines to pass the environment variable into the R Shiny app (explained in details here):
env > /home/shiny/.Renvironchown shiny.shiny /home/shiny/.Renviron
Then, as in Section 05, we will build new docker images for each app. Again, we use new docker image tags to distinguish them from images built in previous sections.
# within ./Hist_App folderdocker build . -t shiny-hist-user# within ./Scatter_App folderdocker build . -t shiny-scatter-user
Before building the final ShinyProxy image, we also need to modify the applicaiton.yaml since the docker images and volumes have all changed (See the exact changes here).
Finally, with the following commands:
docker build . -t shinyproxy-run-user # Note the tag name changedocker run --rm -v /var/run/docker.sock:/var/run/docker.sock --net sp-test-net -p 8080:8080 shinyproxy-run-user
We can check out localhost:8080 and see that Bob can only access files in the Bob/ folder now. Finally, we built a simple prototype of R Shiny app series allowing user authentication and user-specific data access!
|
[
{
"code": null,
"e": 461,
"s": 171,
"text": "For many R users, R Shiny has become a popular platform to build interactive web applications for data science. It allows people to easily visualize data analysis from R without messing with many lines of code. You can explore some powerful and visually attractive apps in R Shiny Gallery."
},
{
"code": null,
"e": 871,
"s": 461,
"text": "As a bioinformatics scientist, I provide biologists with state-of-the-art data analysis and visualization solutions of high-throughput experimental data. With the number of collaborators growing, I need to build a host of R Shiny apps to ensure a modularized, standardized, and reproducible workflow. However, if I want to scale up my project and put the system to wider use, I have to face several questions:"
},
{
"code": null,
"e": 1141,
"s": 871,
"text": "How to run R Shiny apps on remote computer or cloud smoothly?How to deploy and manage multiple R Shiny apps from a single portal?How can R Shiny apps dynamically read and write files in the host system?Within R Shiny apps, can different users access different datasets?"
},
{
"code": null,
"e": 1203,
"s": 1141,
"text": "How to run R Shiny apps on remote computer or cloud smoothly?"
},
{
"code": null,
"e": 1272,
"s": 1203,
"text": "How to deploy and manage multiple R Shiny apps from a single portal?"
},
{
"code": null,
"e": 1346,
"s": 1272,
"text": "How can R Shiny apps dynamically read and write files in the host system?"
},
{
"code": null,
"e": 1414,
"s": 1346,
"text": "Within R Shiny apps, can different users access different datasets?"
},
{
"code": null,
"e": 1722,
"s": 1414,
"text": "These can certainly be achieved by Shiny Server Pro provided by RStudio. Nevertheless, I searched online resources, went through trials and errors, and found docker + ShinyProxy as a nice open-source solution, which enabled me to successfully deploy a fleet of R Shiny apps with the desired functionalities."
},
{
"code": null,
"e": 2004,
"s": 1722,
"text": "While the whole process is not technically demanding, I haven’t seen a step-by-step tutorial on how to build these from scratch. Here, I aim to show you the journey of deploying two example R Shiny apps with user-specific data access, and hopefully, it would inspire your projects."
},
{
"code": null,
"e": 2265,
"s": 2004,
"text": "📝 Note: This tutorial describes how to deploy the multi-app system on a local computer. But the steps can be generally applied to the deployment on a remote computer or the cloud. I will include special notes when cautions are needed for the remote deployment."
},
{
"code": null,
"e": 2583,
"s": 2265,
"text": "i️ All the files needed in this tutorial are hosted on my GitHub repository. There are five numbered subdirectories in the repo, corresponding to the five steps (Section 02–06) in this tutorial of building the final system. As we go through the tutorial, I’ll also show you the links to the specific folders or files."
},
{
"code": null,
"e": 2740,
"s": 2583,
"text": "We should have already installed R and RStudio. To build our example R Shiny apps, we also need to install shiny and tidyverseby calling install.packages()."
},
{
"code": null,
"e": 2911,
"s": 2740,
"text": "Next, we will install docker. Since I am using macOS, I used this link to install Docker Desktop. To install it on other operating systems, you can find information here."
},
{
"code": null,
"e": 2933,
"s": 2911,
"text": "Why do we use docker?"
},
{
"code": null,
"e": 4062,
"s": 2933,
"text": "The philosophy of docker is to encapsulate software code and all its dependencies so that it can run uniformly and consistently on any infrastructure, namely, the containerization strategy. R Shiny apps usually have many package dependencies. We’ll first test its running on a local computer and then make them work remotely. Without containerization by docker, we’ll have to make sure all the computers that run the apps have the same running environment. That means we’ll spend much effort installing and configuring numerous software and packages. And when a package gets updated on the test computer, it has to be updated in all the other ones. We can see it will easily become painful to manage multiple R shiny apps in this way. With docker, we can pack the apps, their dependencies, and the running environment as a whole image. The image can be copied to other computers and we can just start running the apps (as long as that computer has docker installed). Without being disrupted by tedious installations and configurations, this type of practice greatly speeds up the workflow of software development and deployment."
},
{
"code": null,
"e": 4259,
"s": 4062,
"text": "Since this is just a proof-of-concept tutorial, we’ll build two simple R Shiny apps. They can be easily scaled up for your larger projects since the general structure and filesystems are the same."
},
{
"code": null,
"e": 4462,
"s": 4259,
"text": "The first app “Hist_App” reads a numeric vector stored in a file and plots its distribution. As shown in Figure 1, we can choose one of the four datasets and adjust the number of bins. ( 💻 Source files)"
},
{
"code": null,
"e": 4754,
"s": 4462,
"text": "The second app “Scatter_App” reads a two-column dataframe stored in a file and draws the scatter plot of the two variables. Similarly, we can choose one of the four datasets and change the color of the points. ( 💻 Source files). In both apps, the data files are located in the./data/ folder."
},
{
"code": null,
"e": 4855,
"s": 4754,
"text": "We can test these two apps locally by clicking “Run App” in the RStudio when we open the app.R file."
},
{
"code": null,
"e": 5080,
"s": 4855,
"text": "Now we have built two R Shiny apps, but they can only run on our local machines. To make them work on other computers, we’ll take advantage of the docker containerization strategy I’ve explained above to build docker images."
},
{
"code": null,
"e": 5562,
"s": 5080,
"text": "To build a docker image, we need a base image to start with. We can copy files and install additional software or packages into the base image to build a new image. Docker Hub is a place where numerous pre-built docker images are publicly available. There is a community repository called ‘rocker’ that routinely updates common R-related docker images. The image we’ll use is rocker/shiny-verse . We use the following command in the terminal to pull the image to the local machine:"
},
{
"code": null,
"e": 5593,
"s": 5562,
"text": "docker pull rocker/shiny-verse"
},
{
"code": null,
"e": 6225,
"s": 5593,
"text": "As you may guess, rocker/shiny-verse is an environment already installed with R, R Shiny server, and several common packages including tidyverse. rocker/shiny-verse is built upon its base image rocker/shiny by installing tidyverse etc.. rocker/shiny is again built from rocker/r-ver, which is the base R environment. Now you can see how it works: the docker image is built layer by layer. When we need to build a docker image, we don’t start from scratch (e.g. from the base operating system, or base R). We can just start with something pre-cooked and add our recipe on top of that. The figure below tries to explain this concept."
},
{
"code": null,
"e": 6636,
"s": 6225,
"text": "Usually, we need additional R packages to run our apps. Hence, we can install those packages on top of rocker/shiny-verse to build a shiny-more image. And finally, app files are copied and configured to build the shiny-app image that ready for running. Fortunately, our two apps don’t require more R packages, thus the shiny-more image is not necessary. We can directly build shiny-app from rocker/shiny-verse."
},
{
"code": null,
"e": 7115,
"s": 6636,
"text": "📝 Note: Though the step from rocker/shiny-verse to shiny-more is skipped in this tutorial, I included the files needed to build this intermediate image in the GitHub since you’ll need them. Technically, one can still go directly from rocker/shiny-verse to shiny-app even if more packages are needed, but by doing it this way, every time the app gets updated, it takes minutes to install all the packages again. Therefore, the best practice is to build the images layer by layer."
},
{
"code": null,
"e": 7471,
"s": 7115,
"text": "We need two files to build the shiny-app image: Dockerfile, which is always needed to build a docker image; shiny-server.sh, which runs the R Shiny server. As you can see from the GitHub directory, in the folder of each app, these two files are added on top of previous files. Now, in the terminal, within the ./Hist_App folder, run the following command:"
},
{
"code": null,
"e": 7500,
"s": 7471,
"text": "docker build . -t shiny-hist"
},
{
"code": null,
"e": 7866,
"s": 7500,
"text": "This will build the shiny-hist image from rocker/shiny-verse. The base image is specified in the first line of Dockerfile: FROM rocker/shiny-verse:latest. The remaining lines are just commands to ask docker to do copying/installations/configurations. In the terminal, run docker images. Now we should see both rocker/shiny-verse and shiny-hist are there. Then, run:"
},
{
"code": null,
"e": 7906,
"s": 7866,
"text": "docker run --rm -p 3838:3838 shiny-hist"
},
{
"code": null,
"e": 8063,
"s": 7906,
"text": "This will start our histogram app on the computer at port 3838. Open the web browser, and go to localhost:3838. We’ll have an R Shiny app running in docker!"
},
{
"code": null,
"e": 8322,
"s": 8063,
"text": "The steps are the same to run the scatterplot app: within the ./Scatter_App folder, run docker build . -t shiny-scatter (remember to change the image tag), and run docker run —-rm -p 3838:3838 shiny-scatter. The scatterplot app will be accessed at port 3838."
},
{
"code": null,
"e": 8751,
"s": 8322,
"text": "Now, we can run R Shiny app docker images on the local computer. But how to make them run on the remote machines? You may notice that rocker/shiny-verse has a rocker/ part. This is the repository name on the Docker Hub. The shiny-hist and shiny-scatter we’ve built are just local images and have not been pushed to Docker Hub. To make a push, sign up a Docker Hub account and login through the Docker Desktop or in the terminal:"
},
{
"code": null,
"e": 8788,
"s": 8751,
"text": "docker login -u \"username\" docker.io"
},
{
"code": null,
"e": 8878,
"s": 8788,
"text": "After re-tagging the apps with the repository name, we can push our docker images online:"
},
{
"code": null,
"e": 9037,
"s": 8878,
"text": "docker tag shiny-hist username/shiny-hist docker tag shiny-scatter username/shiny-scatterdocker push username/shiny-histdocker push username/shiny-scatter"
},
{
"code": null,
"e": 9138,
"s": 9037,
"text": "On other computers with docker installed, we can just pull the images to the local and run the apps."
},
{
"code": null,
"e": 9718,
"s": 9138,
"text": "We’ve already built two R Shiny apps and can utilize docker to deploy them on different computers easily. The next challenge is: how we can access and manage multiple apps from a single portal and add authentication to different users. This is when ShinyProxy comes into play. ShinyProxy is an open-source solution specifically developed to combine R Shiny and docker and provide additional multi-app functionalities including user authentication (even LDAP authentication). This allows a series of R Shiny apps to be deployed and used by multiple users in an enterprise context."
},
{
"code": null,
"e": 10105,
"s": 9718,
"text": "Let’s say we want to access the two apps we’ve built from a single web page and only two users are allowed to log in: Alice and Bob. To achieve this, we need to have three new files in the same folder. Two files Dockerfile and application.yaml are in the GitHub directory. We should also download the shinyproxy-2.3.1.jar file from the ShinyProxy download page since it is a large file."
},
{
"code": null,
"e": 10680,
"s": 10105,
"text": "Before building the ShinyProxy image and running the apps, we should take a look at the application.yaml file to understand how it is configured to run. The lineauthentication: simple indicates we can directly set the usernames and passwords in the user section. Here, two users (“Alice”, “Bob”), and their passwords are set. The R Shiny docker images are configured in the specs section: we can set the ID, display name, and descriptions of the apps, and most importantly, container-image should be shiny-hist or shiny-scatter, so ShinyProxy knows to run the correct image."
},
{
"code": null,
"e": 11267,
"s": 10680,
"text": "Another new concept is the docker network. This makes docker more powerful by connecting multiple containers. We can see in the application.yaml that docker: internal-networking: true and each image has container-network: sp-test-net. It makes the two apps run in a single docker network and managed by ShinyProxy. Moreover, ShinyProxy itself can run as a container. This section aims to build a total image that entails shiny-hist, shiny-scatter, and ShinyProxy all together. Again, anything can be packed and run as a container! The following figure illustrates the ShinyProxy design:"
},
{
"code": null,
"e": 11359,
"s": 11267,
"text": "Therefore, before building the ShinyProxy image, we need to build the docker network first:"
},
{
"code": null,
"e": 11393,
"s": 11359,
"text": "docker network create sp-test-net"
},
{
"code": null,
"e": 11707,
"s": 11393,
"text": "📝 Note: If you try to build a docker network on a remote server, especially when using a VPN, you may need to specify the IP subnet mask to avoid IP address conflicts. The command I used is docker network create --driver=bridge --subnet 172.17.253.9/30 sp-test-net. Please see this link for detailed explanations."
},
{
"code": null,
"e": 11963,
"s": 11707,
"text": "The network name should be the same as the one we specified in application.yaml. Next, we build the ShinyProxy image to connect multiple R Shiny apps (The command should be run in the directory with application.yaml, shinyproxy-2.3.1.jar, and Dockerfile):"
},
{
"code": null,
"e": 11996,
"s": 11963,
"text": "docker build . -t shinyproxy-run"
},
{
"code": null,
"e": 12095,
"s": 11996,
"text": "Finally, we run the shinyproxy-run and go to localhost:8080 on the web browser to see the results:"
},
{
"code": null,
"e": 12202,
"s": 12095,
"text": "docker run --rm -v /var/run/docker.sock:/var/run/docker.sock --net sp-test-net -p 8080:8080 shinyproxy-run"
},
{
"code": null,
"e": 12345,
"s": 12202,
"text": "We should see a login page. By logging in with “Alice” or “Bob” and passwords, we are directed to the portal page with the two apps available."
},
{
"code": null,
"e": 12514,
"s": 12345,
"text": "📝 Note: There are lots of options to configure in the application.yaml file to exert the full potential of ShinyProxy. Detailed documentation can be found on this page."
},
{
"code": null,
"e": 13379,
"s": 12514,
"text": "Having finished the previous steps, we can now deploy and manage multiple R Shiny apps from a single portal. But there is another flaw in our multi-app system: Currently, all the datasets are stored within the ./data folder of each app. This presents a difficulty for dynamic data access. If the datasets used by R Shiny apps are updated, we have to re-build the corresponding app docker image to make the new data accessible to the user. When the updates are frequent, it becomes infeasible to let users see instant data changes. Moreover, we may also want the apps to generate files in the host system, which is impossible if the docker container can only manipulate itself. Fortunately, docker can use volume to create a “docker area” in the host machine and mount it to the container, hence the container can access and manipulate the files in the host system."
},
{
"code": null,
"e": 13521,
"s": 13379,
"text": "To explore this feature, we should first move the data files out of the app folder. The tree structure of the previous section is like below:"
},
{
"code": null,
"e": 14015,
"s": 13521,
"text": "04-shinyproxy/├── Dockerfile├── Hist_App│ ├── Dockerfile│ ├── Hist_App.Rproj│ ├── app.R│ ├── data│ │ ├── alice_vector_1.txt│ │ ├── alice_vector_2.txt│ │ ├── bob_vector_1.txt│ │ └── bob_vector_2.txt│ └── shiny-server.sh├── Scatter_App│ ├── Dockerfile│ ├── Scatter_App.Rproj│ ├── app.R│ ├── data│ │ ├── alice_df_1.txt│ │ ├── alice_df_2.txt│ │ ├── bob_df_1.txt│ │ └── bob_df_2.txt│ └── shiny-server.sh├── application.yml└── shinyproxy-2.3.1.jar"
},
{
"code": null,
"e": 14144,
"s": 14015,
"text": "Let’s re-organize the structure by creating a directory outside of the app folders for storing the data files used by both apps:"
},
{
"code": null,
"e": 14648,
"s": 14144,
"text": "05-data-on-host/├── Data│ ├── DF│ │ ├── alice_df_1.txt│ │ ├── alice_df_2.txt│ │ ├── bob_df_1.txt│ │ └── bob_df_2.txt│ └── Vector│ ├── alice_vector_1.txt│ ├── alice_vector_2.txt│ ├── bob_vector_1.txt│ └── bob_vector_2.txt├── Dockerfile├── Hist_App│ ├── Dockerfile│ ├── Hist_App.Rproj│ ├── app.R│ └── shiny-server.sh├── Scatter_App│ ├── Dockerfile│ ├── Scatter_App.Rproj│ ├── app.R│ └── shiny-server.sh├── application.yml└── shinyproxy-2.3.1.jar"
},
{
"code": null,
"e": 14893,
"s": 14648,
"text": "Now if we try to run docker build in the ./Hist_App folder for the histogram app, there will be errors, since the ./Hist_App/data folder no longer exists. Instead, we should make changes in the Dockerfile and app.R (See the exact changes here)."
},
{
"code": null,
"e": 15157,
"s": 14893,
"text": "We first deleted the lineCOPY data /srv/shiny-server/data in the Dockerfile, then changed the ./data/ to /Data/Vector/ in the app.R to tell the app that the data files are now stored at a different location. After rebuilding the docker image with a different tag:"
},
{
"code": null,
"e": 15217,
"s": 15157,
"text": "# within ./Hist_App folderdocker build . -t shiny-hist-data"
},
{
"code": null,
"e": 15247,
"s": 15217,
"text": "We run the following command:"
},
{
"code": null,
"e": 15476,
"s": 15247,
"text": "docker run --rm -v /Users/mingchuxu/Documents/projects/ShinyProxy-template/05-data-on-host/Data/:/Data -p 3838:3838 shiny-hist-data## Note: The absolute path to /Data in your computer is different, please change it accordingly."
},
{
"code": null,
"e": 16099,
"s": 15476,
"text": "We can see the histogram app runs on localhost:3838 successfully. How does the app know the right location of data files? The trick is from the -v option in the command above. This option tells docker that we want to mount the host directory/Users/mingchuxu/Documents/projects/ShinyProxy-template/05-data-on-hist/Data as the /Data in the container (The option accepts the <host-dir>:<container-dir> format). That’s why when we specify /Data/Vector/ in the app.R, the histogram app knows to go to /Users/mingchuxu/Documents/projects/ShinyProxy-template/05-data-on-hist/Data/Vector in the host system to find the data files."
},
{
"code": null,
"e": 16316,
"s": 16099,
"text": "We can make the same changes in the scatterplot folder (See the exact changes here), build a new docker image, and run it with the host directory mounted. The scatterplot app should also be running at localhost:3838:"
},
{
"code": null,
"e": 16613,
"s": 16316,
"text": "# within ./Scatter_App folderdocker build . -t shiny-scatter-datadocker run --rm -v /Users/mingchuxu/Documents/projects/ShinyProxy-template/05-data-on-host/Data/:/Data -p 3838:3838 shiny-scatter-data## Note: The absolute path to /Data in your computer is different, please change it accordingly."
},
{
"code": null,
"e": 16933,
"s": 16613,
"text": "The next step is to combine the docker volume feature with ShinyProxy. In application.yaml, the option container-volumes is equivalent to the -v option in docker run, allowing us to configure it accordingly. Let’s modify the application.yaml file (See the exact changes here), then build and run a new ShinyProxy image:"
},
{
"code": null,
"e": 17082,
"s": 16933,
"text": "docker build . -t shinyproxy-run-datadocker run --rm -v /var/run/docker.sock:/var/run/docker.sock --net sp-test-net -p 8080:8080 shinyproxy-run-data"
},
{
"code": null,
"e": 17467,
"s": 17082,
"text": "Now from localhost:8080, we can run multiple R Shiny apps that read data from our host machine. The following figure illustrates the improved design compared with Figure 4. We are free to move the ./Data folder to anywhere on our computer. Just remember to modify the container-volumes option in application.yaml each time we change the absolute path and rebuild the ShinyProxy image."
},
{
"code": null,
"e": 17701,
"s": 17467,
"text": "Having finished the previous steps, we are now facing the last problem: how to make Alice and Bob access user-specific data? This can be solved by utilizing the environment variable created upon ShinyProxy login: SHINYPROXY_USERNAME."
},
{
"code": null,
"e": 17958,
"s": 17701,
"text": "First, let’s add one more level to the hierarchy of Data/ folder. As shown in the tree structure below, alice*txt are put into Alice/ and bob*txt into Bob/. This allows R Shiny apps to access different folders based on different ShinyProxy login usernames."
},
{
"code": null,
"e": 18243,
"s": 17958,
"text": "Data├── DF│ ├── Alice│ │ ├── alice_df_1.txt│ │ └── alice_df_2.txt│ └── Bob│ ├── bob_df_1.txt│ └── bob_df_2.txt└── Vector ├── Alice │ ├── alice_vector_1.txt │ └── alice_vector_2.txt └── Bob ├── bob_vector_1.txt └── bob_vector_2.txt"
},
{
"code": null,
"e": 18709,
"s": 18243,
"text": "Next, we should make a series of modifications. Please see this GitHub commit for all the changes needed. Specifically, in the app.R file of each app, we need to add username <- Sys.getenv(\"SHINYPROXY_USERNAME\") to get the login username, and modify the directory path by paste0() in both ui and server; in the shiny-server.sh file of each app, we should add the following two lines to pass the environment variable into the R Shiny app (explained in details here):"
},
{
"code": null,
"e": 18776,
"s": 18709,
"text": "env > /home/shiny/.Renvironchown shiny.shiny /home/shiny/.Renviron"
},
{
"code": null,
"e": 18942,
"s": 18776,
"text": "Then, as in Section 05, we will build new docker images for each app. Again, we use new docker image tags to distinguish them from images built in previous sections."
},
{
"code": null,
"e": 19067,
"s": 18942,
"text": "# within ./Hist_App folderdocker build . -t shiny-hist-user# within ./Scatter_App folderdocker build . -t shiny-scatter-user"
},
{
"code": null,
"e": 19238,
"s": 19067,
"text": "Before building the final ShinyProxy image, we also need to modify the applicaiton.yaml since the docker images and volumes have all changed (See the exact changes here)."
},
{
"code": null,
"e": 19276,
"s": 19238,
"text": "Finally, with the following commands:"
},
{
"code": null,
"e": 19458,
"s": 19276,
"text": "docker build . -t shinyproxy-run-user # Note the tag name changedocker run --rm -v /var/run/docker.sock:/var/run/docker.sock --net sp-test-net -p 8080:8080 shinyproxy-run-user"
}
] |
Groovy - findAll()
|
It finds all values in the receiving object matching the closure condition.
List findAll(Closure closure)
The condition to be met by the collection element is specified in the closure that must be some Boolean expression.
The find method returns a list of all values found as per the expression.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
def lst = [1,2,3,4];
def value;
value = lst.findAll{element -> element > 2}
value.each {println it}
}
}
When we run the above program, we will get the following result −
3
4
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2314,
"s": 2238,
"text": "It finds all values in the receiving object matching the closure condition."
},
{
"code": null,
"e": 2345,
"s": 2314,
"text": "List findAll(Closure closure)\n"
},
{
"code": null,
"e": 2461,
"s": 2345,
"text": "The condition to be met by the collection element is specified in the closure that must be some Boolean expression."
},
{
"code": null,
"e": 2535,
"s": 2461,
"text": "The find method returns a list of all values found as per the expression."
},
{
"code": null,
"e": 2589,
"s": 2535,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2777,
"s": 2589,
"text": "class Example {\n static void main(String[] args) {\n def lst = [1,2,3,4];\n def value;\n\t\t\n value = lst.findAll{element -> element > 2}\n value.each {println it}\n } \n}"
},
{
"code": null,
"e": 2843,
"s": 2777,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 2850,
"s": 2843,
"text": "3 \n4 \n"
},
{
"code": null,
"e": 2883,
"s": 2850,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2901,
"s": 2883,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 2936,
"s": 2901,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2954,
"s": 2936,
"text": " Packt Publishing"
},
{
"code": null,
"e": 2961,
"s": 2954,
"text": " Print"
},
{
"code": null,
"e": 2972,
"s": 2961,
"text": " Add Notes"
}
] |
C++ Functional Library - modulus
|
It is a modulus function object class and binary function object class whose call returns the result of the modulus operation between its two arguments (as returned by operator %).
Following is the declaration for std::modulus.
template <class T> struct modulus;
template <class T> struct modulus;
T − It is a type of the arguments and return type of the functional call.
none
noexcep − It doesn't throw any exceptions.
In below example explains about std::modulus.
#include <iostream>
#include <functional>
#include <algorithm>
int main () {
int numbers[]={1,20,1003,42,56};
int remainders[5];
std::transform (numbers, numbers+5, remainders, std::bind2nd(std::modulus<int>(),2));
for (int i=0; i<5; i++)
std::cout << numbers[i] << " is " << (remainders[i]==0?"even":"odd") << '\n';
return 0;
}
Let us compile and run the above program, this will produce the following result −
1 is odd
20 is even
1003 is odd
42 is even
56 is even
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2784,
"s": 2603,
"text": "It is a modulus function object class and binary function object class whose call returns the result of the modulus operation between its two arguments (as returned by operator %)."
},
{
"code": null,
"e": 2831,
"s": 2784,
"text": "Following is the declaration for std::modulus."
},
{
"code": null,
"e": 2866,
"s": 2831,
"text": "template <class T> struct modulus;"
},
{
"code": null,
"e": 2901,
"s": 2866,
"text": "template <class T> struct modulus;"
},
{
"code": null,
"e": 2975,
"s": 2901,
"text": "T − It is a type of the arguments and return type of the functional call."
},
{
"code": null,
"e": 2980,
"s": 2975,
"text": "none"
},
{
"code": null,
"e": 3023,
"s": 2980,
"text": "noexcep − It doesn't throw any exceptions."
},
{
"code": null,
"e": 3069,
"s": 3023,
"text": "In below example explains about std::modulus."
},
{
"code": null,
"e": 3420,
"s": 3069,
"text": "#include <iostream>\n#include <functional>\n#include <algorithm>\n\nint main () {\n int numbers[]={1,20,1003,42,56};\n int remainders[5];\n std::transform (numbers, numbers+5, remainders, std::bind2nd(std::modulus<int>(),2));\n for (int i=0; i<5; i++)\n std::cout << numbers[i] << \" is \" << (remainders[i]==0?\"even\":\"odd\") << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 3503,
"s": 3420,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3558,
"s": 3503,
"text": "1 is odd\n20 is even\n1003 is odd\n42 is even\n56 is even\n"
},
{
"code": null,
"e": 3565,
"s": 3558,
"text": " Print"
},
{
"code": null,
"e": 3576,
"s": 3565,
"text": " Add Notes"
}
] |
Can we create an object for an interface in java?
|
No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete.
Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.
In the following example we an interface with name MyInterface and a class with name InterfaceExample.
In the interface we have an integer filed (public, static and, final) num and abstract method demo().
From the class we are trying to − create an object of the interface and print the num value.
Live Demo
interface MyInterface{
public static final int num = 30;
public abstract void demo();
}
public class InterfaceExample implements MyInterface {
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
MyInterface interfaceObject = new MyInterface();
System.out.println(interfaceObject.num);
}
}
On compiling, the above program generates the following error
InterfaceExample.java:13: error: MyInterface is abstract; cannot be instantiated
MyInterface interfaceObject = new MyInterface();
^
1 error
To access the members of an interface you need to implements it and provide implementation to all the abstract methods of it.
Live Demo
interface MyInterface{
public int num = 30;
public void demo();
}
public class InterfaceExample implements MyInterface {
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.demo();
System.out.println(MyInterface.num);
}
}
This is the implementation of the demo method
30
|
[
{
"code": null,
"e": 1222,
"s": 1062,
"text": "No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete."
},
{
"code": null,
"e": 1365,
"s": 1222,
"text": "Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”."
},
{
"code": null,
"e": 1468,
"s": 1365,
"text": "In the following example we an interface with name MyInterface and a class with name InterfaceExample."
},
{
"code": null,
"e": 1570,
"s": 1468,
"text": "In the interface we have an integer filed (public, static and, final) num and abstract method demo()."
},
{
"code": null,
"e": 1663,
"s": 1570,
"text": "From the class we are trying to − create an object of the interface and print the num value."
},
{
"code": null,
"e": 1674,
"s": 1663,
"text": " Live Demo"
},
{
"code": null,
"e": 2080,
"s": 1674,
"text": "interface MyInterface{\n public static final int num = 30;\n public abstract void demo();\n}\npublic class InterfaceExample implements MyInterface {\n public void demo() {\n System.out.println(\"This is the implementation of the demo method\");\n }\n public static void main(String args[]) {\n MyInterface interfaceObject = new MyInterface();\n System.out.println(interfaceObject.num);\n }\n}"
},
{
"code": null,
"e": 2142,
"s": 2080,
"text": "On compiling, the above program generates the following error"
},
{
"code": null,
"e": 2285,
"s": 2142,
"text": "InterfaceExample.java:13: error: MyInterface is abstract; cannot be instantiated\n MyInterface interfaceObject = new MyInterface();\n^\n1 error"
},
{
"code": null,
"e": 2411,
"s": 2285,
"text": "To access the members of an interface you need to implements it and provide implementation to all the abstract methods of it."
},
{
"code": null,
"e": 2422,
"s": 2411,
"text": " Live Demo"
},
{
"code": null,
"e": 2818,
"s": 2422,
"text": "interface MyInterface{\n public int num = 30;\n public void demo();\n}\npublic class InterfaceExample implements MyInterface {\n public void demo() {\n System.out.println(\"This is the implementation of the demo method\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.demo();\n System.out.println(MyInterface.num);\n }\n}"
},
{
"code": null,
"e": 2867,
"s": 2818,
"text": "This is the implementation of the demo method\n30"
}
] |
Find maximum sum pair with same digit sum - GeeksforGeeks
|
15 Dec, 2021
Given an array arr having N integers, the task is to find a pair with maximum sum and having the same sum of digits. Print the sum of that pair, if it exists. Otherwise, print -1.
Examples:
Input: arr[]={55, 23, 32, 46, 88}Output: 46 55 101Explanation: Pair {55, 46} will give the sum of 55 + 46 = 101
Input: arr[]={18, 19, 23, 15}Output: -1
Approach: Follow the below steps to solve this problem:
Create a map, say mp to store the sum of digits in a number as the key and the maximum number having that sum of digits as the value.Now create a global variable ans to store the answer to this problem.Now start traversing the array, and in each iteration:Check if the sum of its digit is already present in the map. If it is, then change ans with the maximum of ans and the sum of the two numbers.If the sum of the digits is not present in the map. Create a new key for it and store its value. Otherwise, update the number in the map if it’s greater than the existing number.Return ans as the answer to this problem.
Create a map, say mp to store the sum of digits in a number as the key and the maximum number having that sum of digits as the value.
Now create a global variable ans to store the answer to this problem.
Now start traversing the array, and in each iteration:Check if the sum of its digit is already present in the map. If it is, then change ans with the maximum of ans and the sum of the two numbers.If the sum of the digits is not present in the map. Create a new key for it and store its value. Otherwise, update the number in the map if it’s greater than the existing number.
Check if the sum of its digit is already present in the map. If it is, then change ans with the maximum of ans and the sum of the two numbers.
If the sum of the digits is not present in the map. Create a new key for it and store its value. Otherwise, update the number in the map if it’s greater than the existing number.
Return ans as the answer to this problem.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find sum of digitsint digitSum(long n){ long sum = 0; while (n) { sum += (n % 10); n /= 10; } return sum;} // Function to find maximum sum pair// having the same sum of digitsvoid findMax(vector<int> arr, int n){ // Map to store the sum of digits // in a number as the key and // the maximum number having // that sum of digits as the value unordered_map<int, int> mp; int ans = -1, pairi = 0, pairj = 0; for (int i = 0; i < n; i++) { // Store the current sum of digits // of the number in temp int temp = digitSum(arr[i]); // If temp is already present // in the map then update // ans if the sum is greater // than the existing value if (mp[temp] != 0) { if (arr[i] + mp[temp] > ans) { pairi = arr[i]; pairj = mp[temp]; ans = pairi + pairj; } } // Change the value in the map mp[temp] = max(arr[i], mp[temp]); } cout << pairi << " " << pairj << " " << ans << endl;} // Driver Code Starts.int main(){ vector<int> arr = { 55, 23, 32, 46, 88 }; int n = arr.size(); findMax(arr, n); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find sum of digitsstatic int digitSum(long n){ int sum = 0; while (n > 0) { sum += (n % 10); n /= 10; } return sum;} // Function to find maximum sum pair// having the same sum of digitsstatic void findMax(int []arr, int n){ // Map to store the sum of digits // in a number as the key and // the maximum number having // that sum of digits as the value HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); int ans = -1, pairi = 0, pairj = 0; for (int i = 0; i < n; i++) { // Store the current sum of digits // of the number in temp int temp = digitSum(arr[i]); // If temp is already present // in the map then update // ans if the sum is greater // than the existing value if (mp.containsKey(temp)) { if (arr[i] + mp.get(temp) > ans) { pairi = arr[i]; pairj = mp.get(temp); ans = pairi + pairj; } mp.put(temp, Math.max(arr[i], mp.get(temp))); } else // Change the value in the map mp.put(temp, arr[i]); } System.out.print(pairi+ " " + pairj + " " + ans +"\n");} // Driver Code Starts.public static void main(String[] args){ int []arr = { 55, 23, 32, 46, 88 }; int n = arr.length; findMax(arr, n);}} // This code is contributed by shikhasingrajput
# Python Program to implement# the above approach # Function to find sum of digitsdef digitSum(n): sum = 0 while (n): sum += (n % 10) n = n // 10 return sum # Function to find maximum sum pair# having the same sum of digitsdef findMax(arr, n): # Map to store the sum of digits # in a number as the key and # the maximum number having # that sum of digits as the value mp = {} ans = -1 pairi = 0 pairj = 0 for i in range(n): # Store the current sum of digits # of the number in temp temp = digitSum(arr[i]) # If temp is already present # in the map then update # ans if the sum is greater # than the existing value if (temp not in mp): mp[temp] = 0 if (mp[temp] != 0) : if (arr[i] + mp[temp] > ans): pairi = arr[i] pairj = mp.get(temp) ans = pairi + pairj # Change the value in the map mp[temp] = max(arr[i], mp[temp]) print(f"{pairi} {pairj} {ans}") # Driver Code Starts.arr = [55, 23, 32, 46, 88]n = len(arr)findMax(arr, n) # This code is contributed by Saurabh Jaiswal
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find sum of digitsstatic int digitSum(long n){ int sum = 0; while (n > 0) { sum += (int)(n % 10); n /= 10; } return sum;} // Function to find maximum sum pair// having the same sum of digitsstatic void findMax(int []arr, int n){ // Map to store the sum of digits // in a number as the key and // the maximum number having // that sum of digits as the value Dictionary<int,int> mp = new Dictionary<int, int>(); int ans = -1, pairi = 0, pairj = 0; for (int i = 0; i < n; i++) { // Store the current sum of digits // of the number in temp int temp = digitSum(arr[i]); // If temp is already present // in the map then update // ans if the sum is greater // than the existing value if (mp.ContainsKey(temp)) { if (arr[i] + mp[temp] > ans) { pairi = arr[i]; pairj = mp[temp]; ans = pairi + pairj; } mp[temp] = Math.Max(arr[i], mp[temp]); } else // Change the value in the map mp[temp] = arr[i]; } Console.WriteLine(pairi+ " " + pairj + " " + ans );} // Driver Code Starts.public static void Main(){ int []arr = { 55, 23, 32, 46, 88 }; int n = arr.Length; findMax(arr, n);}} // This code is contributed by Saurabh Jaiswal
<script> // JavaScript Program to implement // the above approach // Function to find sum of digits function digitSum(n) { let sum = 0; while (n) { sum += (n % 10); n = Math.floor(n / 10); } return sum; } // Function to find maximum sum pair // having the same sum of digits function findMax(arr, n) { // Map to store the sum of digits // in a number as the key and // the maximum number having // that sum of digits as the value let mp = new Map(); let ans = -1, pairi = 0, pairj = 0; for (let i = 0; i < n; i++) { // Store the current sum of digits // of the number in temp let temp = digitSum(arr[i]); // If temp is already present // in the map then update // ans if the sum is greater // than the existing value if (!mp.has(temp)) { mp.set(temp, 0); } if (mp.get(temp) != 0) { if (arr[i] + mp.get(temp) > ans) { pairi = arr[i]; pairj = mp.get(temp); ans = pairi + pairj; } } // Change the value in the map mp.set(temp, Math.max(arr[i], mp.get(temp))); } document.write(pairi + " " + pairj + " " + ans + '<br>'); } // Driver Code Starts. let arr = [55, 23, 32, 46, 88]; let n = arr.length; findMax(arr, n); // This code is contributed by Potta Lokesh </script>
46 55 101
Time complexity: O(N)Auxiliary Space: O(N)
lokeshpotta20
_saurabh_jaiswal
anikakapoor
shikhasingrajput
number-digits
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
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": 24822,
"s": 24794,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 25002,
"s": 24822,
"text": "Given an array arr having N integers, the task is to find a pair with maximum sum and having the same sum of digits. Print the sum of that pair, if it exists. Otherwise, print -1."
},
{
"code": null,
"e": 25013,
"s": 25002,
"text": "Examples: "
},
{
"code": null,
"e": 25128,
"s": 25013,
"text": "Input: arr[]={55, 23, 32, 46, 88}Output: 46 55 101Explanation: Pair {55, 46} will give the sum of 55 + 46 = 101 "
},
{
"code": null,
"e": 25168,
"s": 25128,
"text": "Input: arr[]={18, 19, 23, 15}Output: -1"
},
{
"code": null,
"e": 25224,
"s": 25168,
"text": "Approach: Follow the below steps to solve this problem:"
},
{
"code": null,
"e": 25842,
"s": 25224,
"text": "Create a map, say mp to store the sum of digits in a number as the key and the maximum number having that sum of digits as the value.Now create a global variable ans to store the answer to this problem.Now start traversing the array, and in each iteration:Check if the sum of its digit is already present in the map. If it is, then change ans with the maximum of ans and the sum of the two numbers.If the sum of the digits is not present in the map. Create a new key for it and store its value. Otherwise, update the number in the map if it’s greater than the existing number.Return ans as the answer to this problem."
},
{
"code": null,
"e": 25976,
"s": 25842,
"text": "Create a map, say mp to store the sum of digits in a number as the key and the maximum number having that sum of digits as the value."
},
{
"code": null,
"e": 26046,
"s": 25976,
"text": "Now create a global variable ans to store the answer to this problem."
},
{
"code": null,
"e": 26421,
"s": 26046,
"text": "Now start traversing the array, and in each iteration:Check if the sum of its digit is already present in the map. If it is, then change ans with the maximum of ans and the sum of the two numbers.If the sum of the digits is not present in the map. Create a new key for it and store its value. Otherwise, update the number in the map if it’s greater than the existing number."
},
{
"code": null,
"e": 26564,
"s": 26421,
"text": "Check if the sum of its digit is already present in the map. If it is, then change ans with the maximum of ans and the sum of the two numbers."
},
{
"code": null,
"e": 26743,
"s": 26564,
"text": "If the sum of the digits is not present in the map. Create a new key for it and store its value. Otherwise, update the number in the map if it’s greater than the existing number."
},
{
"code": null,
"e": 26785,
"s": 26743,
"text": "Return ans as the answer to this problem."
},
{
"code": null,
"e": 26836,
"s": 26785,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26840,
"s": 26836,
"text": "C++"
},
{
"code": null,
"e": 26845,
"s": 26840,
"text": "Java"
},
{
"code": null,
"e": 26853,
"s": 26845,
"text": "Python3"
},
{
"code": null,
"e": 26856,
"s": 26853,
"text": "C#"
},
{
"code": null,
"e": 26867,
"s": 26856,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find sum of digitsint digitSum(long n){ long sum = 0; while (n) { sum += (n % 10); n /= 10; } return sum;} // Function to find maximum sum pair// having the same sum of digitsvoid findMax(vector<int> arr, int n){ // Map to store the sum of digits // in a number as the key and // the maximum number having // that sum of digits as the value unordered_map<int, int> mp; int ans = -1, pairi = 0, pairj = 0; for (int i = 0; i < n; i++) { // Store the current sum of digits // of the number in temp int temp = digitSum(arr[i]); // If temp is already present // in the map then update // ans if the sum is greater // than the existing value if (mp[temp] != 0) { if (arr[i] + mp[temp] > ans) { pairi = arr[i]; pairj = mp[temp]; ans = pairi + pairj; } } // Change the value in the map mp[temp] = max(arr[i], mp[temp]); } cout << pairi << \" \" << pairj << \" \" << ans << endl;} // Driver Code Starts.int main(){ vector<int> arr = { 55, 23, 32, 46, 88 }; int n = arr.size(); findMax(arr, n); return 0;}",
"e": 28178,
"s": 26867,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find sum of digitsstatic int digitSum(long n){ int sum = 0; while (n > 0) { sum += (n % 10); n /= 10; } return sum;} // Function to find maximum sum pair// having the same sum of digitsstatic void findMax(int []arr, int n){ // Map to store the sum of digits // in a number as the key and // the maximum number having // that sum of digits as the value HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); int ans = -1, pairi = 0, pairj = 0; for (int i = 0; i < n; i++) { // Store the current sum of digits // of the number in temp int temp = digitSum(arr[i]); // If temp is already present // in the map then update // ans if the sum is greater // than the existing value if (mp.containsKey(temp)) { if (arr[i] + mp.get(temp) > ans) { pairi = arr[i]; pairj = mp.get(temp); ans = pairi + pairj; } mp.put(temp, Math.max(arr[i], mp.get(temp))); } else // Change the value in the map mp.put(temp, arr[i]); } System.out.print(pairi+ \" \" + pairj + \" \" + ans +\"\\n\");} // Driver Code Starts.public static void main(String[] args){ int []arr = { 55, 23, 32, 46, 88 }; int n = arr.length; findMax(arr, n);}} // This code is contributed by shikhasingrajput",
"e": 29668,
"s": 28178,
"text": null
},
{
"code": "# Python Program to implement# the above approach # Function to find sum of digitsdef digitSum(n): sum = 0 while (n): sum += (n % 10) n = n // 10 return sum # Function to find maximum sum pair# having the same sum of digitsdef findMax(arr, n): # Map to store the sum of digits # in a number as the key and # the maximum number having # that sum of digits as the value mp = {} ans = -1 pairi = 0 pairj = 0 for i in range(n): # Store the current sum of digits # of the number in temp temp = digitSum(arr[i]) # If temp is already present # in the map then update # ans if the sum is greater # than the existing value if (temp not in mp): mp[temp] = 0 if (mp[temp] != 0) : if (arr[i] + mp[temp] > ans): pairi = arr[i] pairj = mp.get(temp) ans = pairi + pairj # Change the value in the map mp[temp] = max(arr[i], mp[temp]) print(f\"{pairi} {pairj} {ans}\") # Driver Code Starts.arr = [55, 23, 32, 46, 88]n = len(arr)findMax(arr, n) # This code is contributed by Saurabh Jaiswal",
"e": 30861,
"s": 29668,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find sum of digitsstatic int digitSum(long n){ int sum = 0; while (n > 0) { sum += (int)(n % 10); n /= 10; } return sum;} // Function to find maximum sum pair// having the same sum of digitsstatic void findMax(int []arr, int n){ // Map to store the sum of digits // in a number as the key and // the maximum number having // that sum of digits as the value Dictionary<int,int> mp = new Dictionary<int, int>(); int ans = -1, pairi = 0, pairj = 0; for (int i = 0; i < n; i++) { // Store the current sum of digits // of the number in temp int temp = digitSum(arr[i]); // If temp is already present // in the map then update // ans if the sum is greater // than the existing value if (mp.ContainsKey(temp)) { if (arr[i] + mp[temp] > ans) { pairi = arr[i]; pairj = mp[temp]; ans = pairi + pairj; } mp[temp] = Math.Max(arr[i], mp[temp]); } else // Change the value in the map mp[temp] = arr[i]; } Console.WriteLine(pairi+ \" \" + pairj + \" \" + ans );} // Driver Code Starts.public static void Main(){ int []arr = { 55, 23, 32, 46, 88 }; int n = arr.Length; findMax(arr, n);}} // This code is contributed by Saurabh Jaiswal",
"e": 32329,
"s": 30861,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach // Function to find sum of digits function digitSum(n) { let sum = 0; while (n) { sum += (n % 10); n = Math.floor(n / 10); } return sum; } // Function to find maximum sum pair // having the same sum of digits function findMax(arr, n) { // Map to store the sum of digits // in a number as the key and // the maximum number having // that sum of digits as the value let mp = new Map(); let ans = -1, pairi = 0, pairj = 0; for (let i = 0; i < n; i++) { // Store the current sum of digits // of the number in temp let temp = digitSum(arr[i]); // If temp is already present // in the map then update // ans if the sum is greater // than the existing value if (!mp.has(temp)) { mp.set(temp, 0); } if (mp.get(temp) != 0) { if (arr[i] + mp.get(temp) > ans) { pairi = arr[i]; pairj = mp.get(temp); ans = pairi + pairj; } } // Change the value in the map mp.set(temp, Math.max(arr[i], mp.get(temp))); } document.write(pairi + \" \" + pairj + \" \" + ans + '<br>'); } // Driver Code Starts. let arr = [55, 23, 32, 46, 88]; let n = arr.length; findMax(arr, n); // This code is contributed by Potta Lokesh </script>",
"e": 34074,
"s": 32329,
"text": null
},
{
"code": null,
"e": 34084,
"s": 34074,
"text": "46 55 101"
},
{
"code": null,
"e": 34127,
"s": 34084,
"text": "Time complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 34141,
"s": 34127,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 34158,
"s": 34141,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 34170,
"s": 34158,
"text": "anikakapoor"
},
{
"code": null,
"e": 34187,
"s": 34170,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 34201,
"s": 34187,
"text": "number-digits"
},
{
"code": null,
"e": 34208,
"s": 34201,
"text": "Arrays"
},
{
"code": null,
"e": 34221,
"s": 34208,
"text": "Mathematical"
},
{
"code": null,
"e": 34228,
"s": 34221,
"text": "Arrays"
},
{
"code": null,
"e": 34241,
"s": 34228,
"text": "Mathematical"
},
{
"code": null,
"e": 34339,
"s": 34241,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34364,
"s": 34339,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34384,
"s": 34364,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 34422,
"s": 34384,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34507,
"s": 34422,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 34556,
"s": 34507,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34586,
"s": 34556,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34646,
"s": 34586,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34661,
"s": 34646,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34704,
"s": 34661,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to detect orientation change in layout in android?
|
This example demonstrates how do I detect orientation change in layout in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="24sp"
android:textStyle="bold"/>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(MainActivity.this, "Landscape Mode", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(MainActivity.this, "Portrait Mode", Toast.LENGTH_SHORT).show();
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "This example demonstrates how do I detect orientation change in layout in android."
},
{
"code": null,
"e": 1274,
"s": 1145,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1339,
"s": 1274,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1835,
"s": 1339,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"/>\n</LinearLayout>"
},
{
"code": null,
"e": 1892,
"s": 1835,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2725,
"s": 1892,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.content.res.Configuration;\nimport android.os.Bundle;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {\n Toast.makeText(MainActivity.this, \"Landscape Mode\", Toast.LENGTH_SHORT).show();\n } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {\n Toast.makeText(MainActivity.this, \"Portrait Mode\", Toast.LENGTH_SHORT).show();\n }\n }\n}"
},
{
"code": null,
"e": 2780,
"s": 2725,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3497,
"s": 2780,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\" android:configChanges=\"orientation|screenSize\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3852,
"s": 3497,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
}
] |
Binary Search Tree | Set 3 (Iterative Delete) - GeeksforGeeks
|
26 Jul, 2021
Given a binary search tree and a node of the binary search tree, the task is to delete the node from the Binary Search tree Iteratiely.Here are the three cases that arise while performing a delete operation on a BST:
1. Case 1: Node to be deleted is a leaf node. Directly delete the node from the tree.
10 10
/ \ delete(5) / \
7 15 ---------> 7 15
/ \ / \ \ / \
5 8 11 18 8 11 18
2. Case 2: Node to be deleted is an internal node with two children. Copy the contents of the inorder successor of the node to be deleted and delete the inorder successor. The inorder successor can be found by finding the minimum element in the right subtree of the node. inorderSuccessor(10) = 11.
10 11
/ \ delete(10) / \
7 15 ---------> 7 15
/ \ / \ / \ \
5 8 11 18 5 8 18
3. Case 3: Node to be deleted is an internal node with one child. For this case, delete the node and move its child up to take its place.
10 10
/ \ delete(15) / \
7 15 ---------> 7 11
/ \ / / \
5 8 11 5 8
The intuition behind deleting the inorder successor in Case 2 is that the inorder successor of a node with two children will always be greater than all elements in the left sub-tree of the of the node since it is the smallest node in the right sub-tree of the node and the inorder successor of the node will always be smaller than all other nodes in the right sub-tree of the node.
This preserves the BST property of all nodes in the left sub-tree of a given node are smaller than the given node and all nodes in the right sub-tree of the given node are greater than the given node.
Below is the implementation of the above approach:
C++
Python3
// C++ implementation to delete// a node in the BST #include <bits/stdc++.h>using namespace std; // Structure of the nodetypedef struct treeNode { int data; struct treeNode* left; struct treeNode* right;} treeNode; // Utility function to print// the inorder traversal of the BST.void inorder(treeNode* root){ if (root != NULL) { inorder(root->left); cout << root->data << ' '; inorder(root->right); }} // Utility function to insert// nodes into our BSTtreeNode* insert(treeNode* root, int key){ // Check if tree is empty if (root == NULL) { treeNode* temp; temp = (treeNode*)malloc(sizeof(treeNode)); temp->data = key; temp->left = NULL; temp->right = NULL; return temp; } if (key < root->data) { // if the key to be inserted // is lesser than the root, // insert into the left subtree, // and recursively call // the insert function with the // root->left as the new root. root->left = insert(root->left, key); } else { // if the key to be inserted // is greater than the root, // insert into the right subtree, // and recursively call // the insert function with the // root->right as the new root. root->right = insert(root->right, key); } return root;} // Iterative Function to delete// 'key' from the BST.treeNode* deleteIterative(treeNode* root, int key){ treeNode* curr = root; treeNode* prev = NULL; // Check if the key is actually // present in the BST. // the variable prev points to // the parent of the key to be deleted. while (curr != NULL && curr->data != key) { prev = curr; if (key < curr->data) curr = curr->left; else curr = curr->right; } if (curr == NULL) { cout << "Key " << key << " not found in the" << " provided BST.\n"; return root; } // Check if the node to be // deleted has atmost one child. if (curr->left == NULL || curr->right == NULL) { // newCurr will replace // the node to be deleted. treeNode* newCurr; // if the left child does not exist. if (curr->left == NULL) newCurr = curr->right; else newCurr = curr->left; // check if the node to // be deleted is the root. if (prev == NULL) return newCurr; // check if the node to be deleted // is prev's left or right child // and then replace this with newCurr if (curr == prev->left) prev->left = newCurr; else prev->right = newCurr; // free memory of the // node to be deleted. free(curr); } // node to be deleted has // two children. else { treeNode* p = NULL; treeNode* temp; // Compute the inorder successor temp = curr->right; while (temp->left != NULL) { p = temp; temp = temp->left; } // check if the parent of the inorder // successor is the curr or not(i.e. curr= // the node which has the same data as // the given data by the user to be // deleted). if it isn't, then make the // the left child of its parent equal to // the inorder successor'd right child. if (p != NULL) p->left = temp->right; // if the inorder successor was the // curr (i.e. curr = the node which has the // same data as the given data by the // user to be deleted), then make the // right child of the node to be // deleted equal to the right child of // the inorder successor. else curr->right = temp->right; curr->data = temp->data; free(temp); } return root;} // Driver Codeint main(){ /* 10 / \ 7 15 / \ / \ 5 8 11 18 */ treeNode* root = NULL; root = insert(root, 10); root = insert(root, 7); root = insert(root, 5); root = insert(root, 8); root = insert(root, 15); root = insert(root, 11); root = insert(root, 18); cout << "Inorder traversal " << "of original BST:\n"; inorder(root); cout << '\n'; // delete node with data value 11 (leaf) root = deleteIterative(root, 11); cout << "\nDeletion of 11\n"; cout << "Inorder traversal post deletion:\n"; inorder(root); cout << '\n'; // delete node with data value 15 // (internal node with one child) root = deleteIterative(root, 15); cout << "\nDeletion of 15\n"; cout << "Inorder traversal post deletion:\n"; inorder(root); cout << '\n'; // delete node with data value 10 // (root, two children) root = deleteIterative(root, 10); cout << "\nDeletion of 10\n"; cout << "Inorder traversal post deletion:\n"; inorder(root); cout << '\n'; return 0;}
# Python implementation to delete# a node in the Binary Search Tree # Class for a node of BST. class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Utility function to print# the inorder traversal of the BST def inorder(root): if root != None: inorder(root.left) print(root.data, end=" ") inorder(root.right) # Utility function to insert# nodes into our BST def insert(root, key): # check if tree is empty if root == None: temp = Node(key) return temp if key < root.data: """ if the key to be inserted is lesser than the root, insert into the left subtree, and recursively call the insert function with the root.left as the new root. """ root.left = insert(root.left, key) else: """ if the key to be inserted is greater than the root, insert into the right subtree, and recursively call the insert function with the root->right as the new root. """ root.right = insert(root.right, key) return root # Iterative approach to# delete 'key' from the BST. def deleteIterative(root, key): curr = root prev = None # First check if the key is # actually present in the BST. # the variable prev points to the # parent of the key to be deleted while(curr != None and curr.data != key): prev = curr if curr.data < key: curr = curr.right else: curr = curr.left if curr == None: print("Key % d not found in\ the provided BST." % key) return root # Check if the node to be # deleted has atmost one child if curr.left == None or\ curr.right == None: # newCurr will replace # the node to be deleted. newCurr = None # if the left child does not exist. if curr.left == None: newCurr = curr.right else: newCurr = curr.left # check if the node to # be deleted is the root. if prev == None: return newCurr # Check if the node to be # deleted is prev's left or # right child and then # replace this with newCurr if curr == prev.left: prev.left = newCurr else: prev.right = newCurr curr = None # node to be deleted # has two children. else: p = None temp = None # Compute the inorder # successor of curr. temp = curr.right while(temp.left != None): p = temp temp = temp.left # check if the parent of the # inorder successor is the root or not. # if it isn't, then make the left # child of its parent equal to the # inorder successor's right child. if p != None: p.left = temp.right else: # if the inorder successor was # the root, then make the right child # of the node to be deleted equal # to the right child of the inorder # successor. curr.right = temp.right curr.data = temp.data temp = None return root # Function to create the BST# and call the Delete Function def main(): """ 10 / \ 7 15 / \ / \ 5 8 11 18 """ root = None root = insert(root, 10) root = insert(root, 7) root = insert(root, 5) root = insert(root, 8) root = insert(root, 15) root = insert(root, 11) root = insert(root, 18) print("Inorder traversal of original BST:") inorder(root) print("\n") # delete node with data value 11 (leaf) root = deleteIterative(root, 11) print("Deletion of 11") print("Inorder traversal post deletion:") inorder(root) print("\n") # delete node with data value 15 # (internal node with one child) root = deleteIterative(root, 15) print("Deletion of 15") print("Inorder traversal post deletion:") inorder(root) print("\n") # delete node with data value 10 # (root, two children) root = deleteIterative(root, 10) print("Deletion of 10") print("Inorder traversal post deletion:") inorder(root) print() # Driver Codeif __name__ == "__main__": main()
Inorder traversal of original BST:
5 7 8 10 11 15 18
Deletion of 11
Inorder traversal post deletion:
5 7 8 10 15 18
Deletion of 15
Inorder traversal post deletion:
5 7 8 10 18
Deletion of 10
Inorder traversal post deletion:
5 7 8 18
ishansaha05
anikaseth98
Binary Search Trees
BST
Delete Tree
Picked
Binary Search Tree
Data Structures
Data Structures
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Print BST keys in the given range
Find the node with maximum value in a Binary Search Tree
set vs unordered_set in C++ STL
Threaded Binary Tree | Insertion
Floor and Ceil from a BST
Difference between Stack and Queue Data Structures
What is Competitive Programming and How to Prepare for It?
FIFO (First-In-First-Out) approach in Programming
Advantages and Disadvantages of Linked List
C program to implement Adjacency Matrix of a given Graph
|
[
{
"code": null,
"e": 25224,
"s": 25196,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 25442,
"s": 25224,
"text": "Given a binary search tree and a node of the binary search tree, the task is to delete the node from the Binary Search tree Iteratiely.Here are the three cases that arise while performing a delete operation on a BST: "
},
{
"code": null,
"e": 25529,
"s": 25442,
"text": "1. Case 1: Node to be deleted is a leaf node. Directly delete the node from the tree. "
},
{
"code": null,
"e": 25798,
"s": 25529,
"text": " \n 10 10\n / \\ delete(5) / \\\n 7 15 ---------> 7 15 \n / \\ / \\ \\ / \\ \n 5 8 11 18 8 11 18"
},
{
"code": null,
"e": 26098,
"s": 25798,
"text": "2. Case 2: Node to be deleted is an internal node with two children. Copy the contents of the inorder successor of the node to be deleted and delete the inorder successor. The inorder successor can be found by finding the minimum element in the right subtree of the node. inorderSuccessor(10) = 11. "
},
{
"code": null,
"e": 26362,
"s": 26098,
"text": " 10 11\n / \\ delete(10) / \\\n 7 15 ---------> 7 15 \n / \\ / \\ / \\ \\ \n 5 8 11 18 5 8 18"
},
{
"code": null,
"e": 26501,
"s": 26362,
"text": "3. Case 3: Node to be deleted is an internal node with one child. For this case, delete the node and move its child up to take its place. "
},
{
"code": null,
"e": 26750,
"s": 26501,
"text": " 10 10\n / \\ delete(15) / \\\n 7 15 ---------> 7 11 \n / \\ / / \\ \n 5 8 11 5 8"
},
{
"code": null,
"e": 27133,
"s": 26750,
"text": "The intuition behind deleting the inorder successor in Case 2 is that the inorder successor of a node with two children will always be greater than all elements in the left sub-tree of the of the node since it is the smallest node in the right sub-tree of the node and the inorder successor of the node will always be smaller than all other nodes in the right sub-tree of the node. "
},
{
"code": null,
"e": 27336,
"s": 27133,
"text": "This preserves the BST property of all nodes in the left sub-tree of a given node are smaller than the given node and all nodes in the right sub-tree of the given node are greater than the given node. "
},
{
"code": null,
"e": 27388,
"s": 27336,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27392,
"s": 27388,
"text": "C++"
},
{
"code": null,
"e": 27400,
"s": 27392,
"text": "Python3"
},
{
"code": "// C++ implementation to delete// a node in the BST #include <bits/stdc++.h>using namespace std; // Structure of the nodetypedef struct treeNode { int data; struct treeNode* left; struct treeNode* right;} treeNode; // Utility function to print// the inorder traversal of the BST.void inorder(treeNode* root){ if (root != NULL) { inorder(root->left); cout << root->data << ' '; inorder(root->right); }} // Utility function to insert// nodes into our BSTtreeNode* insert(treeNode* root, int key){ // Check if tree is empty if (root == NULL) { treeNode* temp; temp = (treeNode*)malloc(sizeof(treeNode)); temp->data = key; temp->left = NULL; temp->right = NULL; return temp; } if (key < root->data) { // if the key to be inserted // is lesser than the root, // insert into the left subtree, // and recursively call // the insert function with the // root->left as the new root. root->left = insert(root->left, key); } else { // if the key to be inserted // is greater than the root, // insert into the right subtree, // and recursively call // the insert function with the // root->right as the new root. root->right = insert(root->right, key); } return root;} // Iterative Function to delete// 'key' from the BST.treeNode* deleteIterative(treeNode* root, int key){ treeNode* curr = root; treeNode* prev = NULL; // Check if the key is actually // present in the BST. // the variable prev points to // the parent of the key to be deleted. while (curr != NULL && curr->data != key) { prev = curr; if (key < curr->data) curr = curr->left; else curr = curr->right; } if (curr == NULL) { cout << \"Key \" << key << \" not found in the\" << \" provided BST.\\n\"; return root; } // Check if the node to be // deleted has atmost one child. if (curr->left == NULL || curr->right == NULL) { // newCurr will replace // the node to be deleted. treeNode* newCurr; // if the left child does not exist. if (curr->left == NULL) newCurr = curr->right; else newCurr = curr->left; // check if the node to // be deleted is the root. if (prev == NULL) return newCurr; // check if the node to be deleted // is prev's left or right child // and then replace this with newCurr if (curr == prev->left) prev->left = newCurr; else prev->right = newCurr; // free memory of the // node to be deleted. free(curr); } // node to be deleted has // two children. else { treeNode* p = NULL; treeNode* temp; // Compute the inorder successor temp = curr->right; while (temp->left != NULL) { p = temp; temp = temp->left; } // check if the parent of the inorder // successor is the curr or not(i.e. curr= // the node which has the same data as // the given data by the user to be // deleted). if it isn't, then make the // the left child of its parent equal to // the inorder successor'd right child. if (p != NULL) p->left = temp->right; // if the inorder successor was the // curr (i.e. curr = the node which has the // same data as the given data by the // user to be deleted), then make the // right child of the node to be // deleted equal to the right child of // the inorder successor. else curr->right = temp->right; curr->data = temp->data; free(temp); } return root;} // Driver Codeint main(){ /* 10 / \\ 7 15 / \\ / \\ 5 8 11 18 */ treeNode* root = NULL; root = insert(root, 10); root = insert(root, 7); root = insert(root, 5); root = insert(root, 8); root = insert(root, 15); root = insert(root, 11); root = insert(root, 18); cout << \"Inorder traversal \" << \"of original BST:\\n\"; inorder(root); cout << '\\n'; // delete node with data value 11 (leaf) root = deleteIterative(root, 11); cout << \"\\nDeletion of 11\\n\"; cout << \"Inorder traversal post deletion:\\n\"; inorder(root); cout << '\\n'; // delete node with data value 15 // (internal node with one child) root = deleteIterative(root, 15); cout << \"\\nDeletion of 15\\n\"; cout << \"Inorder traversal post deletion:\\n\"; inorder(root); cout << '\\n'; // delete node with data value 10 // (root, two children) root = deleteIterative(root, 10); cout << \"\\nDeletion of 10\\n\"; cout << \"Inorder traversal post deletion:\\n\"; inorder(root); cout << '\\n'; return 0;}",
"e": 32345,
"s": 27400,
"text": null
},
{
"code": "# Python implementation to delete# a node in the Binary Search Tree # Class for a node of BST. class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Utility function to print# the inorder traversal of the BST def inorder(root): if root != None: inorder(root.left) print(root.data, end=\" \") inorder(root.right) # Utility function to insert# nodes into our BST def insert(root, key): # check if tree is empty if root == None: temp = Node(key) return temp if key < root.data: \"\"\" if the key to be inserted is lesser than the root, insert into the left subtree, and recursively call the insert function with the root.left as the new root. \"\"\" root.left = insert(root.left, key) else: \"\"\" if the key to be inserted is greater than the root, insert into the right subtree, and recursively call the insert function with the root->right as the new root. \"\"\" root.right = insert(root.right, key) return root # Iterative approach to# delete 'key' from the BST. def deleteIterative(root, key): curr = root prev = None # First check if the key is # actually present in the BST. # the variable prev points to the # parent of the key to be deleted while(curr != None and curr.data != key): prev = curr if curr.data < key: curr = curr.right else: curr = curr.left if curr == None: print(\"Key % d not found in\\ the provided BST.\" % key) return root # Check if the node to be # deleted has atmost one child if curr.left == None or\\ curr.right == None: # newCurr will replace # the node to be deleted. newCurr = None # if the left child does not exist. if curr.left == None: newCurr = curr.right else: newCurr = curr.left # check if the node to # be deleted is the root. if prev == None: return newCurr # Check if the node to be # deleted is prev's left or # right child and then # replace this with newCurr if curr == prev.left: prev.left = newCurr else: prev.right = newCurr curr = None # node to be deleted # has two children. else: p = None temp = None # Compute the inorder # successor of curr. temp = curr.right while(temp.left != None): p = temp temp = temp.left # check if the parent of the # inorder successor is the root or not. # if it isn't, then make the left # child of its parent equal to the # inorder successor's right child. if p != None: p.left = temp.right else: # if the inorder successor was # the root, then make the right child # of the node to be deleted equal # to the right child of the inorder # successor. curr.right = temp.right curr.data = temp.data temp = None return root # Function to create the BST# and call the Delete Function def main(): \"\"\" 10 / \\ 7 15 / \\ / \\ 5 8 11 18 \"\"\" root = None root = insert(root, 10) root = insert(root, 7) root = insert(root, 5) root = insert(root, 8) root = insert(root, 15) root = insert(root, 11) root = insert(root, 18) print(\"Inorder traversal of original BST:\") inorder(root) print(\"\\n\") # delete node with data value 11 (leaf) root = deleteIterative(root, 11) print(\"Deletion of 11\") print(\"Inorder traversal post deletion:\") inorder(root) print(\"\\n\") # delete node with data value 15 # (internal node with one child) root = deleteIterative(root, 15) print(\"Deletion of 15\") print(\"Inorder traversal post deletion:\") inorder(root) print(\"\\n\") # delete node with data value 10 # (root, two children) root = deleteIterative(root, 10) print(\"Deletion of 10\") print(\"Inorder traversal post deletion:\") inorder(root) print() # Driver Codeif __name__ == \"__main__\": main()",
"e": 36702,
"s": 32345,
"text": null
},
{
"code": null,
"e": 36941,
"s": 36702,
"text": "Inorder traversal of original BST:\n5 7 8 10 11 15 18 \n\nDeletion of 11\nInorder traversal post deletion:\n5 7 8 10 15 18 \n\nDeletion of 15\nInorder traversal post deletion:\n5 7 8 10 18 \n\nDeletion of 10\nInorder traversal post deletion:\n5 7 8 18"
},
{
"code": null,
"e": 36955,
"s": 36943,
"text": "ishansaha05"
},
{
"code": null,
"e": 36967,
"s": 36955,
"text": "anikaseth98"
},
{
"code": null,
"e": 36987,
"s": 36967,
"text": "Binary Search Trees"
},
{
"code": null,
"e": 36991,
"s": 36987,
"text": "BST"
},
{
"code": null,
"e": 37003,
"s": 36991,
"text": "Delete Tree"
},
{
"code": null,
"e": 37010,
"s": 37003,
"text": "Picked"
},
{
"code": null,
"e": 37029,
"s": 37010,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 37045,
"s": 37029,
"text": "Data Structures"
},
{
"code": null,
"e": 37061,
"s": 37045,
"text": "Data Structures"
},
{
"code": null,
"e": 37080,
"s": 37061,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 37178,
"s": 37080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37212,
"s": 37178,
"text": "Print BST keys in the given range"
},
{
"code": null,
"e": 37269,
"s": 37212,
"text": "Find the node with maximum value in a Binary Search Tree"
},
{
"code": null,
"e": 37301,
"s": 37269,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 37334,
"s": 37301,
"text": "Threaded Binary Tree | Insertion"
},
{
"code": null,
"e": 37360,
"s": 37334,
"text": "Floor and Ceil from a BST"
},
{
"code": null,
"e": 37411,
"s": 37360,
"text": "Difference between Stack and Queue Data Structures"
},
{
"code": null,
"e": 37470,
"s": 37411,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 37520,
"s": 37470,
"text": "FIFO (First-In-First-Out) approach in Programming"
},
{
"code": null,
"e": 37564,
"s": 37520,
"text": "Advantages and Disadvantages of Linked List"
}
] |
Tryit Editor v3.7
|
Tryit: HTML elements
|
[] |
How to check if all the values in a numpy array are non-zero?
|
In this program, we have to check whether all the values in a numpy array are zero or not. If all the elements are non-zero, the output is 'True'. Otherwise, the output is 'False'.
The most important Step before implementing the algorithm for this program is to install numpy. Following is the command for installing numpy from command prompt:
pip install numpy
Input:
[1,2,3,4]
Output:
True
Input:
[0,1,2,3]
Output:
False
We shall use the numpy built-in function called 'all(input_array)'. This function checks every number in the array. If the number is non-zero, the function returns 'True'. All non-zero elements are evaluated as 'True', while 0's are evaluated as 'False'.
Step 1: Import numpy.Step 2: Define a numpy array using np.array()Step 3: Pass this array as a parameter to np.all()Step 4: Stop.
Step 1: Import numpy.
Step 2: Define a numpy array using np.array()
Step 3: Pass this array as a parameter to np.all()
import numpy as np
array1 = np.array([1,2,3,4])
array2 = np.array([0,1,2,3])
print("Array 1: ", array1)
print("Array2: ", array2)
print("\nArray 1 is non-zero: ", np.all(array1))
print("Array 2 is non-zero: ", np.all(array2))
Array 1: [1 2 3 4]
|
[
{
"code": null,
"e": 1243,
"s": 1062,
"text": "In this program, we have to check whether all the values in a numpy array are zero or not. If all the elements are non-zero, the output is 'True'. Otherwise, the output is 'False'."
},
{
"code": null,
"e": 1406,
"s": 1243,
"text": "The most important Step before implementing the algorithm for this program is to install numpy. Following is the command for installing numpy from command prompt:"
},
{
"code": null,
"e": 1424,
"s": 1406,
"text": "pip install numpy"
},
{
"code": null,
"e": 1431,
"s": 1424,
"text": "Input:"
},
{
"code": null,
"e": 1441,
"s": 1431,
"text": "[1,2,3,4]"
},
{
"code": null,
"e": 1449,
"s": 1441,
"text": "Output:"
},
{
"code": null,
"e": 1454,
"s": 1449,
"text": "True"
},
{
"code": null,
"e": 1461,
"s": 1454,
"text": "Input:"
},
{
"code": null,
"e": 1471,
"s": 1461,
"text": "[0,1,2,3]"
},
{
"code": null,
"e": 1479,
"s": 1471,
"text": "Output:"
},
{
"code": null,
"e": 1485,
"s": 1479,
"text": "False"
},
{
"code": null,
"e": 1740,
"s": 1485,
"text": "We shall use the numpy built-in function called 'all(input_array)'. This function checks every number in the array. If the number is non-zero, the function returns 'True'. All non-zero elements are evaluated as 'True', while 0's are evaluated as 'False'."
},
{
"code": null,
"e": 1870,
"s": 1740,
"text": "Step 1: Import numpy.Step 2: Define a numpy array using np.array()Step 3: Pass this array as a parameter to np.all()Step 4: Stop."
},
{
"code": null,
"e": 1892,
"s": 1870,
"text": "Step 1: Import numpy."
},
{
"code": null,
"e": 1938,
"s": 1892,
"text": "Step 2: Define a numpy array using np.array()"
},
{
"code": null,
"e": 1989,
"s": 1938,
"text": "Step 3: Pass this array as a parameter to np.all()"
},
{
"code": null,
"e": 2217,
"s": 1989,
"text": "import numpy as np\n\narray1 = np.array([1,2,3,4])\narray2 = np.array([0,1,2,3])\n\nprint(\"Array 1: \", array1)\nprint(\"Array2: \", array2)\nprint(\"\\nArray 1 is non-zero: \", np.all(array1))\nprint(\"Array 2 is non-zero: \", np.all(array2))"
},
{
"code": null,
"e": 2236,
"s": 2217,
"text": "Array 1: [1 2 3 4]"
}
] |
Power Analysis Made Easy. So easy, you can do it by hand. | by Rezwan Hoppe-Islam | Towards Data Science
|
You’ve redesigned your site’s landing page and now you need to A/B test it. How long should you run the test for? This article will demonstrate how to answer this question using a sample size calculation (“power analysis”).
Statistics can be a daunting subject to learn, and it doesn’t have to be. The aim of these guides is to make statistical tools more accessible to people. Make sure that you’re comfortable with the concept of the sampling distribution (see here if you need a refresher) and the calculation of the standard error for a proportion metric (see here). Enjoy!
You want to A/B test a redesign of your landing page. The current landing page sees an average of 200 visitors per day and has a click-through-rate (CTR) of 5%. You believe that the redesign will deliver a CTR of at least 7%. Once we allocate traffic evenly, the current landing page (Control) should see 100 visitors per day, and the redesign (Test) should also see 100 visitors per day:
How many days should you run the test for in order to validate that the Test indeed outperforms the Control?
Let’s say we plan to run our A/B test for just 7 days at which point we would have collected 700 visitors per group. Let’s compute the sampling distribution for the null hypothesis (no difference in population CTRs) and for the alternative hypothesis (a true difference in population CTRs).
Step 1: Calculate the pooled sample proportion (p).
Step 2: Use p to calculate the standard error (se).
Step 3: Compute the sampling distributions.
H0 (null hypothesis): a normal distribution with mean = 0, standard deviation = 0.013.
HA (alternative hypothesis): a normal distribution with mean = 0.02, standard deviation = 0.013.
Let’s plot these distributions:
At a significance level (α) of 0.05, the critical value is 0.0249. This means:
If H0 is true, then the decision to reject it would be incorrect (a Type 1 error). This would occur at a rate of 5 out of 100 experiments (α).
If HA is indeed true, then the decision to reject H0 would be correct. This would occur at a rate of 35 out of 100 experiments (1-β). This rate is also referred to as the power of a test.
If H0 is indeed true, then the decision not to reject it would be correct. This would occur at a rate of 95 out of 100 experiments (1-α).
If HA is true, then the decision not to reject H0 would be incorrect (a Type 2 error). This would occur at a rate of 65 out of 100 experiments (β).
To summarize:
Our decision to run the A/B test for only 7 days would result in us unable to detect the uplift from the Test group in 65 out of 100 experiments. This error rate is too high! Typically, we’d want to bring this value down to 20% which is equivalent to a power of 80%. We can achieve this by increasing our sample size.
Recap: By running the A/B test for 7 days and, therefore, collecting a sample size of 700 visitors per group, the power of our experiment is only 35%. To reach a power of 80%, we’d need to increase our sample size, which means letting the A/B test run longer.
What sample size would we need to obtain a test with 80% power?
Let’s transform our sampling distribution under the null hypothesis to a standard normal distribution to make the calculations more straightforward:
The critical value at 0.05 significance is ~1.96 which you can obtain from a look-up table.
If we now consider the sampling distribution given the alternative hypothesis, then we want the area under the curve between -1.96 and 1.96 to equal 20% (for 80% power). Therefore, the critical value has to be a distance of ~0.84 away from the mean (also available from a look-up table).
So the total standardized difference between means must be 1.96 + 0.84 = 2.8.
This may be easier to understand graphically:
We also know that the real difference between means is 0.02, therefore, the standardized difference equals 0.02 / se. So we can construct an equality and solve for n:
So we’d need to collect 2,211 observations per group. At a rate of 100 visitors per day per group, we’d need to run the test for at least 23 days to obtain an experiment with 80% power. With this sample size, if the redesign page indeed delivers at least 7% CTR, then we’d detect this uplift in 80 out of 100 experiments.
Recap: Referring to the standard normal distribution, we were able to determine that the standardized difference between means should be ~2.8 for 80% power. We were then able to express this in terms of the standard error and then solve for n. We calculated n = 2,211 observations.
By this point, you should feel fairly comfortable with the overall framework of a sample size calculation (power analysis). Now let’s see how we can reduce all the above-mentioned steps into just a few lines of code. In R we would write:
Which produces:
[1] "absolute difference (Test — Control)"0.02[1] "pooled sample proportion"0.06[1] "standardized distance for requested power"2.80158521811297[1] "solve for n"2213.38408508644
|
[
{
"code": null,
"e": 396,
"s": 172,
"text": "You’ve redesigned your site’s landing page and now you need to A/B test it. How long should you run the test for? This article will demonstrate how to answer this question using a sample size calculation (“power analysis”)."
},
{
"code": null,
"e": 750,
"s": 396,
"text": "Statistics can be a daunting subject to learn, and it doesn’t have to be. The aim of these guides is to make statistical tools more accessible to people. Make sure that you’re comfortable with the concept of the sampling distribution (see here if you need a refresher) and the calculation of the standard error for a proportion metric (see here). Enjoy!"
},
{
"code": null,
"e": 1139,
"s": 750,
"text": "You want to A/B test a redesign of your landing page. The current landing page sees an average of 200 visitors per day and has a click-through-rate (CTR) of 5%. You believe that the redesign will deliver a CTR of at least 7%. Once we allocate traffic evenly, the current landing page (Control) should see 100 visitors per day, and the redesign (Test) should also see 100 visitors per day:"
},
{
"code": null,
"e": 1248,
"s": 1139,
"text": "How many days should you run the test for in order to validate that the Test indeed outperforms the Control?"
},
{
"code": null,
"e": 1539,
"s": 1248,
"text": "Let’s say we plan to run our A/B test for just 7 days at which point we would have collected 700 visitors per group. Let’s compute the sampling distribution for the null hypothesis (no difference in population CTRs) and for the alternative hypothesis (a true difference in population CTRs)."
},
{
"code": null,
"e": 1591,
"s": 1539,
"text": "Step 1: Calculate the pooled sample proportion (p)."
},
{
"code": null,
"e": 1643,
"s": 1591,
"text": "Step 2: Use p to calculate the standard error (se)."
},
{
"code": null,
"e": 1687,
"s": 1643,
"text": "Step 3: Compute the sampling distributions."
},
{
"code": null,
"e": 1774,
"s": 1687,
"text": "H0 (null hypothesis): a normal distribution with mean = 0, standard deviation = 0.013."
},
{
"code": null,
"e": 1871,
"s": 1774,
"text": "HA (alternative hypothesis): a normal distribution with mean = 0.02, standard deviation = 0.013."
},
{
"code": null,
"e": 1903,
"s": 1871,
"text": "Let’s plot these distributions:"
},
{
"code": null,
"e": 1982,
"s": 1903,
"text": "At a significance level (α) of 0.05, the critical value is 0.0249. This means:"
},
{
"code": null,
"e": 2125,
"s": 1982,
"text": "If H0 is true, then the decision to reject it would be incorrect (a Type 1 error). This would occur at a rate of 5 out of 100 experiments (α)."
},
{
"code": null,
"e": 2313,
"s": 2125,
"text": "If HA is indeed true, then the decision to reject H0 would be correct. This would occur at a rate of 35 out of 100 experiments (1-β). This rate is also referred to as the power of a test."
},
{
"code": null,
"e": 2451,
"s": 2313,
"text": "If H0 is indeed true, then the decision not to reject it would be correct. This would occur at a rate of 95 out of 100 experiments (1-α)."
},
{
"code": null,
"e": 2599,
"s": 2451,
"text": "If HA is true, then the decision not to reject H0 would be incorrect (a Type 2 error). This would occur at a rate of 65 out of 100 experiments (β)."
},
{
"code": null,
"e": 2613,
"s": 2599,
"text": "To summarize:"
},
{
"code": null,
"e": 2931,
"s": 2613,
"text": "Our decision to run the A/B test for only 7 days would result in us unable to detect the uplift from the Test group in 65 out of 100 experiments. This error rate is too high! Typically, we’d want to bring this value down to 20% which is equivalent to a power of 80%. We can achieve this by increasing our sample size."
},
{
"code": null,
"e": 3191,
"s": 2931,
"text": "Recap: By running the A/B test for 7 days and, therefore, collecting a sample size of 700 visitors per group, the power of our experiment is only 35%. To reach a power of 80%, we’d need to increase our sample size, which means letting the A/B test run longer."
},
{
"code": null,
"e": 3255,
"s": 3191,
"text": "What sample size would we need to obtain a test with 80% power?"
},
{
"code": null,
"e": 3404,
"s": 3255,
"text": "Let’s transform our sampling distribution under the null hypothesis to a standard normal distribution to make the calculations more straightforward:"
},
{
"code": null,
"e": 3496,
"s": 3404,
"text": "The critical value at 0.05 significance is ~1.96 which you can obtain from a look-up table."
},
{
"code": null,
"e": 3784,
"s": 3496,
"text": "If we now consider the sampling distribution given the alternative hypothesis, then we want the area under the curve between -1.96 and 1.96 to equal 20% (for 80% power). Therefore, the critical value has to be a distance of ~0.84 away from the mean (also available from a look-up table)."
},
{
"code": null,
"e": 3862,
"s": 3784,
"text": "So the total standardized difference between means must be 1.96 + 0.84 = 2.8."
},
{
"code": null,
"e": 3908,
"s": 3862,
"text": "This may be easier to understand graphically:"
},
{
"code": null,
"e": 4075,
"s": 3908,
"text": "We also know that the real difference between means is 0.02, therefore, the standardized difference equals 0.02 / se. So we can construct an equality and solve for n:"
},
{
"code": null,
"e": 4397,
"s": 4075,
"text": "So we’d need to collect 2,211 observations per group. At a rate of 100 visitors per day per group, we’d need to run the test for at least 23 days to obtain an experiment with 80% power. With this sample size, if the redesign page indeed delivers at least 7% CTR, then we’d detect this uplift in 80 out of 100 experiments."
},
{
"code": null,
"e": 4679,
"s": 4397,
"text": "Recap: Referring to the standard normal distribution, we were able to determine that the standardized difference between means should be ~2.8 for 80% power. We were then able to express this in terms of the standard error and then solve for n. We calculated n = 2,211 observations."
},
{
"code": null,
"e": 4917,
"s": 4679,
"text": "By this point, you should feel fairly comfortable with the overall framework of a sample size calculation (power analysis). Now let’s see how we can reduce all the above-mentioned steps into just a few lines of code. In R we would write:"
},
{
"code": null,
"e": 4933,
"s": 4917,
"text": "Which produces:"
}
] |
Create a Pandas Dataframe from a dict of equal length lists in Python
|
The Dataframe in pandas can be created using various options. One of the option is to take a dictionary and convert it to a Dataframe. In this article we will see how to take three lists of equal length and convert them to a pandas dataframe using a python dictionary.
In this approach we have the lists declared individually. Then each of them is used as a value for the appropriate key inside a dictionary definition. Finally the pandas method called pd.Dataframe is applied to the dictionary.
Live Demo
import pandas as pd
# Lists for Exam schedule
Days = ['Mon', 'Tue', 'Wed','Thu', 'Fri']
Sub = ['Chemisry','Physics','Maths','English','Biology']
Time = ['2 PM', '10 AM', '11 AM','1 PM', '3 PM']
# Dictionary for Exam Schedule
Exam_Schedule = {'Exam Day': Days,
'Exam Subject': Sub,
'Exam Time': Time}
# Dictionary to DataFrame
Exam_Schedule_df = pd.DataFrame(Exam_Schedule)
print(Exam_Schedule_df)
Running the above code gives us the following result −
Exam Day Exam Subject Exam Time
0 Mon Chemisry 2 PM
1 Tue Physics 10 AM
2 Wed Maths 11 AM
3 Thu English 1 PM
4 Fri Biology 3 PM
In this approach we take the lists directly as the values inside the dictionary instead of declaring them individually. Then the dictionary is converted to the pandas dataframe in a similar manner as above.
Live Demo
import pandas as pd
# Dictionary for Exam Schedule
Exam_Schedule = {
'Exam Day': ['Mon', 'Tue', 'Wed','Thu', 'Fri'],
'Exam Subject': ['Chemisry','Physics','Maths','English','Biology'],
'Exam Time': ['2 PM', '10 AM', '11 AM','1 PM', '3 PM']
}
# Dictionary to DataFrame
Exam_Schedule_df = pd.DataFrame(Exam_Schedule)
print(Exam_Schedule_df)
Running the above code gives us the following result −
Exam Day Exam Subject Exam Time
0 Mon Chemisry 2 PM
1 Tue Physics 10 AM
2 Wed Maths 11 AM
3 Thu English 1 PM
4 Fri Biology 3 PM
|
[
{
"code": null,
"e": 1331,
"s": 1062,
"text": "The Dataframe in pandas can be created using various options. One of the option is to take a dictionary and convert it to a Dataframe. In this article we will see how to take three lists of equal length and convert them to a pandas dataframe using a python dictionary."
},
{
"code": null,
"e": 1558,
"s": 1331,
"text": "In this approach we have the lists declared individually. Then each of them is used as a value for the appropriate key inside a dictionary definition. Finally the pandas method called pd.Dataframe is applied to the dictionary."
},
{
"code": null,
"e": 1569,
"s": 1558,
"text": " Live Demo"
},
{
"code": null,
"e": 2000,
"s": 1569,
"text": "import pandas as pd\n\n# Lists for Exam schedule\nDays = ['Mon', 'Tue', 'Wed','Thu', 'Fri']\nSub = ['Chemisry','Physics','Maths','English','Biology']\nTime = ['2 PM', '10 AM', '11 AM','1 PM', '3 PM']\n\n# Dictionary for Exam Schedule\nExam_Schedule = {'Exam Day': Days,\n 'Exam Subject': Sub,\n 'Exam Time': Time}\n\n# Dictionary to DataFrame\nExam_Schedule_df = pd.DataFrame(Exam_Schedule)\n\nprint(Exam_Schedule_df)"
},
{
"code": null,
"e": 2055,
"s": 2000,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2246,
"s": 2055,
"text": " Exam Day Exam Subject Exam Time\n0 Mon Chemisry 2 PM\n1 Tue Physics 10 AM\n2 Wed Maths 11 AM\n3 Thu English 1 PM\n4 Fri Biology 3 PM"
},
{
"code": null,
"e": 2453,
"s": 2246,
"text": "In this approach we take the lists directly as the values inside the dictionary instead of declaring them individually. Then the dictionary is converted to the pandas dataframe in a similar manner as above."
},
{
"code": null,
"e": 2464,
"s": 2453,
"text": " Live Demo"
},
{
"code": null,
"e": 2806,
"s": 2464,
"text": "import pandas as pd\n\n# Dictionary for Exam Schedule\nExam_Schedule = {\n'Exam Day': ['Mon', 'Tue', 'Wed','Thu', 'Fri'],\n'Exam Subject': ['Chemisry','Physics','Maths','English','Biology'],\n'Exam Time': ['2 PM', '10 AM', '11 AM','1 PM', '3 PM']\n}\n\n# Dictionary to DataFrame\nExam_Schedule_df = pd.DataFrame(Exam_Schedule)\n\nprint(Exam_Schedule_df)"
},
{
"code": null,
"e": 2861,
"s": 2806,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3070,
"s": 2861,
"text": " Exam Day Exam Subject Exam Time\n0 Mon Chemisry 2 PM\n1 Tue Physics 10 AM\n2 Wed Maths 11 AM\n3 Thu English 1 PM\n4 Fri Biology 3 PM"
}
] |
Bash Scripting - How to read a file line by line - GeeksforGeeks
|
22 Nov, 2021
In this article, we are going to see how to read a file line by line in Bash scripting.
There might be instances where you want to read the contents of a file line by line using a BASH script. In this section, we will look at different ways to do just that. We will use BASH commands and tools to achieve that result. We make use of the read and cat commands, for loops, while loops, etc to read from the file and iterate over the file line by line with a few lines of script in BASH.
We can use the read command to read the contents of a file line by line. We use the -r argument to the read command to avoid any backslash-escaped characters.
#!usr/bin/env bash
file="temp.txt"
while read -r line; do
echo -e "$line\n"
done <$file
In the following example, we can see that we have an iteration over a file line by line and we store the contents of a single line in the variable “line“. The file name is stored in the variable file and this can be customized as per requirements. You can run the script using the following command (Here filereader.sh can be any name you give to your script).
bash filereader.sh
We use the read command with -r argument to read the contents without escaping the backslash character. We read the content of each line and store that in the variable line and inside the while loop we echo with a formatted -e argument to use special characters like \n and print the contents of the line variable.
The file can be also inputted by parsing it as a positional parameter.
bash filereader.sh filename
The filename can be any file you want to read the contents of. You need to change the script where the file variable has been declared.
file=$1
This will take the first parameter after the script name as the filename to be used in the script. Hence we can make the script dynamically change the file as per the input given.
From this approach, we can read the contents of a file using the cat command and the for a loop. We use the same approach for a loop as in the while loop but we store the contents of the file in a variable using the cat command. The for loop iterates over the lines in the cat command’s output one by one until it reaches EOF or the end of the file.
Here as well we can incorporate the positional parameter as a filename. We need to replace the filename with $1 in the script.
file=$(cat $1)
This will take the file from the command line argument and parse it to the cat command to further process the script.
#!usr/bin/env bash
file=$(cat temp.txt)
for line in $file
do
echo -e "$line\n"
done
Thus, from the above examples, we were able to read the contents of a file line by line in a BASH script.
Bash-Script
Picked
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++
nohup Command in Linux with Examples
scp command in Linux with Examples
chown command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Basic Operators in Shell Scripting
SED command in Linux | Set 2
Docker - COPY Instruction
Named Pipe or FIFO with example C program
|
[
{
"code": null,
"e": 24432,
"s": 24404,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 24520,
"s": 24432,
"text": "In this article, we are going to see how to read a file line by line in Bash scripting."
},
{
"code": null,
"e": 24917,
"s": 24520,
"text": "There might be instances where you want to read the contents of a file line by line using a BASH script. In this section, we will look at different ways to do just that. We will use BASH commands and tools to achieve that result. We make use of the read and cat commands, for loops, while loops, etc to read from the file and iterate over the file line by line with a few lines of script in BASH."
},
{
"code": null,
"e": 25077,
"s": 24917,
"text": "We can use the read command to read the contents of a file line by line. We use the -r argument to the read command to avoid any backslash-escaped characters. "
},
{
"code": null,
"e": 25172,
"s": 25077,
"text": "#!usr/bin/env bash\n\nfile=\"temp.txt\"\n\nwhile read -r line; do\n echo -e \"$line\\n\"\ndone <$file "
},
{
"code": null,
"e": 25534,
"s": 25172,
"text": "In the following example, we can see that we have an iteration over a file line by line and we store the contents of a single line in the variable “line“. The file name is stored in the variable file and this can be customized as per requirements. You can run the script using the following command (Here filereader.sh can be any name you give to your script)."
},
{
"code": null,
"e": 25553,
"s": 25534,
"text": "bash filereader.sh"
},
{
"code": null,
"e": 25868,
"s": 25553,
"text": "We use the read command with -r argument to read the contents without escaping the backslash character. We read the content of each line and store that in the variable line and inside the while loop we echo with a formatted -e argument to use special characters like \\n and print the contents of the line variable."
},
{
"code": null,
"e": 25940,
"s": 25868,
"text": "The file can be also inputted by parsing it as a positional parameter. "
},
{
"code": null,
"e": 25968,
"s": 25940,
"text": "bash filereader.sh filename"
},
{
"code": null,
"e": 26104,
"s": 25968,
"text": "The filename can be any file you want to read the contents of. You need to change the script where the file variable has been declared."
},
{
"code": null,
"e": 26112,
"s": 26104,
"text": "file=$1"
},
{
"code": null,
"e": 26292,
"s": 26112,
"text": "This will take the first parameter after the script name as the filename to be used in the script. Hence we can make the script dynamically change the file as per the input given."
},
{
"code": null,
"e": 26642,
"s": 26292,
"text": "From this approach, we can read the contents of a file using the cat command and the for a loop. We use the same approach for a loop as in the while loop but we store the contents of the file in a variable using the cat command. The for loop iterates over the lines in the cat command’s output one by one until it reaches EOF or the end of the file."
},
{
"code": null,
"e": 26769,
"s": 26642,
"text": "Here as well we can incorporate the positional parameter as a filename. We need to replace the filename with $1 in the script."
},
{
"code": null,
"e": 26784,
"s": 26769,
"text": "file=$(cat $1)"
},
{
"code": null,
"e": 26903,
"s": 26784,
"text": "This will take the file from the command line argument and parse it to the cat command to further process the script. "
},
{
"code": null,
"e": 26993,
"s": 26903,
"text": "#!usr/bin/env bash\n\nfile=$(cat temp.txt)\n\nfor line in $file\ndo\n echo -e \"$line\\n\"\ndone"
},
{
"code": null,
"e": 27099,
"s": 26993,
"text": "Thus, from the above examples, we were able to read the contents of a file line by line in a BASH script."
},
{
"code": null,
"e": 27111,
"s": 27099,
"text": "Bash-Script"
},
{
"code": null,
"e": 27118,
"s": 27111,
"text": "Picked"
},
{
"code": null,
"e": 27129,
"s": 27118,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27227,
"s": 27129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27236,
"s": 27227,
"text": "Comments"
},
{
"code": null,
"e": 27249,
"s": 27236,
"text": "Old Comments"
},
{
"code": null,
"e": 27275,
"s": 27249,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27312,
"s": 27275,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27347,
"s": 27312,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27384,
"s": 27347,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27424,
"s": 27384,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 27458,
"s": 27424,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27493,
"s": 27458,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 27522,
"s": 27493,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27548,
"s": 27522,
"text": "Docker - COPY Instruction"
}
] |
Angular Material 7 - Slider
|
The <mat-slider>, an Angular Directive, is used as a enhanced range selector with material design styling and animation capabilities.
In this chapter, we will showcase the configuration required to draw a slider control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatSliderModule, MatCheckboxModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatSliderModule, MatCheckboxModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<mat-slider
class = "tp-margin"
[disabled] = "disabled"
[invert] = "invert"
[thumbLabel] = "thumbLabel"
[(ngModel)] = "value"
[vertical] = "vertical">
</mat-slider>
<section class = "tp-section">
<mat-checkbox class = "tp-margin" [(ngModel)] = "thumbLabel">Show thumb label</mat-checkbox>
</section>
<section class = "tp-section">
<mat-checkbox class = "tp-margin" [(ngModel)] = "vertical">Vertical</mat-checkbox>
<mat-checkbox class = "tp-margin" [(ngModel)] = "invert">Inverted</mat-checkbox>
</section>
<section class = "tp-section">
<mat-checkbox class = "tp-margin" [(ngModel)] = "disabled">Disabled</mat-checkbox>
</section>
Following is the content of the modified CSS file app.component.css.
.tp-section {
display: flex;
align-content: center;
align-items: center;
height: 60px;
}
.tp-margin {
margin: 30px;
}
.mat-slider-horizontal {
width: 300px;
}
.mat-slider-vertical {
height: 300px;
}
Following is the content of the modified ts file app.component.ts.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'materialApp';
disabled = false;
invert = false;
thumbLabel = false;
value = 0;
vertical = false;
}
Verify the result.
As first, we've created four check boxes using mat-checkbox and bind them using ngModel with variables. These properties will be used to customize the slider.
As first, we've created four check boxes using mat-checkbox and bind them using ngModel with variables. These properties will be used to customize the slider.
Then, we've created the slider and showcased its various attributes bound with variables in .ts file.
Then, we've created the slider and showcased its various attributes bound with variables in .ts file.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2889,
"s": 2755,
"text": "The <mat-slider>, an Angular Directive, is used as a enhanced range selector with material design styling and animation capabilities."
},
{
"code": null,
"e": 2999,
"s": 2889,
"text": "In this chapter, we will showcase the configuration required to draw a slider control using Angular Material."
},
{
"code": null,
"e": 3110,
"s": 2999,
"text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −"
},
{
"code": null,
"e": 3184,
"s": 3110,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3837,
"s": 3184,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatSliderModule, MatCheckboxModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatSliderModule, MatCheckboxModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3913,
"s": 3837,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 4585,
"s": 3913,
"text": "<mat-slider\n class = \"tp-margin\"\n [disabled] = \"disabled\"\n [invert] = \"invert\" \n [thumbLabel] = \"thumbLabel\" \n [(ngModel)] = \"value\"\n [vertical] = \"vertical\">\n</mat-slider>\n<section class = \"tp-section\">\n <mat-checkbox class = \"tp-margin\" [(ngModel)] = \"thumbLabel\">Show thumb label</mat-checkbox>\n</section>\n<section class = \"tp-section\">\n <mat-checkbox class = \"tp-margin\" [(ngModel)] = \"vertical\">Vertical</mat-checkbox>\n <mat-checkbox class = \"tp-margin\" [(ngModel)] = \"invert\">Inverted</mat-checkbox>\n</section>\n<section class = \"tp-section\">\n <mat-checkbox class = \"tp-margin\" [(ngModel)] = \"disabled\">Disabled</mat-checkbox>\n</section>"
},
{
"code": null,
"e": 4654,
"s": 4585,
"text": "Following is the content of the modified CSS file app.component.css."
},
{
"code": null,
"e": 4875,
"s": 4654,
"text": ".tp-section {\n display: flex;\n align-content: center;\n align-items: center;\n height: 60px;\n}\n.tp-margin {\n margin: 30px;\n}\n\n.mat-slider-horizontal {\n width: 300px;\n}\n.mat-slider-vertical {\n height: 300px;\n}"
},
{
"code": null,
"e": 4942,
"s": 4875,
"text": "Following is the content of the modified ts file app.component.ts."
},
{
"code": null,
"e": 5259,
"s": 4942,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'materialApp'; \n disabled = false;\n invert = false;\n thumbLabel = false;\n value = 0;\n vertical = false;\n}"
},
{
"code": null,
"e": 5278,
"s": 5259,
"text": "Verify the result."
},
{
"code": null,
"e": 5437,
"s": 5278,
"text": "As first, we've created four check boxes using mat-checkbox and bind them using ngModel with variables. These properties will be used to customize the slider."
},
{
"code": null,
"e": 5596,
"s": 5437,
"text": "As first, we've created four check boxes using mat-checkbox and bind them using ngModel with variables. These properties will be used to customize the slider."
},
{
"code": null,
"e": 5698,
"s": 5596,
"text": "Then, we've created the slider and showcased its various attributes bound with variables in .ts file."
},
{
"code": null,
"e": 5800,
"s": 5698,
"text": "Then, we've created the slider and showcased its various attributes bound with variables in .ts file."
},
{
"code": null,
"e": 5835,
"s": 5800,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5849,
"s": 5835,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5884,
"s": 5849,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5898,
"s": 5884,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5933,
"s": 5898,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5953,
"s": 5933,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5988,
"s": 5953,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6005,
"s": 5988,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6038,
"s": 6005,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6050,
"s": 6038,
"text": " Senol Atac"
},
{
"code": null,
"e": 6085,
"s": 6050,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6097,
"s": 6085,
"text": " Senol Atac"
},
{
"code": null,
"e": 6104,
"s": 6097,
"text": " Print"
},
{
"code": null,
"e": 6115,
"s": 6104,
"text": " Add Notes"
}
] |
Ternary Operator in C#
|
Ternary operator is a Conditional operator in C#. It takes three arguments and evaluates a Boolean expression.
For example −
b = (a == 1) ? 20 : 30;
Above, if the first operand evaluates to true (1), the second operand is evaluated. If the first operand evaluates to false (0), the third operand is evaluated.
The following is an example −
Live Demo
using System;
namespace DEMO {
class Program {
static void Main(string[] args) {
int a, b;
a = 10;
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
b = (a == 10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
Console.ReadLine();
}
}
}
Value of b is 30
Value of b is 20
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "Ternary operator is a Conditional operator in C#. It takes three arguments and evaluates a Boolean expression."
},
{
"code": null,
"e": 1187,
"s": 1173,
"text": "For example −"
},
{
"code": null,
"e": 1211,
"s": 1187,
"text": "b = (a == 1) ? 20 : 30;"
},
{
"code": null,
"e": 1372,
"s": 1211,
"text": "Above, if the first operand evaluates to true (1), the second operand is evaluated. If the first operand evaluates to false (0), the third operand is evaluated."
},
{
"code": null,
"e": 1402,
"s": 1372,
"text": "The following is an example −"
},
{
"code": null,
"e": 1413,
"s": 1402,
"text": " Live Demo"
},
{
"code": null,
"e": 1759,
"s": 1413,
"text": "using System;\n\nnamespace DEMO {\n\n class Program {\n\n static void Main(string[] args) {\n\n int a, b;\n a = 10;\n b = (a == 1) ? 20 : 30;\n Console.WriteLine(\"Value of b is {0}\", b);\n\n b = (a == 10) ? 20 : 30;\n Console.WriteLine(\"Value of b is {0}\", b);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1793,
"s": 1759,
"text": "Value of b is 30\nValue of b is 20"
}
] |
TIKA - Language Detection
|
For classification of documents based on the language they are written in a multilingual website, a language detection tool is needed. This tool should accept documents without language annotation (metadata) and add that information in the metadata of the document by detecting the language.
To detect the language of a document, a language profile is constructed and compared with the profile of the known languages. The text set of these known languages is known as a corpus.
A corpus is a collection of texts of a written language that explains how the language is used in real situations.
The corpus is developed from books, transcripts, and other data resources like the Internet. The accuracy of the corpus depends upon the profiling algorithm we use to frame the corpus.
The common way of detecting languages is by using dictionaries. The words used in a given piece of text will be matched with those that are in the dictionaries.
A list of common words used in a language will be the most simple and effective corpus for detecting a particular language, for example, articles a, an, the in English.
Using word sets, a simple algorithm is framed to find the distance between two corpora, which will be equal to the sum of differences between the frequencies of matching words.
Such algorithms suffer from the following problems −
Since the frequency of matching words is very less, the algorithm cannot efficiently work with small texts having few sentences. It needs a lot of text for accurate match.
Since the frequency of matching words is very less, the algorithm cannot efficiently work with small texts having few sentences. It needs a lot of text for accurate match.
It cannot detect word boundaries for languages having compound sentences, and those having no word dividers like spaces or punctuation marks.
It cannot detect word boundaries for languages having compound sentences, and those having no word dividers like spaces or punctuation marks.
Due to these difficulties in using word sets as corpus, individual characters or character groups are considered.
Since the characters that are commonly used in a language are finite in number, it is easy to apply an algorithm based on word frequencies rather than characters. This algorithm works even better in case of certain character sets used in one or very few languages.
This algorithm suffers from the following drawbacks −
It is difficult to differentiate two languages having similar character frequencies.
It is difficult to differentiate two languages having similar character frequencies.
There is no specific tool or algorithm to specifically identify a language with the help of (as corpus) the character set used by multiple languages.
There is no specific tool or algorithm to specifically identify a language with the help of (as corpus) the character set used by multiple languages.
The drawbacks stated above gave rise to a new approach of using character sequences of a given length for profiling corpus. Such sequence of characters are called as N-grams in general, where N represents the length of the character sequence.
N-gram algorithm is an effective approach for language detection, especially in case of European languages like English.
N-gram algorithm is an effective approach for language detection, especially in case of European languages like English.
This algorithm works fine with short texts.
This algorithm works fine with short texts.
Though there are advanced language profiling algorithms to detect multiple languages in a multilingual document having more attractive features, Tika uses the 3-grams algorithm, as it is suitable in most practical situations.
Though there are advanced language profiling algorithms to detect multiple languages in a multilingual document having more attractive features, Tika uses the 3-grams algorithm, as it is suitable in most practical situations.
Among all the 184 standard languages standardized by ISO 639-1, Tika can detect 18 languages. Language detection in Tika is done using the getLanguage() method of the LanguageIdentifier class. This method returns the code name of the language in String format. Given below is the list of the 18 language-code pairs detected by Tika −
While instantiating the LanguageIdentifier class, you should pass the String format of the content to be extracted, or a LanguageProfile class object.
LanguageIdentifier object = new LanguageIdentifier(“this is english”);
Given below is the example program for Language detection in Tika.
import java.io.IOException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.language.LanguageIdentifier;
import org.xml.sax.SAXException;
public class LanguageDetection {
public static void main(String args[])throws IOException, SAXException, TikaException {
LanguageIdentifier identifier = new LanguageIdentifier("this is english ");
String language = identifier.getLanguage();
System.out.println("Language of the given content is : " + language);
}
}
Save the above code as LanguageDetection.java and run it from the command prompt using the following commands −
javac LanguageDetection.java
java LanguageDetection
If you execute the above program it gives the following outpu−
Language of the given content is : en
To detect the language of a given document, you have to parse it using the parse() method. The parse() method parses the content and stores it in the handler object, which was passed to it as one of the arguments. Pass the String format of the handler object to the constructor of the LanguageIdentifier class as shown below −
parser.parse(inputstream, handler, metadata, context);
LanguageIdentifier object = new LanguageIdentifier(handler.toString());
Given below is the complete program that demonstrates how to detect the language of a given document −
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.language.*;
import org.xml.sax.SAXException;
public class DocumentLanguageDetection {
public static void main(final String[] args) throws IOException, SAXException, TikaException {
//Instantiating a file object
File file = new File("Example.txt");
//Parser method parameters
Parser parser = new AutoDetectParser();
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
FileInputStream content = new FileInputStream(file);
//Parsing the given document
parser.parse(content, handler, metadata, new ParseContext());
LanguageIdentifier object = new LanguageIdentifier(handler.toString());
System.out.println("Language name :" + object.getLanguage());
}
}
Save the above code as SetMetadata.java and run it from the command prompt −
javac SetMetadata.java
java SetMetadata
Given below is the content of Example.txt.
Hi students welcome to tutorialspoint
If you execute the above program, it will give you the following output −
Language name :en
Along with the Tika jar, Tika provides a Graphical User Interface application (GUI) and a Command Line Interface (CLI) application. You can execute a Tika application from the command prompt too like other Java applications.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2402,
"s": 2110,
"text": "For classification of documents based on the language they are written in a multilingual website, a language detection tool is needed. This tool should accept documents without language annotation (metadata) and add that information in the metadata of the document by detecting the language."
},
{
"code": null,
"e": 2588,
"s": 2402,
"text": "To detect the language of a document, a language profile is constructed and compared with the profile of the known languages. The text set of these known languages is known as a corpus."
},
{
"code": null,
"e": 2703,
"s": 2588,
"text": "A corpus is a collection of texts of a written language that explains how the language is used in real situations."
},
{
"code": null,
"e": 2888,
"s": 2703,
"text": "The corpus is developed from books, transcripts, and other data resources like the Internet. The accuracy of the corpus depends upon the profiling algorithm we use to frame the corpus."
},
{
"code": null,
"e": 3049,
"s": 2888,
"text": "The common way of detecting languages is by using dictionaries. The words used in a given piece of text will be matched with those that are in the dictionaries."
},
{
"code": null,
"e": 3218,
"s": 3049,
"text": "A list of common words used in a language will be the most simple and effective corpus for detecting a particular language, for example, articles a, an, the in English."
},
{
"code": null,
"e": 3395,
"s": 3218,
"text": "Using word sets, a simple algorithm is framed to find the distance between two corpora, which will be equal to the sum of differences between the frequencies of matching words."
},
{
"code": null,
"e": 3448,
"s": 3395,
"text": "Such algorithms suffer from the following problems −"
},
{
"code": null,
"e": 3620,
"s": 3448,
"text": "Since the frequency of matching words is very less, the algorithm cannot efficiently work with small texts having few sentences. It needs a lot of text for accurate match."
},
{
"code": null,
"e": 3792,
"s": 3620,
"text": "Since the frequency of matching words is very less, the algorithm cannot efficiently work with small texts having few sentences. It needs a lot of text for accurate match."
},
{
"code": null,
"e": 3934,
"s": 3792,
"text": "It cannot detect word boundaries for languages having compound sentences, and those having no word dividers like spaces or punctuation marks."
},
{
"code": null,
"e": 4076,
"s": 3934,
"text": "It cannot detect word boundaries for languages having compound sentences, and those having no word dividers like spaces or punctuation marks."
},
{
"code": null,
"e": 4190,
"s": 4076,
"text": "Due to these difficulties in using word sets as corpus, individual characters or character groups are considered."
},
{
"code": null,
"e": 4455,
"s": 4190,
"text": "Since the characters that are commonly used in a language are finite in number, it is easy to apply an algorithm based on word frequencies rather than characters. This algorithm works even better in case of certain character sets used in one or very few languages."
},
{
"code": null,
"e": 4509,
"s": 4455,
"text": "This algorithm suffers from the following drawbacks −"
},
{
"code": null,
"e": 4594,
"s": 4509,
"text": "It is difficult to differentiate two languages having similar character frequencies."
},
{
"code": null,
"e": 4679,
"s": 4594,
"text": "It is difficult to differentiate two languages having similar character frequencies."
},
{
"code": null,
"e": 4829,
"s": 4679,
"text": "There is no specific tool or algorithm to specifically identify a language with the help of (as corpus) the character set used by multiple languages."
},
{
"code": null,
"e": 4979,
"s": 4829,
"text": "There is no specific tool or algorithm to specifically identify a language with the help of (as corpus) the character set used by multiple languages."
},
{
"code": null,
"e": 5222,
"s": 4979,
"text": "The drawbacks stated above gave rise to a new approach of using character sequences of a given length for profiling corpus. Such sequence of characters are called as N-grams in general, where N represents the length of the character sequence."
},
{
"code": null,
"e": 5343,
"s": 5222,
"text": "N-gram algorithm is an effective approach for language detection, especially in case of European languages like English."
},
{
"code": null,
"e": 5464,
"s": 5343,
"text": "N-gram algorithm is an effective approach for language detection, especially in case of European languages like English."
},
{
"code": null,
"e": 5508,
"s": 5464,
"text": "This algorithm works fine with short texts."
},
{
"code": null,
"e": 5552,
"s": 5508,
"text": "This algorithm works fine with short texts."
},
{
"code": null,
"e": 5778,
"s": 5552,
"text": "Though there are advanced language profiling algorithms to detect multiple languages in a multilingual document having more attractive features, Tika uses the 3-grams algorithm, as it is suitable in most practical situations."
},
{
"code": null,
"e": 6004,
"s": 5778,
"text": "Though there are advanced language profiling algorithms to detect multiple languages in a multilingual document having more attractive features, Tika uses the 3-grams algorithm, as it is suitable in most practical situations."
},
{
"code": null,
"e": 6338,
"s": 6004,
"text": "Among all the 184 standard languages standardized by ISO 639-1, Tika can detect 18 languages. Language detection in Tika is done using the getLanguage() method of the LanguageIdentifier class. This method returns the code name of the language in String format. Given below is the list of the 18 language-code pairs detected by Tika −"
},
{
"code": null,
"e": 6489,
"s": 6338,
"text": "While instantiating the LanguageIdentifier class, you should pass the String format of the content to be extracted, or a LanguageProfile class object."
},
{
"code": null,
"e": 6560,
"s": 6489,
"text": "LanguageIdentifier object = new LanguageIdentifier(“this is english”);"
},
{
"code": null,
"e": 6627,
"s": 6560,
"text": "Given below is the example program for Language detection in Tika."
},
{
"code": null,
"e": 7132,
"s": 6627,
"text": "import java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.language.LanguageIdentifier;\n\nimport org.xml.sax.SAXException;\n\npublic class LanguageDetection {\n\n public static void main(String args[])throws IOException, SAXException, TikaException {\n\n LanguageIdentifier identifier = new LanguageIdentifier(\"this is english \");\n String language = identifier.getLanguage();\n System.out.println(\"Language of the given content is : \" + language);\n }\n}"
},
{
"code": null,
"e": 7244,
"s": 7132,
"text": "Save the above code as LanguageDetection.java and run it from the command prompt using the following commands −"
},
{
"code": null,
"e": 7301,
"s": 7244,
"text": "javac LanguageDetection.java \njava LanguageDetection \n"
},
{
"code": null,
"e": 7365,
"s": 7301,
"text": " If you execute the above program it gives the following outpu−"
},
{
"code": null,
"e": 7404,
"s": 7365,
"text": "Language of the given content is : en\n"
},
{
"code": null,
"e": 7731,
"s": 7404,
"text": "To detect the language of a given document, you have to parse it using the parse() method. The parse() method parses the content and stores it in the handler object, which was passed to it as one of the arguments. Pass the String format of the handler object to the constructor of the LanguageIdentifier class as shown below −"
},
{
"code": null,
"e": 7858,
"s": 7731,
"text": "parser.parse(inputstream, handler, metadata, context);\nLanguageIdentifier object = new LanguageIdentifier(handler.toString());"
},
{
"code": null,
"e": 7961,
"s": 7858,
"text": "Given below is the complete program that demonstrates how to detect the language of a given document −"
},
{
"code": null,
"e": 9100,
"s": 7961,
"text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.AutoDetectParser;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.Parser;\nimport org.apache.tika.sax.BodyContentHandler;\nimport org.apache.tika.language.*;\n\nimport org.xml.sax.SAXException;\n\npublic class DocumentLanguageDetection {\n\n public static void main(final String[] args) throws IOException, SAXException, TikaException {\n\n //Instantiating a file object\n File file = new File(\"Example.txt\");\n\n //Parser method parameters\n Parser parser = new AutoDetectParser();\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream content = new FileInputStream(file);\n\n //Parsing the given document\n parser.parse(content, handler, metadata, new ParseContext());\n\n LanguageIdentifier object = new LanguageIdentifier(handler.toString());\n System.out.println(\"Language name :\" + object.getLanguage());\n }\n}"
},
{
"code": null,
"e": 9177,
"s": 9100,
"text": "Save the above code as SetMetadata.java and run it from the command prompt −"
},
{
"code": null,
"e": 9222,
"s": 9177,
"text": "javac SetMetadata.java \njava SetMetadata \n"
},
{
"code": null,
"e": 9265,
"s": 9222,
"text": "Given below is the content of Example.txt."
},
{
"code": null,
"e": 9304,
"s": 9265,
"text": "Hi students welcome to tutorialspoint\n"
},
{
"code": null,
"e": 9378,
"s": 9304,
"text": "If you execute the above program, it will give you the following output −"
},
{
"code": null,
"e": 9397,
"s": 9378,
"text": "Language name :en\n"
},
{
"code": null,
"e": 9622,
"s": 9397,
"text": "Along with the Tika jar, Tika provides a Graphical User Interface application (GUI) and a Command Line Interface (CLI) application. You can execute a Tika application from the command prompt too like other Java applications."
},
{
"code": null,
"e": 9629,
"s": 9622,
"text": " Print"
},
{
"code": null,
"e": 9640,
"s": 9629,
"text": " Add Notes"
}
] |
How to add multiple intervals to DATE_ADD() in MySQL?
|
The current date and time is as follows −
mysql> select now();
This will produce the following output −
+---------------------+
| now() |
+---------------------+
| 2019-06-15 12:24:06 |
+---------------------+
1 row in set (0.00 sec)
Let us first create a table −
mysql> create table DemoTable
->(
-> ArrivalDate datetime
-> );
Query OK, 0 rows affected (1.15 sec)
Insert some records in the table using insert command. Here, we are adding multiple intervals to the DATE_ADD() method −
mysql> insert into DemoTable values(DATE_ADD(DATE_ADD(NOW(), INTERVAL 6
MONTH), INTERVAL 1 YEAR));
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(DATE_ADD(DATE_ADD(NOW(), INTERVAL 3
MONTH), INTERVAL 4 YEAR));
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------------+
| ArrivalDate |
+---------------------+
| 2020-12-15 12:23:39 |
| 2023-09-15 12:23:48 |
+---------------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1104,
"s": 1062,
"text": "The current date and time is as follows −"
},
{
"code": null,
"e": 1125,
"s": 1104,
"text": "mysql> select now();"
},
{
"code": null,
"e": 1166,
"s": 1125,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1310,
"s": 1166,
"text": "+---------------------+\n| now() |\n+---------------------+\n| 2019-06-15 12:24:06 |\n+---------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1340,
"s": 1310,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1450,
"s": 1340,
"text": "mysql> create table DemoTable\n ->(\n -> ArrivalDate datetime\n -> );\nQuery OK, 0 rows affected (1.15 sec)"
},
{
"code": null,
"e": 1571,
"s": 1450,
"text": "Insert some records in the table using insert command. Here, we are adding multiple intervals to the DATE_ADD() method −"
},
{
"code": null,
"e": 1842,
"s": 1571,
"text": "mysql> insert into DemoTable values(DATE_ADD(DATE_ADD(NOW(), INTERVAL 6\nMONTH), INTERVAL 1 YEAR));\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DemoTable values(DATE_ADD(DATE_ADD(NOW(), INTERVAL 3\nMONTH), INTERVAL 4 YEAR));\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1902,
"s": 1842,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1933,
"s": 1902,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1974,
"s": 1933,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2143,
"s": 1974,
"text": "+---------------------+\n| ArrivalDate |\n+---------------------+\n| 2020-12-15 12:23:39 |\n| 2023-09-15 12:23:48 |\n+---------------------+\n2 rows in set (0.00 sec)"
}
] |
Accessing value of a specified key in Julia - get(), get!() and getkey() Methods - GeeksforGeeks
|
26 Mar, 2020
The get() is an inbuilt function in julia which is used to return the value stored for the specified key, or the given default value if no mapping for the key is present.
Syntax:get(collection, key, default)
Parameters:
collection: Specified collection.
key: Specified key present in the collection.
default: Specified default value which is returned if no mapping for the key is present in the collection.
Returns: It returns the value stored for the specified key, or the given default value if no mapping for the key is present.
Example:
# Julia program to illustrate # the use of get() method # Getting the value stored for the# specified key, or the given default# value if no mapping for the key is present.D = Dict("a"=>5, "b"=>10, "c"=>15);println(get(D, "a", 1))println(get(D, "b", 2))println(get(D, "c", 3))println(get(D, "d", 4))
Output:
5
10
15
4
The get!() is an inbuilt function in julia which is used to return the value stored for the specified key, or if no mapping for the key is present, store key => default, and return default.
Syntax:get!(collection, key, default)
Parameters:
collection: Specified collection.
key: Specified key present in the collection.
default: Specified default value.
Returns: It returns the value stored for the specified key, or if no mapping for the key is present, store key => default, and return default.
Example:
# Julia program to illustrate # the use of get !() method # Getting the value stored for # the specified key, or if no# mapping for the key is present,# store key => default, and return default.D = Dict("a"=>5, "b"=>10, "c"=>15);println(get !(D, "a", 1))println(get !(D, "b", 2))println(get !(D, "c", 3))println(get !(D, "d", 4))println(D)
Output:
5
10
15
4
Dict("c"=>15, "b"=>10, "a"=>5, "d"=>4)
The getkey() is an inbuilt function in julia which is used to return the key matching argument key if one exists in collection, otherwise return default.
Syntax:get!(collection, key, default)
Parameters:
collection: Specified collection.
key: Specified key present in the collection.
default: Specified default value.
Returns: It returns the key matching argument key if one exists in collection, otherwise return default.
Example:
# Julia program to illustrate # the use of getkey() method # Getting the key matching argument # key if one exists in the collection, # otherwise return default.D = Dict("a"=>5, "b"=>10, "c"=>15);println(getkey(D, "a", 1))println(getkey(D, "b", 6))println(getkey(D, "d", 1))println(getkey(D, "e", 'z'))
Output:
a
b
1
z
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Get array dimensions and size of a dimension in Julia - size() Method
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Working with Excel Files in Julia
Getting the maximum value from a list in Julia - max() Method
Get number of elements of array in Julia - length() Method
Exception handling in Julia
Working with Date and Time in Julia
Getting the absolute value of a number in Julia - abs() Method
NamedTuple in Julia
|
[
{
"code": null,
"e": 24544,
"s": 24516,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24715,
"s": 24544,
"text": "The get() is an inbuilt function in julia which is used to return the value stored for the specified key, or the given default value if no mapping for the key is present."
},
{
"code": null,
"e": 24752,
"s": 24715,
"text": "Syntax:get(collection, key, default)"
},
{
"code": null,
"e": 24764,
"s": 24752,
"text": "Parameters:"
},
{
"code": null,
"e": 24798,
"s": 24764,
"text": "collection: Specified collection."
},
{
"code": null,
"e": 24844,
"s": 24798,
"text": "key: Specified key present in the collection."
},
{
"code": null,
"e": 24951,
"s": 24844,
"text": "default: Specified default value which is returned if no mapping for the key is present in the collection."
},
{
"code": null,
"e": 25076,
"s": 24951,
"text": "Returns: It returns the value stored for the specified key, or the given default value if no mapping for the key is present."
},
{
"code": null,
"e": 25085,
"s": 25076,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of get() method # Getting the value stored for the# specified key, or the given default# value if no mapping for the key is present.D = Dict(\"a\"=>5, \"b\"=>10, \"c\"=>15);println(get(D, \"a\", 1))println(get(D, \"b\", 2))println(get(D, \"c\", 3))println(get(D, \"d\", 4))",
"e": 25386,
"s": 25085,
"text": null
},
{
"code": null,
"e": 25394,
"s": 25386,
"text": "Output:"
},
{
"code": null,
"e": 25405,
"s": 25394,
"text": "5\n10\n15\n4\n"
},
{
"code": null,
"e": 25595,
"s": 25405,
"text": "The get!() is an inbuilt function in julia which is used to return the value stored for the specified key, or if no mapping for the key is present, store key => default, and return default."
},
{
"code": null,
"e": 25633,
"s": 25595,
"text": "Syntax:get!(collection, key, default)"
},
{
"code": null,
"e": 25645,
"s": 25633,
"text": "Parameters:"
},
{
"code": null,
"e": 25679,
"s": 25645,
"text": "collection: Specified collection."
},
{
"code": null,
"e": 25725,
"s": 25679,
"text": "key: Specified key present in the collection."
},
{
"code": null,
"e": 25759,
"s": 25725,
"text": "default: Specified default value."
},
{
"code": null,
"e": 25902,
"s": 25759,
"text": "Returns: It returns the value stored for the specified key, or if no mapping for the key is present, store key => default, and return default."
},
{
"code": null,
"e": 25911,
"s": 25902,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of get !() method # Getting the value stored for # the specified key, or if no# mapping for the key is present,# store key => default, and return default.D = Dict(\"a\"=>5, \"b\"=>10, \"c\"=>15);println(get !(D, \"a\", 1))println(get !(D, \"b\", 2))println(get !(D, \"c\", 3))println(get !(D, \"d\", 4))println(D)",
"e": 26252,
"s": 25911,
"text": null
},
{
"code": null,
"e": 26260,
"s": 26252,
"text": "Output:"
},
{
"code": null,
"e": 26310,
"s": 26260,
"text": "5\n10\n15\n4\nDict(\"c\"=>15, \"b\"=>10, \"a\"=>5, \"d\"=>4)\n"
},
{
"code": null,
"e": 26464,
"s": 26310,
"text": "The getkey() is an inbuilt function in julia which is used to return the key matching argument key if one exists in collection, otherwise return default."
},
{
"code": null,
"e": 26502,
"s": 26464,
"text": "Syntax:get!(collection, key, default)"
},
{
"code": null,
"e": 26514,
"s": 26502,
"text": "Parameters:"
},
{
"code": null,
"e": 26548,
"s": 26514,
"text": "collection: Specified collection."
},
{
"code": null,
"e": 26594,
"s": 26548,
"text": "key: Specified key present in the collection."
},
{
"code": null,
"e": 26628,
"s": 26594,
"text": "default: Specified default value."
},
{
"code": null,
"e": 26733,
"s": 26628,
"text": "Returns: It returns the key matching argument key if one exists in collection, otherwise return default."
},
{
"code": null,
"e": 26742,
"s": 26733,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of getkey() method # Getting the key matching argument # key if one exists in the collection, # otherwise return default.D = Dict(\"a\"=>5, \"b\"=>10, \"c\"=>15);println(getkey(D, \"a\", 1))println(getkey(D, \"b\", 6))println(getkey(D, \"d\", 1))println(getkey(D, \"e\", 'z'))",
"e": 27046,
"s": 26742,
"text": null
},
{
"code": null,
"e": 27054,
"s": 27046,
"text": "Output:"
},
{
"code": null,
"e": 27063,
"s": 27054,
"text": "a\nb\n1\nz\n"
},
{
"code": null,
"e": 27069,
"s": 27063,
"text": "Julia"
},
{
"code": null,
"e": 27167,
"s": 27069,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27176,
"s": 27167,
"text": "Comments"
},
{
"code": null,
"e": 27189,
"s": 27176,
"text": "Old Comments"
},
{
"code": null,
"e": 27259,
"s": 27189,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 27307,
"s": 27259,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 27377,
"s": 27307,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 27411,
"s": 27377,
"text": "Working with Excel Files in Julia"
},
{
"code": null,
"e": 27473,
"s": 27411,
"text": "Getting the maximum value from a list in Julia - max() Method"
},
{
"code": null,
"e": 27532,
"s": 27473,
"text": "Get number of elements of array in Julia - length() Method"
},
{
"code": null,
"e": 27560,
"s": 27532,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 27596,
"s": 27560,
"text": "Working with Date and Time in Julia"
},
{
"code": null,
"e": 27659,
"s": 27596,
"text": "Getting the absolute value of a number in Julia - abs() Method"
}
] |
How to use checkbox in Android?
|
This example demonstrates how do I make a specific text on TextView bold in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="MainActivity">
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="68dp"
android:text="Pizza"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Coffee"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Burger"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox2" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="184dp"
android:text="Order"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox3" />
</android.support.constraint.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
CheckBox pizza,coffee,burger;
Button buttonOrder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pizza = findViewById(R.id.checkBox);
coffee = findViewById(R.id.checkBox2);
burger = findViewById(R.id.checkBox3);
buttonOrder = findViewById(R.id.button);
buttonOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int totalAmount = 0;
StringBuilder result = new StringBuilder();
result.append("Selected Items");
if (pizza.isChecked()) {
result.append("\nPizza 100Rs");
totalAmount += 100;
}
if (coffee.isChecked()) {
result.append("\nCoffe 50Rs");
totalAmount += 50;
}
if (burger.isChecked()) {
result.append("\nBurger 120Rs");
totalAmount += 120;
}
result.append("\nTotal: " + totalAmount + "Rs");
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "This example demonstrates how do I make a specific text on TextView bold in android."
},
{
"code": null,
"e": 1276,
"s": 1147,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1341,
"s": 1276,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3140,
"s": 1341,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\"MainActivity\">\n <CheckBox\n android:id=\"@+id/checkBox\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginLeft=\"144dp\"\n android:layout_marginTop=\"68dp\"\n android:text=\"Pizza\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n <CheckBox\n android:id=\"@+id/checkBox2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginLeft=\"144dp\"\n android:layout_marginTop=\"28dp\"\n android:text=\"Coffee\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toBottomOf=\"@+id/checkBox\" />\n <CheckBox\n android:id=\"@+id/checkBox3\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginLeft=\"144dp\"\n android:layout_marginTop=\"28dp\"\n android:text=\"Burger\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toBottomOf=\"@+id/checkBox2\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginLeft=\"144dp\"\n android:layout_marginTop=\"184dp\"\n android:text=\"Order\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toBottomOf=\"@+id/checkBox3\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 3197,
"s": 3140,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4682,
"s": 3197,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.CheckBox;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n CheckBox pizza,coffee,burger;\n Button buttonOrder;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n pizza = findViewById(R.id.checkBox);\n coffee = findViewById(R.id.checkBox2);\n burger = findViewById(R.id.checkBox3);\n buttonOrder = findViewById(R.id.button);\n buttonOrder.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n int totalAmount = 0;\n StringBuilder result = new StringBuilder();\n result.append(\"Selected Items\");\n if (pizza.isChecked()) {\n result.append(\"\\nPizza 100Rs\");\n totalAmount += 100;\n }\n if (coffee.isChecked()) {\n result.append(\"\\nCoffe 50Rs\");\n totalAmount += 50;\n }\n if (burger.isChecked()) {\n result.append(\"\\nBurger 120Rs\");\n totalAmount += 120;\n }\n result.append(\"\\nTotal: \" + totalAmount + \"Rs\");\n Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT).show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 4737,
"s": 4682,
"text": "Step 4 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5410,
"s": 4737,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5757,
"s": 5410,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 5798,
"s": 5757,
"text": "Click here to download the project code."
}
] |
Redis - Hash Hmget Command
|
Redis HMGET command is used to get the values associated with the specified fields in the hash stored at the key. If the field does not exist in Redis hash, then a nil value is returned.
Array reply, list of values associated with the given fields, in the same order as they are requested.
Following is the basic syntax of Redis HMGET command.
redis 127.0.0.1:6379> HMGET KEY_NAME FIELD1...FIELDN
redis 127.0.0.1:6379> HSET myhash field1 "foo"
(integer) 1
redis 127.0.0.1:6379> HSET myhash field2 "bar"
(integer) 1
redis 127.0.0.1:6379> HMGET myhash field1 field2 nofield
1) "foo"
2) "bar"
3) (nil)
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2232,
"s": 2045,
"text": "Redis HMGET command is used to get the values associated with the specified fields in the hash stored at the key. If the field does not exist in Redis hash, then a nil value is returned."
},
{
"code": null,
"e": 2335,
"s": 2232,
"text": "Array reply, list of values associated with the given fields, in the same order as they are requested."
},
{
"code": null,
"e": 2389,
"s": 2335,
"text": "Following is the basic syntax of Redis HMGET command."
},
{
"code": null,
"e": 2444,
"s": 2389,
"text": "redis 127.0.0.1:6379> HMGET KEY_NAME FIELD1...FIELDN \n"
},
{
"code": null,
"e": 2654,
"s": 2444,
"text": "redis 127.0.0.1:6379> HSET myhash field1 \"foo\" \n(integer) 1 \nredis 127.0.0.1:6379> HSET myhash field2 \"bar\" \n(integer) 1 \nredis 127.0.0.1:6379> HMGET myhash field1 field2 nofield \n1) \"foo\" \n2) \"bar\" \n3) (nil)\n"
},
{
"code": null,
"e": 2686,
"s": 2654,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2706,
"s": 2686,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2713,
"s": 2706,
"text": " Print"
},
{
"code": null,
"e": 2724,
"s": 2713,
"text": " Add Notes"
}
] |
How to disable autocomplete of an HTML input field ? - GeeksforGeeks
|
06 Sep, 2021
In this article, we will learn how to disable or off autocomplete features of a particular input field in HTML form. As we know that autocomplete feature is used to allow a browser whether to automatically complete filled the input data value based on the values that the user entered before. As the latest browsers supports enabled autocomplete by default. The autocomplete feature faster the process of filling the form. In case of low internet excess or session expired, if the autocomplete is enabled then the browser automatically filled the data values that the user entered before.
Autocomplete attribute take two values:
on: It specifies that autocomplete is enabled.
off: It specifies that the autocomplete is disabled.
If you want to disabled autocomplete feature then follow the approach which are given below:
Approach:
First we create an HTML document that contains an <input> tag.
Use the <input> tag with autocomplete attribute
Set the autocomplete attribute to value “off”.
Example: Below code demonstrates that a form has two input fields, one with autocomplete status is on and in the other field autocomplete feature is off.
HTML
<!DOCTYPE html><html> <head> <title> How to disable autocomplete of an HTML input field? </title> <style> h1, h2 { font-family: impact; } </style></head> <body style="text-align:center;"> <h1>GeeksForGeeks</h1> <h2> How to disable autocomplete of an HTML input field? </h2> <form id="myGeeks"> Name:<input type="text" id="text_id" name="geeks" autocomplete="on"> <br> Address: <input type="Address" name="address" autocomplete="off"> <br><br> <input type="submit"> </form></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
How to auto-resize an image to fit a div container using CSS?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 24894,
"s": 24866,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 25484,
"s": 24894,
"text": "In this article, we will learn how to disable or off autocomplete features of a particular input field in HTML form. As we know that autocomplete feature is used to allow a browser whether to automatically complete filled the input data value based on the values that the user entered before. As the latest browsers supports enabled autocomplete by default. The autocomplete feature faster the process of filling the form. In case of low internet excess or session expired, if the autocomplete is enabled then the browser automatically filled the data values that the user entered before. "
},
{
"code": null,
"e": 25524,
"s": 25484,
"text": "Autocomplete attribute take two values:"
},
{
"code": null,
"e": 25571,
"s": 25524,
"text": "on: It specifies that autocomplete is enabled."
},
{
"code": null,
"e": 25624,
"s": 25571,
"text": "off: It specifies that the autocomplete is disabled."
},
{
"code": null,
"e": 25718,
"s": 25624,
"text": "If you want to disabled autocomplete feature then follow the approach which are given below: "
},
{
"code": null,
"e": 25729,
"s": 25718,
"text": "Approach: "
},
{
"code": null,
"e": 25792,
"s": 25729,
"text": "First we create an HTML document that contains an <input> tag."
},
{
"code": null,
"e": 25840,
"s": 25792,
"text": "Use the <input> tag with autocomplete attribute"
},
{
"code": null,
"e": 25887,
"s": 25840,
"text": "Set the autocomplete attribute to value “off”."
},
{
"code": null,
"e": 26043,
"s": 25889,
"text": "Example: Below code demonstrates that a form has two input fields, one with autocomplete status is on and in the other field autocomplete feature is off."
},
{
"code": null,
"e": 26048,
"s": 26043,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to disable autocomplete of an HTML input field? </title> <style> h1, h2 { font-family: impact; } </style></head> <body style=\"text-align:center;\"> <h1>GeeksForGeeks</h1> <h2> How to disable autocomplete of an HTML input field? </h2> <form id=\"myGeeks\"> Name:<input type=\"text\" id=\"text_id\" name=\"geeks\" autocomplete=\"on\"> <br> Address: <input type=\"Address\" name=\"address\" autocomplete=\"off\"> <br><br> <input type=\"submit\"> </form></body> </html>",
"e": 26697,
"s": 26048,
"text": null
},
{
"code": null,
"e": 26706,
"s": 26697,
"text": "Output: "
},
{
"code": null,
"e": 26843,
"s": 26706,
"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": 26859,
"s": 26843,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26874,
"s": 26859,
"text": "HTML-Questions"
},
{
"code": null,
"e": 26881,
"s": 26874,
"text": "Picked"
},
{
"code": null,
"e": 26886,
"s": 26881,
"text": "HTML"
},
{
"code": null,
"e": 26903,
"s": 26886,
"text": "Web Technologies"
},
{
"code": null,
"e": 26908,
"s": 26903,
"text": "HTML"
},
{
"code": null,
"e": 27006,
"s": 26908,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27015,
"s": 27006,
"text": "Comments"
},
{
"code": null,
"e": 27028,
"s": 27015,
"text": "Old Comments"
},
{
"code": null,
"e": 27052,
"s": 27028,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27089,
"s": 27052,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27109,
"s": 27089,
"text": "Angular File Upload"
},
{
"code": null,
"e": 27138,
"s": 27109,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27200,
"s": 27138,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 27242,
"s": 27200,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27275,
"s": 27242,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27318,
"s": 27275,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27363,
"s": 27318,
"text": "Convert a string to an integer in JavaScript"
}
] |
Can we Overload or Override static methods in java ? - GeeksforGeeks
|
01 Sep, 2021
Let us first define Overloading and Overriding.Overriding: Overriding is a feature of OOP languages like Java that is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in the superclass (or base class). The implementation to be executed is decided at run-time and a decision is made according to the object used for the call. Note that signatures of both methods must be the same. Refer Overriding in Java for details.Overloading: Overloading is also a feature of OOP languages like Java that is related to compile-time (or static) polymorphism. This feature allows different methods to have the same name, but different signatures, especially the number of input parameters and type of input parameters. Note that in both C++ and Java, methods cannot be overloaded according to the return type.Can we overload static methods? The answer is ‘Yes’. We can have two or more static methods with the same name, but differences in input parameters. For example, consider the following Java program.
Java
// filename Test.javapublic class Test { public static void foo() { System.out.println("Test.foo() called "); } public static void foo(int a) { System.out.println("Test.foo(int) called "); } public static void main(String args[]) { Test.foo(); Test.foo(10); }}
Test.foo() called
Test.foo(int) called
Can we overload methods that differ only by static keyword? We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is the same). See the following Java program for example. This behavior is the same in C++ (See point 2 of this).
Java
// filename Test.javapublic class Test { public static void foo() { System.out.println("Test.foo() called "); } public void foo() { // Compiler Error: cannot redefine foo() System.out.println("Test.foo(int) called "); } public static void main(String args[]) { Test.foo(); }}
Output:
Compiler Error, cannot redefine foo()
Can we Override static methods in java? We can declare static methods with the same signature in the subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’. If a derived class defines a static method with the same signature as a static method in the base class, the method in the derived class is hidden by the method in the base class.
Java
/* Java program to show that if static method is redefined by a derived class, then it is not overriding. */ // Superclassclass Base { // Static method in base class which will be hidden in subclass public static void display() { System.out.println("Static or class method from Base"); } // Non-static method which will be overridden in derived class public void print() { System.out.println("Non-static or Instance method from Base"); }} // Subclassclass Derived extends Base { // This method is hidden by display() in Base public static void display() { System.out.println("Static or class method from Derived"); } // This method overrides print() in Base public void print() { System.out.println("Non-static or Instance method from Derived"); }} // Driver classpublic class Test { public static void main(String args[ ]) { Base obj1 = new Derived(); // As per overriding rules this should call to class Derive's static // overridden method. Since static method can not be overridden, it // calls Base's display() obj1.display(); // Here overriding works and Derive's print() is called obj1.print(); }}
Static or class method from Base
Non-static or Instance method from Derived
The following are some important points for method overriding and static methods in Java. 1) For class (or static) methods, the method according to the type of reference is called, not according to the object being referred, which means method call is decided at compile time.2) For instance (or non-static) methods, the method is called according to the type of object being referred, not according to the type of reference, which means method calls is decided at run time.3) An instance method cannot override a static method, and a static method cannot hide an instance method. For example, the following program has two compiler errors.
Java
/* Java program to show that if static methods are redefined by a derived class, then it is not overriding but hidding. */ // Superclassclass Base { // Static method in base class which will be hidden in subclass public static void display() { System.out.println("Static or class method from Base"); } // Non-static method which will be overridden in derived class public void print() { System.out.println("Non-static or Instance method from Base"); }} // Subclassclass Derived extends Base { // Static is removed here (Causes Compiler Error) public void display() { System.out.println("Non-static method from Derived"); } // Static is added here (Causes Compiler Error) public static void print() { System.out.println("Static method from Derived"); }}
4) In a subclass (or Derived Class), we can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods — they are new methods, unique to the subclass.
References: http://docs.oracle.com/javase/tutorial/java/IandI/override.htmlThis article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ashok3612
shivam2608
Java
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
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 25033,
"s": 25005,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 26090,
"s": 25033,
"text": "Let us first define Overloading and Overriding.Overriding: Overriding is a feature of OOP languages like Java that is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in the superclass (or base class). The implementation to be executed is decided at run-time and a decision is made according to the object used for the call. Note that signatures of both methods must be the same. Refer Overriding in Java for details.Overloading: Overloading is also a feature of OOP languages like Java that is related to compile-time (or static) polymorphism. This feature allows different methods to have the same name, but different signatures, especially the number of input parameters and type of input parameters. Note that in both C++ and Java, methods cannot be overloaded according to the return type.Can we overload static methods? The answer is ‘Yes’. We can have two or more static methods with the same name, but differences in input parameters. For example, consider the following Java program. "
},
{
"code": null,
"e": 26095,
"s": 26090,
"text": "Java"
},
{
"code": "// filename Test.javapublic class Test { public static void foo() { System.out.println(\"Test.foo() called \"); } public static void foo(int a) { System.out.println(\"Test.foo(int) called \"); } public static void main(String args[]) { Test.foo(); Test.foo(10); }}",
"e": 26405,
"s": 26095,
"text": null
},
{
"code": null,
"e": 26446,
"s": 26405,
"text": "Test.foo() called \nTest.foo(int) called "
},
{
"code": null,
"e": 26745,
"s": 26446,
"text": "Can we overload methods that differ only by static keyword? We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is the same). See the following Java program for example. This behavior is the same in C++ (See point 2 of this). "
},
{
"code": null,
"e": 26750,
"s": 26745,
"text": "Java"
},
{
"code": "// filename Test.javapublic class Test { public static void foo() { System.out.println(\"Test.foo() called \"); } public void foo() { // Compiler Error: cannot redefine foo() System.out.println(\"Test.foo(int) called \"); } public static void main(String args[]) { Test.foo(); }}",
"e": 27065,
"s": 26750,
"text": null
},
{
"code": null,
"e": 27073,
"s": 27065,
"text": "Output:"
},
{
"code": null,
"e": 27111,
"s": 27073,
"text": "Compiler Error, cannot redefine foo()"
},
{
"code": null,
"e": 27511,
"s": 27111,
"text": "Can we Override static methods in java? We can declare static methods with the same signature in the subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’. If a derived class defines a static method with the same signature as a static method in the base class, the method in the derived class is hidden by the method in the base class. "
},
{
"code": null,
"e": 27516,
"s": 27511,
"text": "Java"
},
{
"code": "/* Java program to show that if static method is redefined by a derived class, then it is not overriding. */ // Superclassclass Base { // Static method in base class which will be hidden in subclass public static void display() { System.out.println(\"Static or class method from Base\"); } // Non-static method which will be overridden in derived class public void print() { System.out.println(\"Non-static or Instance method from Base\"); }} // Subclassclass Derived extends Base { // This method is hidden by display() in Base public static void display() { System.out.println(\"Static or class method from Derived\"); } // This method overrides print() in Base public void print() { System.out.println(\"Non-static or Instance method from Derived\"); }} // Driver classpublic class Test { public static void main(String args[ ]) { Base obj1 = new Derived(); // As per overriding rules this should call to class Derive's static // overridden method. Since static method can not be overridden, it // calls Base's display() obj1.display(); // Here overriding works and Derive's print() is called obj1.print(); }}",
"e": 28782,
"s": 27516,
"text": null
},
{
"code": null,
"e": 28858,
"s": 28782,
"text": "Static or class method from Base\nNon-static or Instance method from Derived"
},
{
"code": null,
"e": 29501,
"s": 28858,
"text": "The following are some important points for method overriding and static methods in Java. 1) For class (or static) methods, the method according to the type of reference is called, not according to the object being referred, which means method call is decided at compile time.2) For instance (or non-static) methods, the method is called according to the type of object being referred, not according to the type of reference, which means method calls is decided at run time.3) An instance method cannot override a static method, and a static method cannot hide an instance method. For example, the following program has two compiler errors. "
},
{
"code": null,
"e": 29506,
"s": 29501,
"text": "Java"
},
{
"code": "/* Java program to show that if static methods are redefined by a derived class, then it is not overriding but hidding. */ // Superclassclass Base { // Static method in base class which will be hidden in subclass public static void display() { System.out.println(\"Static or class method from Base\"); } // Non-static method which will be overridden in derived class public void print() { System.out.println(\"Non-static or Instance method from Base\"); }} // Subclassclass Derived extends Base { // Static is removed here (Causes Compiler Error) public void display() { System.out.println(\"Non-static method from Derived\"); } // Static is added here (Causes Compiler Error) public static void print() { System.out.println(\"Static method from Derived\"); }}",
"e": 30348,
"s": 29506,
"text": null
},
{
"code": null,
"e": 30565,
"s": 30348,
"text": "4) In a subclass (or Derived Class), we can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods — they are new methods, unique to the subclass."
},
{
"code": null,
"e": 30814,
"s": 30565,
"text": "References: http://docs.oracle.com/javase/tutorial/java/IandI/override.htmlThis article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 30824,
"s": 30814,
"text": "ashok3612"
},
{
"code": null,
"e": 30835,
"s": 30824,
"text": "shivam2608"
},
{
"code": null,
"e": 30840,
"s": 30835,
"text": "Java"
},
{
"code": null,
"e": 30845,
"s": 30840,
"text": "Java"
},
{
"code": null,
"e": 30943,
"s": 30845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30958,
"s": 30943,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31002,
"s": 30958,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31024,
"s": 31002,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31075,
"s": 31024,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31111,
"s": 31075,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 31136,
"s": 31111,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31166,
"s": 31136,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31185,
"s": 31166,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31200,
"s": 31185,
"text": "Stream In Java"
}
] |
ReactJS Forwarding Refs - GeeksforGeeks
|
31 Jul, 2021
The forwardRef method in React allows parent components to move down (or “forward”) refs to their children. ForwardRef gives a child component a reference to a DOM entity created by its parent component in React. This helps the child to read and modify the element from any location where it is used.
How does forwardRef work in React?
In React, parent components typically use props to transfer data down to their children. Consider you make a child component with a new set of props to change its behavior. We need a way to change the behavior of a child component without having to look for the state or re-rendering the component. We can do this by using refs. We can access a DOM node that is represented by an element using refs. As a result, we will make changes to it without affecting its state or having to re-render it.
When a child component needs to refer to its parent’s current node, the parent component must have a way for the child to receive its ref. The technique is known as ref forwarding.
Syntax:
React.forwardRef((props, ref) => {})
Parameters: It takes a function with props and ref arguments.
Return Value: This function returns a JSX Element.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react' class App extends React.Component { constructor(props) { super(props) this.aRef = React.createRef() } render() { return ( <> <Counter ref={this.aRef} /> <button onClick={() => { console.log(this.aRef) }}> Ref </button> </> ) }} const Counter = React.forwardRef((props, ref) => { class Counter extends React.Component { constructor(props) { super(props) this.state = { count: 0 } } render() { return ( <div> Count: {this.state.count} <button ref={ref} onClick={() => this.setState( { count: this.state.count + 1 })}> Increment </button> </div> ) } } return <Counter />}) export default App
Explanation: Since the counter is within the function, it can access the props and ref parameters using a closure. The counter is rendered and returned. The ref passed to the Counter component is set to the value of the button element’s ref attribute. The counter element’s ref attribute will now be set to refer to the button element.
The Counter component is rendered by the App component. It starts by creating a ref this.aRef is assigned to the Counter component’s ref attribute as a value. We’ve included a button that logs the value of this.aRef. The this.aRef will hold the HTMLButtonElement of the Incr button in the Counter component. Clicking on the Ref button will confirm that It will log this.aRef which will log the object of the Incr button HTMLButtonElement. It didn’t log the instance of the Counter because the Counter component forwarded it to its child component, the Increment button.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://reactjs.org/docs/forwarding-refs.html
manikarora059
Picked
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 26372,
"s": 26071,
"text": "The forwardRef method in React allows parent components to move down (or “forward”) refs to their children. ForwardRef gives a child component a reference to a DOM entity created by its parent component in React. This helps the child to read and modify the element from any location where it is used."
},
{
"code": null,
"e": 26407,
"s": 26372,
"text": "How does forwardRef work in React?"
},
{
"code": null,
"e": 26902,
"s": 26407,
"text": "In React, parent components typically use props to transfer data down to their children. Consider you make a child component with a new set of props to change its behavior. We need a way to change the behavior of a child component without having to look for the state or re-rendering the component. We can do this by using refs. We can access a DOM node that is represented by an element using refs. As a result, we will make changes to it without affecting its state or having to re-render it."
},
{
"code": null,
"e": 27083,
"s": 26902,
"text": "When a child component needs to refer to its parent’s current node, the parent component must have a way for the child to receive its ref. The technique is known as ref forwarding."
},
{
"code": null,
"e": 27091,
"s": 27083,
"text": "Syntax:"
},
{
"code": null,
"e": 27128,
"s": 27091,
"text": "React.forwardRef((props, ref) => {})"
},
{
"code": null,
"e": 27190,
"s": 27128,
"text": "Parameters: It takes a function with props and ref arguments."
},
{
"code": null,
"e": 27242,
"s": 27190,
"text": "Return Value: This function returns a JSX Element."
},
{
"code": null,
"e": 27270,
"s": 27242,
"text": "Creating React Application:"
},
{
"code": null,
"e": 27334,
"s": 27270,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27366,
"s": 27334,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27466,
"s": 27366,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27480,
"s": 27466,
"text": "cd foldername"
},
{
"code": null,
"e": 27532,
"s": 27480,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27662,
"s": 27532,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 27673,
"s": 27662,
"text": "Javascript"
},
{
"code": "import React from 'react' class App extends React.Component { constructor(props) { super(props) this.aRef = React.createRef() } render() { return ( <> <Counter ref={this.aRef} /> <button onClick={() => { console.log(this.aRef) }}> Ref </button> </> ) }} const Counter = React.forwardRef((props, ref) => { class Counter extends React.Component { constructor(props) { super(props) this.state = { count: 0 } } render() { return ( <div> Count: {this.state.count} <button ref={ref} onClick={() => this.setState( { count: this.state.count + 1 })}> Increment </button> </div> ) } } return <Counter />}) export default App",
"e": 28459,
"s": 27673,
"text": null
},
{
"code": null,
"e": 28796,
"s": 28459,
"text": " Explanation: Since the counter is within the function, it can access the props and ref parameters using a closure. The counter is rendered and returned. The ref passed to the Counter component is set to the value of the button element’s ref attribute. The counter element’s ref attribute will now be set to refer to the button element."
},
{
"code": null,
"e": 29366,
"s": 28796,
"text": "The Counter component is rendered by the App component. It starts by creating a ref this.aRef is assigned to the Counter component’s ref attribute as a value. We’ve included a button that logs the value of this.aRef. The this.aRef will hold the HTMLButtonElement of the Incr button in the Counter component. Clicking on the Ref button will confirm that It will log this.aRef which will log the object of the Incr button HTMLButtonElement. It didn’t log the instance of the Counter because the Counter component forwarded it to its child component, the Increment button."
},
{
"code": null,
"e": 29479,
"s": 29366,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29489,
"s": 29479,
"text": "npm start"
},
{
"code": null,
"e": 29589,
"s": 29489,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output: "
},
{
"code": null,
"e": 29647,
"s": 29589,
"text": "Reference: https://reactjs.org/docs/forwarding-refs.html "
},
{
"code": null,
"e": 29661,
"s": 29647,
"text": "manikarora059"
},
{
"code": null,
"e": 29668,
"s": 29661,
"text": "Picked"
},
{
"code": null,
"e": 29683,
"s": 29668,
"text": "ReactJS-Basics"
},
{
"code": null,
"e": 29691,
"s": 29683,
"text": "ReactJS"
},
{
"code": null,
"e": 29708,
"s": 29691,
"text": "Web Technologies"
},
{
"code": null,
"e": 29806,
"s": 29708,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29833,
"s": 29806,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29875,
"s": 29833,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29913,
"s": 29875,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 29948,
"s": 29913,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 30006,
"s": 29948,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 30046,
"s": 30006,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30079,
"s": 30046,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30124,
"s": 30079,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30174,
"s": 30124,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.