title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Dynamically Resize Buttons When Resizing a Window using Tkinter
Python has many rich libraries for creating and developing GUI-based applications. Tkinter is one of the most commonly used Python libraries for creating GUI-based applications. It has many features like adding widgets and other necessary attributes necessary for creating an application. A button is a widget which can be assigned for some particular task or event. However, to dynamically resize or position the button widget, we can configure its position and layout using the Grid module in tkinter. To resize the button dynamically, we can use rowconfiguration() and coloumnconfiguration() methods. In a tkinter Grid system, there are four attributes which can be used to resize any widget. These attributes generally refer to the direction such as North, South, East, and West. To make the buttons responsive and dynamically resizable according to the screen or window size, we have to use the row and column property in it. #Importing the tkinter library from tkinter import * win= Tk() win.title("Dynamically Resize Buttons") win.geometry("700x500") #Configure Rows and column Grid.rowconfigure(win, 0,weight=1) Grid.columnconfigure(win,0,weight=1) #Create buttons b1= Button(win, text= "C++") b2= Button(win, text= "Java") #Create List of buttons bl= [b1, b2] row_no=0 #Loop through all the buttons and configure it row-wise for button in bl: Grid.rowconfigure(win,row_no, weight=1) row_no+=1 #Adjust the position in grid and make them sticky b1.grid(row=0, column=0, sticky= "nsew") b2.grid(row=1, column=0, stick= "nsew") win.mainloop() Running the above code will generate the output and display two buttons horizontally in a row−order, which can be dynamically resizable according to screen or window size.
[ { "code": null, "e": 1476, "s": 1187, "text": "Python has many rich libraries for creating and developing GUI-based applications.\nTkinter is one of the most commonly used Python libraries for creating GUI-based\napplications. It has many features like adding widgets and other necessary attributes necessary for creating an application." }, { "code": null, "e": 1791, "s": 1476, "text": "A button is a widget which can be assigned for some particular task or event. However, to dynamically resize or position the button widget, we can configure its position and layout using the Grid module in tkinter. To resize the button dynamically, we can use rowconfiguration() and coloumnconfiguration() methods." }, { "code": null, "e": 2118, "s": 1791, "text": "In a tkinter Grid system, there are four attributes which can be used to resize any widget. These attributes generally refer to the direction such as North, South, East, and West. To make the buttons responsive and dynamically resizable according to the screen or window size, we have to use the row and column property in it." }, { "code": null, "e": 2749, "s": 2118, "text": "#Importing the tkinter library\nfrom tkinter import *\nwin= Tk()\nwin.title(\"Dynamically Resize Buttons\")\nwin.geometry(\"700x500\")\n\n#Configure Rows and column\n\nGrid.rowconfigure(win, 0,weight=1)\nGrid.columnconfigure(win,0,weight=1)\n#Create buttons\n\nb1= Button(win, text= \"C++\")\nb2= Button(win, text= \"Java\")\n\n#Create List of buttons\nbl= [b1, b2]\n\nrow_no=0\n#Loop through all the buttons and configure it row-wise\nfor button in bl:\n Grid.rowconfigure(win,row_no, weight=1)\n row_no+=1\n\n#Adjust the position in grid and make them sticky\n\nb1.grid(row=0, column=0, sticky= \"nsew\")\nb2.grid(row=1, column=0, stick= \"nsew\")\n\nwin.mainloop()" }, { "code": null, "e": 2921, "s": 2749, "text": "Running the above code will generate the output and display two buttons\nhorizontally in a row−order, which can be dynamically resizable according to screen\nor window size." } ]
Check if a Matrix is Invertible
29 Jul, 2021 In linear algebra, an n-by-n square matrix A is called Invertible, if there exists an n-by-n square matrix B such that where ‘In‘ denotes the n-by-n identity matrix. The matrix B is called the inverse matrix of A. A square matrix is Invertible if and only if its determinant is non-zero. Examples: Input : {{1, 2, 3} {4, 5, 6} {7, 8, 9}} Output : No The given matrix is NOT Invertible The value of Determinant is: 0 We find determinant of the matrix. Then we check if the determinant value is 0 or not. If the value is 0, then we output, not invertible. C++ Java Python 3 C# PHP Javascript // C++ program to find Determinant of a matrix#include <bits/stdc++.h>using namespace std; // Dimension of input square matrix#define N 4 // Function to get cofactor of mat[p][q] in temp[][]. n is current// dimension of mat[][]void getCofactor(int mat[N][N], int temp[N][N], int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix.n is current dimension of mat[][]. */int determinantOfMatrix(int mat[N][N], int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return mat[0][0]; int temp[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} bool isInvertible(int mat[N][N], int n){ if (determinantOfMatrix(mat, N) != 0) return true; else return false;} // Driver program to test above functionsint main(){ /* int mat[N][N] = {{6, 1, 1}, {4, -2, 5}, {2, 8, 7}}; */ int mat[N][N] = { { 1, 0, 2, -1 }, { 3, 0, 0, 5 }, { 2, 1, 4, -3 }, { 1, 0, 5, 0 } }; if (isInvertible(mat, N)) cout << "Yes"; else cout << "No"; return 0;} // Java program to find// Determinant of a matrixclass GFG{ // Dimension of input square matrix static int N = 4; // Function to get cofactor // of mat[p][q] in temp[][]. // n is current dimension // of mat[][] static void getCofactor(int [][]mat, int [][]temp, int p, int q, int n) { int i = 0, j = 0; // Looping for each // element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix // only those element which are // not in given row and column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase // row index and reset col index if (j == n - 1) { j = 0; i++; } } } } } /* Recursive function for finding determinant of matrix. n is current dimension of mat[][]. */ static int determinantOfMatrix(int [][]mat, int n) { int D = 0; // Initialize result // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors int [][]temp = new int[N][N]; // To store sign multiplier int sign = 1; // Iterate for each // element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // terms are to be added // with alternate sign sign = -sign; } return D; } static boolean isInvertible(int [][]mat, int n) { if (determinantOfMatrix(mat, N) != 0) return true; else return false; } // Driver Code public static void main(String []args) { int [][]mat = {{1, 0, 2, -1 }, {3, 0, 0, 5 }, {2, 1, 4, -3 }, {1, 0, 5, 0 }}; if (isInvertible(mat, N)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed// by ChitraNayal # Function to get cofactor of# mat[p][q] in temp[][]. n is# current dimension of mat[][]def getCofactor(mat, temp, p, q, n): i = 0 j = 0 # Looping for each element # of the matrix for row in range(n): for col in range(n): # Copying into temporary matrix # only those element which are # not in given row and column if (row != p and col != q) : temp[i][j] = mat[row][col] j += 1 # Row is filled, so increase # row index and reset col index if (j == n - 1): j = 0 i += 1 # Recursive function for# finding determinant of matrix.# n is current dimension of mat[][].def determinantOfMatrix(mat, n): D = 0 # Initialize result # Base case : if matrix # contains single element if (n == 1): return mat[0][0] # To store cofactors temp = [[0 for x in range(N)] for y in range(N)] sign = 1 # To store sign multiplier # Iterate for each # element of first row for f in range(n): # Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n) D += (sign * mat[0][f] * determinantOfMatrix(temp, n - 1)) # terms are to be added # with alternate sign sign = -sign return D def isInvertible(mat, n): if (determinantOfMatrix(mat, N) != 0): return True else: return False # Driver Codemat = [[ 1, 0, 2, -1 ], [ 3, 0, 0, 5 ], [ 2, 1, 4, -3 ], [ 1, 0, 5, 0 ]]; N = 4if (isInvertible(mat, N)): print("Yes")else: print("No") # This code is contributed# by ChitraNayal // C# program to find// Determinant of a matrixusing System; class GFG{ // Dimension of input// square matrixstatic int N = 4; // Function to get cofactor of// mat[p,q] in temp[,]. n is// current dimension of mat[,]static void getCofactor(int[,] mat, int[,] temp, int p, int q, int n){int i = 0, j = 0; // Looping for each element// of the matrixfor (int row = 0; row < n; row++){ for (int col = 0; col < n; col++) { // Copying into temporary matrix // only those element which are // not in given row and column if (row != p && col != q) { temp[i, j++] = mat[row, col]; // Row is filled, so // increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } }}} /* Recursive function for findingdeterminant of matrix. n is currentdimension of mat[,]. */static int determinantOfMatrix(int[,] mat, int n){int D = 0; // Initialize result // Base case : if matrix// contains single elementif (n == 1) return mat[0, 0]; // To store cofactorsint[,] temp = new int[N, N]; int sign = 1; // To store sign multiplier // Iterate for each// element of first rowfor (int f = 0; f < n; f++){ // Getting Cofactor of mat[0,f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0, f] * determinantOfMatrix(temp, n - 1); // terms are to be added // with alternate sign sign = -sign;}return D;} static bool isInvertible(int[,] mat, int n){ if (determinantOfMatrix(mat, N) != 0) return true; else return false;} // Driver Codepublic static void Main(){ int[,] mat = {{ 1, 0, 2, -1 }, { 3, 0, 0, 5 }, { 2, 1, 4, -3 }, { 1, 0, 5, 0 }}; if (isInvertible(mat, N)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed// by ChitraNayal <?php// PHP program to find Determinant// of a matrix // Dimension of input// square matrix$N = 4; // Function to get cofactor of// $mat[$p][$q] in $temp[][].// $n is current dimension of $mat[][]function getCofactor(&$mat, &$temp, $p, $q, $n){ $i = 0; $j = 0; // Looping for each element // of the matrix for ($row = 0; $row < $n; $row++) { for ($col = 0; $col < $n; $col++) { // Copying into temporary matrix // only those element which are // not in given row and column if ($row != $p && $col != $q) { $temp[$i][$j++] = $mat[$row][$col]; // Row is filled, so // increase row index and // reset col index if ($j == $n - 1) { $j = 0; $i++; } } } }} /* Recursive function for findingdeterminant of matrix. n is currentdimension of $mat[][]. */function determinantOfMatrix(&$mat, $n){ $D = 0; // Initialize result // Base case : if matrix // contains single element if ($n == 1) return $mat[0][0]; $temp = array(array()); // To store cofactors $sign = 1; // To store sign multiplier // Iterate for each // element of first row for ($f = 0; $f < $n; $f++) { // Getting Cofactor of $mat[0][$f] getCofactor($mat, $temp, 0, $f, $n); $D += $sign * $mat[0][$f] * determinantOfMatrix($temp, $n - 1); // terms are to be added // with alternate sign $sign = -$sign; } return $D;} function isInvertible(&$mat, $n){ global $N; if (determinantOfMatrix($mat, $N) != 0) return true; else return false;} // Driver Code$mat = array(array(1, 0, 2, -1 ), array(3, 0, 0, 5 ), array(2, 1, 4, -3 ), array(1, 0, 5, 0 ));if (isInvertible($mat, $N)) echo "Yes";else echo "No"; // This code is contributed// by ChitraNayal?> <script>// Javascript program to find// Determinant of a matrix // Function to get cofactor // of mat[p][q] in temp[][]. // n is current dimension // of mat[][] function getCofactor(mat,temp,p,q,n){ let i = 0, j = 0; // Looping for each // element of the matrix for (let row = 0; row < n; row++) { for (let col = 0; col < n; col++) { // Copying into temporary matrix // only those element which are // not in given row and column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase // row index and reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix. n is current dimension of mat[][]. */function determinantOfMatrix(mat,n){ let D = 0; // Initialize result // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors let temp = new Array(N); for(let i=0;i<N;i++) { temp[i]=new Array(N); for(let j=0;j<N;j++) { temp[i][j]=0; } } // To store sign multiplier let sign = 1; // Iterate for each // element of first row for (let f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // terms are to be added // with alternate sign sign = -sign; } return D;} function isInvertible(mat,n){ if (determinantOfMatrix(mat, N) != 0) return true; else return false;} // Driver Code let mat = [[ 1, 0, 2, -1 ], [ 3, 0, 0, 5 ], [ 2, 1, 4, -3 ], [ 1, 0, 5, 0 ]]; let N = 4if (isInvertible(mat, N)) document.write("Yes")else document.write("No") // This code is contributed by rag2127</script> Yes ukasp rag2127 surinderdawra388 Algebra Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 The Celebrity Problem Unique paths in a Grid with Obstacles Count all possible paths from top left to bottom right of a mXn matrix Printing all solutions in N-Queen Problem Gold Mine Problem Search in a row wise and column wise sorted matrix Real-time application of Data Structures Python program to multiply two matrices Min Cost Path | DP-6
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Jul, 2021" }, { "code": null, "e": 342, "s": 52, "text": "In linear algebra, an n-by-n square matrix A is called Invertible, if there exists an n-by-n square matrix B such that where ‘In‘ denotes the n-by-n identity matrix. The matrix B is called the inverse matrix of A. A square matrix is Invertible if and only if its determinant is non-zero. " }, { "code": null, "e": 354, "s": 342, "text": "Examples: " }, { "code": null, "e": 492, "s": 354, "text": "Input : {{1, 2, 3}\n {4, 5, 6}\n {7, 8, 9}}\nOutput : No\nThe given matrix is NOT Invertible\nThe value of Determinant is: 0\n " }, { "code": null, "e": 631, "s": 492, "text": "We find determinant of the matrix. Then we check if the determinant value is 0 or not. If the value is 0, then we output, not invertible. " }, { "code": null, "e": 635, "s": 631, "text": "C++" }, { "code": null, "e": 640, "s": 635, "text": "Java" }, { "code": null, "e": 649, "s": 640, "text": "Python 3" }, { "code": null, "e": 652, "s": 649, "text": "C#" }, { "code": null, "e": 656, "s": 652, "text": "PHP" }, { "code": null, "e": 667, "s": 656, "text": "Javascript" }, { "code": "// C++ program to find Determinant of a matrix#include <bits/stdc++.h>using namespace std; // Dimension of input square matrix#define N 4 // Function to get cofactor of mat[p][q] in temp[][]. n is current// dimension of mat[][]void getCofactor(int mat[N][N], int temp[N][N], int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix.n is current dimension of mat[][]. */int determinantOfMatrix(int mat[N][N], int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return mat[0][0]; int temp[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} bool isInvertible(int mat[N][N], int n){ if (determinantOfMatrix(mat, N) != 0) return true; else return false;} // Driver program to test above functionsint main(){ /* int mat[N][N] = {{6, 1, 1}, {4, -2, 5}, {2, 8, 7}}; */ int mat[N][N] = { { 1, 0, 2, -1 }, { 3, 0, 0, 5 }, { 2, 1, 4, -3 }, { 1, 0, 5, 0 } }; if (isInvertible(mat, N)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 2738, "s": 667, "text": null }, { "code": "// Java program to find// Determinant of a matrixclass GFG{ // Dimension of input square matrix static int N = 4; // Function to get cofactor // of mat[p][q] in temp[][]. // n is current dimension // of mat[][] static void getCofactor(int [][]mat, int [][]temp, int p, int q, int n) { int i = 0, j = 0; // Looping for each // element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix // only those element which are // not in given row and column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase // row index and reset col index if (j == n - 1) { j = 0; i++; } } } } } /* Recursive function for finding determinant of matrix. n is current dimension of mat[][]. */ static int determinantOfMatrix(int [][]mat, int n) { int D = 0; // Initialize result // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors int [][]temp = new int[N][N]; // To store sign multiplier int sign = 1; // Iterate for each // element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // terms are to be added // with alternate sign sign = -sign; } return D; } static boolean isInvertible(int [][]mat, int n) { if (determinantOfMatrix(mat, N) != 0) return true; else return false; } // Driver Code public static void main(String []args) { int [][]mat = {{1, 0, 2, -1 }, {3, 0, 0, 5 }, {2, 1, 4, -3 }, {1, 0, 5, 0 }}; if (isInvertible(mat, N)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed// by ChitraNayal", "e": 5070, "s": 2738, "text": null }, { "code": "# Function to get cofactor of# mat[p][q] in temp[][]. n is# current dimension of mat[][]def getCofactor(mat, temp, p, q, n): i = 0 j = 0 # Looping for each element # of the matrix for row in range(n): for col in range(n): # Copying into temporary matrix # only those element which are # not in given row and column if (row != p and col != q) : temp[i][j] = mat[row][col] j += 1 # Row is filled, so increase # row index and reset col index if (j == n - 1): j = 0 i += 1 # Recursive function for# finding determinant of matrix.# n is current dimension of mat[][].def determinantOfMatrix(mat, n): D = 0 # Initialize result # Base case : if matrix # contains single element if (n == 1): return mat[0][0] # To store cofactors temp = [[0 for x in range(N)] for y in range(N)] sign = 1 # To store sign multiplier # Iterate for each # element of first row for f in range(n): # Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n) D += (sign * mat[0][f] * determinantOfMatrix(temp, n - 1)) # terms are to be added # with alternate sign sign = -sign return D def isInvertible(mat, n): if (determinantOfMatrix(mat, N) != 0): return True else: return False # Driver Codemat = [[ 1, 0, 2, -1 ], [ 3, 0, 0, 5 ], [ 2, 1, 4, -3 ], [ 1, 0, 5, 0 ]]; N = 4if (isInvertible(mat, N)): print(\"Yes\")else: print(\"No\") # This code is contributed# by ChitraNayal", "e": 6819, "s": 5070, "text": null }, { "code": "// C# program to find// Determinant of a matrixusing System; class GFG{ // Dimension of input// square matrixstatic int N = 4; // Function to get cofactor of// mat[p,q] in temp[,]. n is// current dimension of mat[,]static void getCofactor(int[,] mat, int[,] temp, int p, int q, int n){int i = 0, j = 0; // Looping for each element// of the matrixfor (int row = 0; row < n; row++){ for (int col = 0; col < n; col++) { // Copying into temporary matrix // only those element which are // not in given row and column if (row != p && col != q) { temp[i, j++] = mat[row, col]; // Row is filled, so // increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } }}} /* Recursive function for findingdeterminant of matrix. n is currentdimension of mat[,]. */static int determinantOfMatrix(int[,] mat, int n){int D = 0; // Initialize result // Base case : if matrix// contains single elementif (n == 1) return mat[0, 0]; // To store cofactorsint[,] temp = new int[N, N]; int sign = 1; // To store sign multiplier // Iterate for each// element of first rowfor (int f = 0; f < n; f++){ // Getting Cofactor of mat[0,f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0, f] * determinantOfMatrix(temp, n - 1); // terms are to be added // with alternate sign sign = -sign;}return D;} static bool isInvertible(int[,] mat, int n){ if (determinantOfMatrix(mat, N) != 0) return true; else return false;} // Driver Codepublic static void Main(){ int[,] mat = {{ 1, 0, 2, -1 }, { 3, 0, 0, 5 }, { 2, 1, 4, -3 }, { 1, 0, 5, 0 }}; if (isInvertible(mat, N)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed// by ChitraNayal", "e": 8809, "s": 6819, "text": null }, { "code": "<?php// PHP program to find Determinant// of a matrix // Dimension of input// square matrix$N = 4; // Function to get cofactor of// $mat[$p][$q] in $temp[][].// $n is current dimension of $mat[][]function getCofactor(&$mat, &$temp, $p, $q, $n){ $i = 0; $j = 0; // Looping for each element // of the matrix for ($row = 0; $row < $n; $row++) { for ($col = 0; $col < $n; $col++) { // Copying into temporary matrix // only those element which are // not in given row and column if ($row != $p && $col != $q) { $temp[$i][$j++] = $mat[$row][$col]; // Row is filled, so // increase row index and // reset col index if ($j == $n - 1) { $j = 0; $i++; } } } }} /* Recursive function for findingdeterminant of matrix. n is currentdimension of $mat[][]. */function determinantOfMatrix(&$mat, $n){ $D = 0; // Initialize result // Base case : if matrix // contains single element if ($n == 1) return $mat[0][0]; $temp = array(array()); // To store cofactors $sign = 1; // To store sign multiplier // Iterate for each // element of first row for ($f = 0; $f < $n; $f++) { // Getting Cofactor of $mat[0][$f] getCofactor($mat, $temp, 0, $f, $n); $D += $sign * $mat[0][$f] * determinantOfMatrix($temp, $n - 1); // terms are to be added // with alternate sign $sign = -$sign; } return $D;} function isInvertible(&$mat, $n){ global $N; if (determinantOfMatrix($mat, $N) != 0) return true; else return false;} // Driver Code$mat = array(array(1, 0, 2, -1 ), array(3, 0, 0, 5 ), array(2, 1, 4, -3 ), array(1, 0, 5, 0 ));if (isInvertible($mat, $N)) echo \"Yes\";else echo \"No\"; // This code is contributed// by ChitraNayal?>", "e": 10852, "s": 8809, "text": null }, { "code": "<script>// Javascript program to find// Determinant of a matrix // Function to get cofactor // of mat[p][q] in temp[][]. // n is current dimension // of mat[][] function getCofactor(mat,temp,p,q,n){ let i = 0, j = 0; // Looping for each // element of the matrix for (let row = 0; row < n; row++) { for (let col = 0; col < n; col++) { // Copying into temporary matrix // only those element which are // not in given row and column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase // row index and reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix. n is current dimension of mat[][]. */function determinantOfMatrix(mat,n){ let D = 0; // Initialize result // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors let temp = new Array(N); for(let i=0;i<N;i++) { temp[i]=new Array(N); for(let j=0;j<N;j++) { temp[i][j]=0; } } // To store sign multiplier let sign = 1; // Iterate for each // element of first row for (let f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // terms are to be added // with alternate sign sign = -sign; } return D;} function isInvertible(mat,n){ if (determinantOfMatrix(mat, N) != 0) return true; else return false;} // Driver Code let mat = [[ 1, 0, 2, -1 ], [ 3, 0, 0, 5 ], [ 2, 1, 4, -3 ], [ 1, 0, 5, 0 ]]; let N = 4if (isInvertible(mat, N)) document.write(\"Yes\")else document.write(\"No\") // This code is contributed by rag2127</script>", "e": 12972, "s": 10852, "text": null }, { "code": null, "e": 12976, "s": 12972, "text": "Yes" }, { "code": null, "e": 12984, "s": 12978, "text": "ukasp" }, { "code": null, "e": 12992, "s": 12984, "text": "rag2127" }, { "code": null, "e": 13009, "s": 12992, "text": "surinderdawra388" }, { "code": null, "e": 13017, "s": 13009, "text": "Algebra" }, { "code": null, "e": 13024, "s": 13017, "text": "Matrix" }, { "code": null, "e": 13031, "s": 13024, "text": "Matrix" }, { "code": null, "e": 13129, "s": 13031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13153, "s": 13129, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 13175, "s": 13153, "text": "The Celebrity Problem" }, { "code": null, "e": 13213, "s": 13175, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 13284, "s": 13213, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 13326, "s": 13284, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 13344, "s": 13326, "text": "Gold Mine Problem" }, { "code": null, "e": 13395, "s": 13344, "text": "Search in a row wise and column wise sorted matrix" }, { "code": null, "e": 13436, "s": 13395, "text": "Real-time application of Data Structures" }, { "code": null, "e": 13476, "s": 13436, "text": "Python program to multiply two matrices" } ]
VB.Net - Basic Controls
An object is a type of user interface element you create on a Visual Basic form by using a toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic control consists of three important elements − Properties which describe the object, Properties which describe the object, Methods cause an object to do something and Methods cause an object to do something and Events are what happens when an object does something. Events are what happens when an object does something. All the Visual Basic Objects can be moved, resized or customized by setting their properties. A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color. Properties can be set at design time by using the Properties window or at run time by using statements in the program code. Object. Property = Value Where Object is the name of the object you're customizing. Object is the name of the object you're customizing. Property is the characteristic you want to change. Property is the characteristic you want to change. Value is the new property setting. Value is the new property setting. For example, Form1.Caption = "Hello" You can set any of the form properties using Properties Window. Most of the properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with different controls and restrictions applied to them. A method is a procedure created as a member of a class and they cause an object to do something. Methods are used to access or manipulate the characteristics of an object or a variable. There are mainly two categories of methods you will use in your classes − If you are using a control such as one of those provided by the Toolbox, you can call any of its public methods. The requirements of such a method depend on the class being used. If you are using a control such as one of those provided by the Toolbox, you can call any of its public methods. The requirements of such a method depend on the class being used. If none of the existing methods can perform your desired task, you can add a method to a class. If none of the existing methods can perform your desired task, you can add a method to a class. For example, the MessageBox control has a method named Show, which is called in the code snippet below − Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MessageBox.Show("Hello, World") End Sub End Class An event is a signal that informs an application that something important has occurred. For example, when a user clicks a control on a form, the form can raise a Click event and call a procedure that handles the event. There are various types of events associated with a Form like click, double click, close, load, resize, etc. Following is the default structure of a form Load event handler subroutine. You can see this code by double clicking the code which will give you a complete list of the all events associated with Form control − Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'event handler code goes here End Sub Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event. Similar way, you can check stub code for click, double click. If you want to initialize some variables like properties, etc., then you will keep such code inside Form1_Load() subroutine. Here, important point to note is the name of the event handler, which is by default Form1_Load, but you can change this name based on your naming convention you use in your application programming. VB.Net provides a huge variety of controls that help you to create rich user interface. Functionalities of all these controls are defined in the respective control classes. The control classes are defined in the System.Windows.Forms namespace. The following table lists some of the commonly used controls − Forms The container for all the controls that make up the user interface. TextBox It represents a Windows text box control. Label It represents a standard Windows label. Button It represents a Windows button control. ListBox It represents a Windows control to display a list of items. ComboBox It represents a Windows combo box control. RadioButton It enables the user to select a single option from a group of choices when paired with other RadioButton controls. CheckBox It represents a Windows CheckBox. PictureBox It represents a Windows picture box control for displaying an image. ProgressBar It represents a Windows progress bar control. ScrollBar It Implements the basic functionality of a scroll bar control. DateTimePicker It represents a Windows control that allows the user to select a date and a time and to display the date and time with a specified format. TreeView It displays a hierarchical collection of labeled items, each represented by a TreeNode. ListView It represents a Windows list view control, which displays a collection of items that can be displayed using one of four different views.
[ { "code": null, "e": 2665, "s": 2434, "text": "An object is a type of user interface element you create on a Visual Basic form by using a toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic control consists of three important elements −" }, { "code": null, "e": 2703, "s": 2665, "text": "Properties which describe the object," }, { "code": null, "e": 2741, "s": 2703, "text": "Properties which describe the object," }, { "code": null, "e": 2785, "s": 2741, "text": "Methods cause an object to do something and" }, { "code": null, "e": 2829, "s": 2785, "text": "Methods cause an object to do something and" }, { "code": null, "e": 2884, "s": 2829, "text": "Events are what happens when an object does something." }, { "code": null, "e": 2939, "s": 2884, "text": "Events are what happens when an object does something." }, { "code": null, "e": 3136, "s": 2939, "text": "All the Visual Basic Objects can be moved, resized or customized by setting their properties. A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color." }, { "code": null, "e": 3260, "s": 3136, "text": "Properties can be set at design time by using the Properties window or at run time by using statements in the program code." }, { "code": null, "e": 3285, "s": 3260, "text": "Object. Property = Value" }, { "code": null, "e": 3291, "s": 3285, "text": "Where" }, { "code": null, "e": 3344, "s": 3291, "text": "Object is the name of the object you're customizing." }, { "code": null, "e": 3397, "s": 3344, "text": "Object is the name of the object you're customizing." }, { "code": null, "e": 3448, "s": 3397, "text": "Property is the characteristic you want to change." }, { "code": null, "e": 3499, "s": 3448, "text": "Property is the characteristic you want to change." }, { "code": null, "e": 3534, "s": 3499, "text": "Value is the new property setting." }, { "code": null, "e": 3569, "s": 3534, "text": "Value is the new property setting." }, { "code": null, "e": 3582, "s": 3569, "text": "For example," }, { "code": null, "e": 3606, "s": 3582, "text": "Form1.Caption = \"Hello\"" }, { "code": null, "e": 3886, "s": 3606, "text": "You can set any of the form properties using Properties Window. Most of the properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with different controls and restrictions applied to them." }, { "code": null, "e": 4146, "s": 3886, "text": "A method is a procedure created as a member of a class and they cause an object to do something. Methods are used to access or manipulate the characteristics of an object or a variable. There are mainly two categories of methods you will use in your classes −" }, { "code": null, "e": 4325, "s": 4146, "text": "If you are using a control such as one of those provided by the Toolbox, you can call any of its public methods. The requirements of such a method depend on the class being used." }, { "code": null, "e": 4504, "s": 4325, "text": "If you are using a control such as one of those provided by the Toolbox, you can call any of its public methods. The requirements of such a method depend on the class being used." }, { "code": null, "e": 4600, "s": 4504, "text": "If none of the existing methods can perform your desired task, you can add a method to a class." }, { "code": null, "e": 4696, "s": 4600, "text": "If none of the existing methods can perform your desired task, you can add a method to a class." }, { "code": null, "e": 4801, "s": 4696, "text": "For example, the MessageBox control has a method named Show, which is called in the code snippet below −" }, { "code": null, "e": 4994, "s": 4801, "text": "Public Class Form1\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) \n Handles Button1.Click\n MessageBox.Show(\"Hello, World\")\n End Sub\nEnd Class" }, { "code": null, "e": 5322, "s": 4994, "text": "An event is a signal that informs an application that something important has occurred. For example, when a user clicks a control on a form, the form can raise a Click event and call a procedure that handles the event. There are various types of events associated with a Form like click, double click, close, load, resize, etc." }, { "code": null, "e": 5533, "s": 5322, "text": "Following is the default structure of a form Load event handler subroutine. You can see this code by double clicking the code which will give you a complete list of the all events associated with Form control −" }, { "code": null, "e": 5651, "s": 5533, "text": "Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n 'event handler code goes here\nEnd Sub" }, { "code": null, "e": 6123, "s": 5651, "text": "Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event. Similar way, you can check stub code for click, double click. If you want to initialize some variables like properties, etc., then you will keep such code inside Form1_Load() subroutine. Here, important point to note is the name of the event handler, which is by default Form1_Load, but you can change this name based on your naming convention you use in your application programming.\n" }, { "code": null, "e": 6367, "s": 6123, "text": "VB.Net provides a huge variety of controls that help you to create rich user interface. Functionalities of all these controls are defined in the respective control classes. The control classes are defined in the System.Windows.Forms namespace." }, { "code": null, "e": 6430, "s": 6367, "text": "The following table lists some of the commonly used controls −" }, { "code": null, "e": 6436, "s": 6430, "text": "Forms" }, { "code": null, "e": 6504, "s": 6436, "text": "The container for all the controls that make up the user interface." }, { "code": null, "e": 6512, "s": 6504, "text": "TextBox" }, { "code": null, "e": 6554, "s": 6512, "text": "It represents a Windows text box control." }, { "code": null, "e": 6560, "s": 6554, "text": "Label" }, { "code": null, "e": 6600, "s": 6560, "text": "It represents a standard Windows label." }, { "code": null, "e": 6607, "s": 6600, "text": "Button" }, { "code": null, "e": 6647, "s": 6607, "text": "It represents a Windows button control." }, { "code": null, "e": 6655, "s": 6647, "text": "ListBox" }, { "code": null, "e": 6715, "s": 6655, "text": "It represents a Windows control to display a list of items." }, { "code": null, "e": 6724, "s": 6715, "text": "ComboBox" }, { "code": null, "e": 6767, "s": 6724, "text": "It represents a Windows combo box control." }, { "code": null, "e": 6779, "s": 6767, "text": "RadioButton" }, { "code": null, "e": 6894, "s": 6779, "text": "It enables the user to select a single option from a group of choices when paired with other RadioButton controls." }, { "code": null, "e": 6903, "s": 6894, "text": "CheckBox" }, { "code": null, "e": 6937, "s": 6903, "text": "It represents a Windows CheckBox." }, { "code": null, "e": 6948, "s": 6937, "text": "PictureBox" }, { "code": null, "e": 7017, "s": 6948, "text": "It represents a Windows picture box control for displaying an image." }, { "code": null, "e": 7029, "s": 7017, "text": "ProgressBar" }, { "code": null, "e": 7075, "s": 7029, "text": "It represents a Windows progress bar control." }, { "code": null, "e": 7085, "s": 7075, "text": "ScrollBar" }, { "code": null, "e": 7148, "s": 7085, "text": "It Implements the basic functionality of a scroll bar control." }, { "code": null, "e": 7163, "s": 7148, "text": "DateTimePicker" }, { "code": null, "e": 7302, "s": 7163, "text": "It represents a Windows control that allows the user to select a date and a time and to display the date and time with a specified format." }, { "code": null, "e": 7311, "s": 7302, "text": "TreeView" }, { "code": null, "e": 7399, "s": 7311, "text": "It displays a hierarchical collection of labeled items, each represented by a TreeNode." }, { "code": null, "e": 7408, "s": 7399, "text": "ListView" } ]
Using List as Stack and Queues in Python
In this article, we will learn about Stack & Queue structures in Python 3.x. Or earlier. Here we will discuss the working and modification within these data structures − This includes − Insertion operation (Push, Enqueue)Deletion operation (Pop, Dequeue)Display / Traversing Operation Insertion operation (Push, Enqueue) Deletion operation (Pop, Dequeue) Display / Traversing Operation Prerequisites: List & List Operations Related Data Structure: List Manipulation In stacks, objects are stored one over another, and these objects get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First Out type arrangement is followed in the Stack data structure. Operations on a Stack − Addition / Appending of Element: This increases the stack size by the number of items added and Addition takes place at the upper end i.e. at the top of the stack. Deletion / Removal of Element − This involves two conditions − If the Stack is empty no element is available for deletion i.e. Underflow occurs in the Stack or If the Stack has certain elements present in it then the element present at the top gets removed. This reduces the size of the stack by the number of elements removed. Traversing /Displaying − This involves visiting each element of the stack and displaying on the screen. We can also insert an additional functionality of peek i.e. Retrieving the value at the top of the Stack. Insertion order is preserved. Duplicacy is allowed in Stack. Similar data-type Storage. Highly useful in Parsing Operations. def isEmpty(stk): # checks whether the stack is empty or not if stk==[]: return True else: return False def Push(stk,item): # Allow additions to the stack stk.append(item) top=len(stk)-1 def Pop(stk): if isEmpty(stk): # verifies whether the stack is empty or not print("Underflow") else: # Allow deletions from the stack item=stk.pop() if len(stk)==0: top=None else: top=len(stk) print("Popped item is "+str(item)) def Display(stk): if isEmpty(stk): print("Stack is empty") else: top=len(stk)-1 print("Elements in the stack are: ") for i in range(top,-1,-1): print (str(stk[i])) # executable code if __name__ == "__main__": stk=[] top=None Push(stk,1) Push(stk,2) Push(stk,3) Push(stk,4) Pop(stk) Display(stk) The above code implements the Stack functionality in Python 3.x. or earlier. We can make a menu-driven program by providing choices to the user by using multiple if-else statements. The concept of framing the Stack remains the same in both cases. The screen shown below depicts the output produced by the above program. We can also use input() function for user-based input system(Here I implemented static inputs ) Popped item is 4 Elements in the stack are: 3 2 1 In stacks, objects are stored one after another, and these objects get removed in the order of the arrival i.e. FIFO concept is followed. FIFO means First in First Out type arrangement is followed in Queue data structure. Operations on a Queue Addition / Appending of Element − This increases the queue size by the number of items added and Addition takes place at the rear end i.e. at the back of the queue. Addition / Appending of Element − This increases the queue size by the number of items added and Addition takes place at the rear end i.e. at the back of the queue. Deletion / Removal of Element − This involves two conditions − If the Queue is empty no element is available for deletion i.e. Underflow occurs in the Queue or If the Queue has certain elements present in it then the element present at the front gets removed. This reduces the size of the stack by the number of elements removed. Deletion / Removal of Element − This involves two conditions − If the Queue is empty no element is available for deletion i.e. Underflow occurs in the Queue or If the Queue has certain elements present in it then the element present at the front gets removed. This reduces the size of the stack by the number of elements removed. Traversing /Displaying − This involves visiting each element of the stack and displaying on the screen. Traversing /Displaying − This involves visiting each element of the stack and displaying on the screen. We can also insert an additional functionality of peek i.e. Retrieving the value at the back/end of the Queue. Insertion order is preserved. Duplicacy is allowed in Queue. Similar data-type Storage. Highly useful in Parsing CPU task operations. Live Demo #Adding elements to queue at the rear end def enqueue(data): queue.insert(0,data) #Removing the front element from the queue def dequeue(): if len(queue)>0: return queue.pop() return ("Queue Empty!") #To display the elements of the queue def display(): print("Elements on queue are:"); for i in range(len(queue)): print(queue[i]) # executable code if __name__=="__main__": queue=[] enqueue(5) enqueue(6) enqueue(9) enqueue(5) enqueue(3) print("Popped Element is: "+str(dequeue())) display() The above code implements the Queue functionality in Python 3.x. or earlier. We can make a menu-driven program by providing choices to the user by using multiple if-else statements. The concept of framing the Queue remains the same in both cases. The screen shown below depicts the output produced by the above program. We can also use input() function for user-based input system(Here I implemented static inputs ) Popped item is: 5 Elements on queue are: 3 5 9 6 In this article, we learnt how to implement the Stack & Queue data structure in Python 3.x. Or earlier. You can implement the same algorithm to implement a stack/queue detector program in any other programming language.
[ { "code": null, "e": 1357, "s": 1187, "text": "In this article, we will learn about Stack & Queue structures in Python 3.x. Or earlier. Here we will discuss the working and modification within these data structures −" }, { "code": null, "e": 1373, "s": 1357, "text": "This includes −" }, { "code": null, "e": 1472, "s": 1373, "text": "Insertion operation (Push, Enqueue)Deletion operation (Pop, Dequeue)Display / Traversing Operation" }, { "code": null, "e": 1508, "s": 1472, "text": "Insertion operation (Push, Enqueue)" }, { "code": null, "e": 1542, "s": 1508, "text": "Deletion operation (Pop, Dequeue)" }, { "code": null, "e": 1573, "s": 1542, "text": "Display / Traversing Operation" }, { "code": null, "e": 1611, "s": 1573, "text": "Prerequisites: List & List Operations" }, { "code": null, "e": 1653, "s": 1611, "text": "Related Data Structure: List Manipulation" }, { "code": null, "e": 1885, "s": 1653, "text": "In stacks, objects are stored one over another, and these objects get removed in the reverse order of the arrival i.e. LIFO concept is followed. LIFO means Last in First Out type arrangement is followed in the Stack data structure." }, { "code": null, "e": 1909, "s": 1885, "text": "Operations on a Stack −" }, { "code": null, "e": 2073, "s": 1909, "text": "Addition / Appending of Element: This increases the stack size by the number of items added and Addition takes place at the upper end i.e. at the top of the stack." }, { "code": null, "e": 2401, "s": 2073, "text": "Deletion / Removal of Element − This involves two conditions − If the Stack is empty no element is available for deletion i.e. Underflow occurs in the Stack or If the Stack has certain elements present in it then the element present at the top gets removed. This reduces the size of the stack by the number of elements removed." }, { "code": null, "e": 2505, "s": 2401, "text": "Traversing /Displaying − This involves visiting each element of the stack and displaying on the screen." }, { "code": null, "e": 2611, "s": 2505, "text": "We can also insert an additional functionality of peek i.e. Retrieving the value at the top of the Stack." }, { "code": null, "e": 2641, "s": 2611, "text": "Insertion order is preserved." }, { "code": null, "e": 2672, "s": 2641, "text": "Duplicacy is allowed in Stack." }, { "code": null, "e": 2699, "s": 2672, "text": "Similar data-type Storage." }, { "code": null, "e": 2736, "s": 2699, "text": "Highly useful in Parsing Operations." }, { "code": null, "e": 3594, "s": 2736, "text": "def isEmpty(stk): # checks whether the stack is empty or not\n if stk==[]:\n return True\n else:\n return False\n\ndef Push(stk,item): # Allow additions to the stack\n stk.append(item)\n top=len(stk)-1\n\ndef Pop(stk):\n if isEmpty(stk): # verifies whether the stack is empty or not\n print(\"Underflow\")\n else: # Allow deletions from the stack\n item=stk.pop()\n if len(stk)==0:\n top=None\n else:\n top=len(stk)\n print(\"Popped item is \"+str(item))\n\ndef Display(stk):\n if isEmpty(stk):\n print(\"Stack is empty\")\n else:\n top=len(stk)-1\n print(\"Elements in the stack are: \")\n for i in range(top,-1,-1):\n print (str(stk[i]))\n\n# executable code\nif __name__ == \"__main__\":\n stk=[]\n top=None\n Push(stk,1)\n Push(stk,2)\n Push(stk,3)\n Push(stk,4)\n Pop(stk)\n Display(stk)" }, { "code": null, "e": 3841, "s": 3594, "text": "The above code implements the Stack functionality in Python 3.x. or earlier. We can make a menu-driven program by providing choices to the user by using multiple if-else statements. The concept of framing the Stack remains the same in both cases." }, { "code": null, "e": 4010, "s": 3841, "text": "The screen shown below depicts the output produced by the above program. We can also use input() function for user-based input system(Here I implemented static inputs )" }, { "code": null, "e": 4060, "s": 4010, "text": "Popped item is 4\nElements in the stack are:\n3\n2\n1" }, { "code": null, "e": 4282, "s": 4060, "text": "In stacks, objects are stored one after another, and these objects get removed in the order of the arrival i.e. FIFO concept is followed. FIFO means First in First Out type arrangement is followed in Queue data structure." }, { "code": null, "e": 4304, "s": 4282, "text": "Operations on a Queue" }, { "code": null, "e": 4469, "s": 4304, "text": "Addition / Appending of Element − This increases the queue size by the number of items added and Addition takes place at the rear end i.e. at the back of the queue." }, { "code": null, "e": 4634, "s": 4469, "text": "Addition / Appending of Element − This increases the queue size by the number of items added and Addition takes place at the rear end i.e. at the back of the queue." }, { "code": null, "e": 4964, "s": 4634, "text": "Deletion / Removal of Element − This involves two conditions − If the Queue is empty no element is available for deletion i.e. Underflow occurs in the Queue or If the Queue has certain elements present in it then the element present at the front gets removed. This reduces the size of the stack by the number of elements removed." }, { "code": null, "e": 5294, "s": 4964, "text": "Deletion / Removal of Element − This involves two conditions − If the Queue is empty no element is available for deletion i.e. Underflow occurs in the Queue or If the Queue has certain elements present in it then the element present at the front gets removed. This reduces the size of the stack by the number of elements removed." }, { "code": null, "e": 5398, "s": 5294, "text": "Traversing /Displaying − This involves visiting each element of the stack and displaying on the screen." }, { "code": null, "e": 5502, "s": 5398, "text": "Traversing /Displaying − This involves visiting each element of the stack and displaying on the screen." }, { "code": null, "e": 5613, "s": 5502, "text": "We can also insert an additional functionality of peek i.e. Retrieving the value at the back/end of the Queue." }, { "code": null, "e": 5643, "s": 5613, "text": "Insertion order is preserved." }, { "code": null, "e": 5674, "s": 5643, "text": "Duplicacy is allowed in Queue." }, { "code": null, "e": 5701, "s": 5674, "text": "Similar data-type Storage." }, { "code": null, "e": 5747, "s": 5701, "text": "Highly useful in Parsing CPU task operations." }, { "code": null, "e": 5758, "s": 5747, "text": " Live Demo" }, { "code": null, "e": 6303, "s": 5758, "text": "#Adding elements to queue at the rear end\ndef enqueue(data):\n queue.insert(0,data)\n\n#Removing the front element from the queue\ndef dequeue():\n if len(queue)>0:\n return queue.pop()\n return (\"Queue Empty!\")\n\n#To display the elements of the queue\ndef display():\n print(\"Elements on queue are:\");\n for i in range(len(queue)):\n print(queue[i])\n\n# executable code\nif __name__==\"__main__\":\n queue=[]\n enqueue(5)\n enqueue(6)\n enqueue(9)\n enqueue(5)\n enqueue(3)\n print(\"Popped Element is: \"+str(dequeue()))\n display()" }, { "code": null, "e": 6550, "s": 6303, "text": "The above code implements the Queue functionality in Python 3.x. or earlier. We can make a menu-driven program by providing choices to the user by using multiple if-else statements. The concept of framing the Queue remains the same in both cases." }, { "code": null, "e": 6719, "s": 6550, "text": "The screen shown below depicts the output produced by the above program. We can also use input() function for user-based input system(Here I implemented static inputs )" }, { "code": null, "e": 6768, "s": 6719, "text": "Popped item is: 5\nElements on queue are:\n3\n5\n9\n6" }, { "code": null, "e": 6988, "s": 6768, "text": "In this article, we learnt how to implement the Stack & Queue data structure in Python 3.x. Or earlier. You can implement the same algorithm to implement a stack/queue detector program in any other programming language." } ]
How to use Compare-Object in PowerShell?
Compare-Object command in PowerShell is used to compare two objects. Objects can be a variable content, two files, strings, etc. This cmdlet uses few syntaxes to show the difference between objects which is called side indicators. => - Difference in destination object. <= - Difference in reference (source) object. == - When the source and destination objects are equal. PS C:\> Compare-Object "World" "Alpha" InputObject SideIndicator ----------- ------------- Alpha => World <= In the above example, the Alpha string shows the right indicator means it is the difference from the source object while the World string shows the left indicator means it is different from the destination string. The below example won’t show any output because the source and destination reference objects are the same but when you use -IncludeEqual parameter, it will show the equal indicator (==) for the matching object PS C:\> Compare-Object "World" "woRld" PS C:\> Compare-Object "World" "woRld" -IncludeEqual InputObject SideIndicator ----------- ------------- World == Please note, Comparison-Object is not case sensitive. For the case-sensitive comparison, use -CaseSensitive parameter. PS C:\> Compare-Object "World" "woRld" -CaseSensitive InputObject SideIndicator ----------- ------------- woRld => World <= $sourcefiles = Get-ChildItem C:\Test1 -Recurse $destfiles = Get-ChildItem C:\Test2\ -Recurse Compare-Object $sourcefiles $destfiles -IncludeEqual InputObject SideIndicator ----------- ------------- File1.txt == File3.txt => File2.txt <= The above example shows that the file1.txt exists at both locations, while File3.txt is at the destination location but not at the source location and File2.txt exists at the source location but not at the destination location. If we use -ExcludeDifference parameter, the output won’t be displayed unless we add -IncludeEqual parameter. Compare-Object $sourcefiles $destfiles -ExcludeDifferent The below command will display only the files which are matching. PS C:\> Compare-Object $sourcefiles $destfiles -IncludeEqual -ExcludeDifferent InputObject SideIndicator ----------- ------------- File1.txt == To compare two objects with the specific property name, use -Property parameter. In the below example, we will compare files LastWriteTime. $sfiles = Get-ChildItem C:\Test1\ -Recurse $dfiles = Get-ChildItem C:\Test2\ -Recurse Compare-Object $sfiles $dfiles -Property LastWriteTime -IncludeEqual LastWriteTime SideIndicator ------------- ------------- 8/28/2020 7:27:11 AM == 8/28/2020 7:29:00 AM => 8/28/2020 7:49:37 AM <= If you need the name of any specific property in the output then add that property first and then add the property name to compare. For example, Compare-Object $sfiles $dfiles -Property Name, LastWriteTime -IncludeEqual Name LastWriteTime SideIndicator ---- ------------- ------------- File1.txt 8/28/2020 7:27:11 AM == File3.txt 8/28/2020 7:29:00 AM => File2.txt 8/28/2020 7:49:37 AM <=
[ { "code": null, "e": 1293, "s": 1062, "text": "Compare-Object command in PowerShell is used to compare two objects. Objects can be a variable content, two files, strings, etc. This cmdlet uses few syntaxes to show the difference between objects which is called side indicators." }, { "code": null, "e": 1434, "s": 1293, "text": "=> - Difference in destination object.\n<= - Difference in reference (source) object.\n== - When the source and destination objects are equal." }, { "code": null, "e": 1544, "s": 1434, "text": "PS C:\\> Compare-Object \"World\" \"Alpha\"\n\nInputObject SideIndicator\n----------- -------------\nAlpha =>\nWorld <=" }, { "code": null, "e": 1758, "s": 1544, "text": "In the above example, the Alpha string shows the right indicator means it is the difference from the source object while the World string shows the left indicator means it is different from the destination string." }, { "code": null, "e": 1968, "s": 1758, "text": "The below example won’t show any output because the source and destination reference objects are the same but when you use -IncludeEqual parameter, it will show the equal indicator (==) for the matching object" }, { "code": null, "e": 2123, "s": 1968, "text": "PS C:\\> Compare-Object \"World\" \"woRld\"\n\nPS C:\\> Compare-Object \"World\" \"woRld\" -IncludeEqual\n\nInputObject SideIndicator\n----------- -------------\nWorld ==" }, { "code": null, "e": 2242, "s": 2123, "text": "Please note, Comparison-Object is not case sensitive. For the case-sensitive comparison, use -CaseSensitive parameter." }, { "code": null, "e": 2368, "s": 2242, "text": "PS C:\\> Compare-Object \"World\" \"woRld\" -CaseSensitive\n\n\nInputObject SideIndicator\n----------- -------------\nwoRld =>\nWorld <=" }, { "code": null, "e": 2514, "s": 2368, "text": "$sourcefiles = Get-ChildItem C:\\Test1 -Recurse\n$destfiles = Get-ChildItem C:\\Test2\\ -Recurse\nCompare-Object $sourcefiles $destfiles -IncludeEqual" }, { "code": null, "e": 2605, "s": 2514, "text": "InputObject SideIndicator\n----------- -------------\nFile1.txt ==\nFile3.txt =>\nFile2.txt <=" }, { "code": null, "e": 2833, "s": 2605, "text": "The above example shows that the file1.txt exists at both locations, while File3.txt is at the destination location but not at the source location and File2.txt exists at the source location but not at the destination location." }, { "code": null, "e": 2942, "s": 2833, "text": "If we use -ExcludeDifference parameter, the output won’t be displayed unless we add -IncludeEqual parameter." }, { "code": null, "e": 3000, "s": 2942, "text": "Compare-Object $sourcefiles $destfiles -ExcludeDifferent\n" }, { "code": null, "e": 3066, "s": 3000, "text": "The below command will display only the files which are matching." }, { "code": null, "e": 3211, "s": 3066, "text": "PS C:\\> Compare-Object $sourcefiles $destfiles -IncludeEqual -ExcludeDifferent\n\nInputObject SideIndicator\n----------- -------------\nFile1.txt ==" }, { "code": null, "e": 3351, "s": 3211, "text": "To compare two objects with the specific property name, use -Property parameter. In the below example, we will compare files LastWriteTime." }, { "code": null, "e": 3507, "s": 3351, "text": "$sfiles = Get-ChildItem C:\\Test1\\ -Recurse\n$dfiles = Get-ChildItem C:\\Test2\\ -Recurse\n\nCompare-Object $sfiles $dfiles -Property LastWriteTime -IncludeEqual" }, { "code": null, "e": 3635, "s": 3507, "text": "LastWriteTime SideIndicator\n------------- -------------\n8/28/2020 7:27:11 AM ==\n8/28/2020 7:29:00 AM =>\n8/28/2020 7:49:37 AM <=" }, { "code": null, "e": 3780, "s": 3635, "text": "If you need the name of any specific property in the output then add that property first and then add the property name to compare. For example," }, { "code": null, "e": 3856, "s": 3780, "text": "Compare-Object $sfiles $dfiles -Property Name, LastWriteTime -IncludeEqual\n" }, { "code": null, "e": 4024, "s": 3856, "text": "Name LastWriteTime SideIndicator\n---- ------------- -------------\nFile1.txt 8/28/2020 7:27:11 AM ==\nFile3.txt 8/28/2020 7:29:00 AM =>\nFile2.txt 8/28/2020 7:49:37 AM <=" } ]
How to repair MySQL tables from the command line?
The repair of MySQL tables is only applicable to MyISAM engine type, not for InnoDB. Therefore, we need to change the Engine type to MyISAM. The following is an example. Creating a table mysql> create table RepairTableDemo -> ( -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.51 sec) To convert this table to engine type MyISAM, use ALTER. mysql> ALTER TABLE RepairTableDemo ENGINE = MyISAM; Query OK, 0 rows affected (1.14 sec) Records: 0 Duplicates: 0 Warnings: 0 Inserting records into table. mysql> insert into RepairTableDemo values(1,'John'),(2,'Carol'),(3,'Johnson'); Query OK, 3 rows affected (0.06 sec) Records: 3 Duplicates: 0 Warnings: 0 To display all records. mysql> select *from RepairTableDemo; The following is the output. +------+---------+ | id | name | +------+---------+ | 1 | John | | 2 | Carol | | 3 | Johnson | +------+---------+ 3 rows in set (0.00 sec) Let us now see the syntax to repair a table. REPAIR TABLE yourTableName; The following is the query − mysql> REPAIR TABLE RepairTableDemo; Here is the output. It shows that the repair status is fine. +--------------------------+--------+----------+----------+ | Table | Op | Msg_type | Msg_text | +--------------------------+--------+----------+----------+ | business.repairtabledemo | repair | status | OK | +--------------------------+--------+----------+----------+ 1 row in set (0.10 sec)
[ { "code": null, "e": 1203, "s": 1062, "text": "The repair of MySQL tables is only applicable to MyISAM engine type, not for InnoDB. Therefore, we need to change the Engine type to MyISAM." }, { "code": null, "e": 1232, "s": 1203, "text": "The following is an example." }, { "code": null, "e": 1249, "s": 1232, "text": "Creating a table" }, { "code": null, "e": 1377, "s": 1249, "text": "mysql> create table RepairTableDemo\n -> (\n -> id int,\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1433, "s": 1377, "text": "To convert this table to engine type MyISAM, use ALTER." }, { "code": null, "e": 1561, "s": 1433, "text": "mysql> ALTER TABLE RepairTableDemo ENGINE = MyISAM;\nQuery OK, 0 rows affected (1.14 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1591, "s": 1561, "text": "Inserting records into table." }, { "code": null, "e": 1746, "s": 1591, "text": "mysql> insert into RepairTableDemo values(1,'John'),(2,'Carol'),(3,'Johnson');\nQuery OK, 3 rows affected (0.06 sec)\nRecords: 3 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1770, "s": 1746, "text": "To display all records." }, { "code": null, "e": 1807, "s": 1770, "text": "mysql> select *from RepairTableDemo;" }, { "code": null, "e": 1836, "s": 1807, "text": "The following is the output." }, { "code": null, "e": 1995, "s": 1836, "text": "+------+---------+\n| id | name |\n+------+---------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Johnson |\n+------+---------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 2040, "s": 1995, "text": "Let us now see the syntax to repair a table." }, { "code": null, "e": 2069, "s": 2040, "text": "REPAIR TABLE yourTableName;\n" }, { "code": null, "e": 2098, "s": 2069, "text": "The following is the query −" }, { "code": null, "e": 2135, "s": 2098, "text": "mysql> REPAIR TABLE RepairTableDemo;" }, { "code": null, "e": 2196, "s": 2135, "text": "Here is the output. It shows that the repair status is fine." }, { "code": null, "e": 2521, "s": 2196, "text": "+--------------------------+--------+----------+----------+\n| Table | Op | Msg_type | Msg_text |\n+--------------------------+--------+----------+----------+\n| business.repairtabledemo | repair | status | OK |\n+--------------------------+--------+----------+----------+\n1 row in set (0.10 sec)\n" } ]
DatePicker in Kotlin - GeeksforGeeks
21 Jan, 2022 Android DatePicker is a user interface control which is used to select the date by day, month and year in our android application. DatePicker is used to ensure that the users will select a valid date.In android DatePicker having two modes, first one to show the complete calendar and second one shows the dates in spinner view.We can create a DatePicker control in two ways either manually in XML file or create it in Activity file programmatically.First we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. We can use android:datePickerMode to show only calendar view. In the below example, we are using the DatePicker in Calendar mode. XML <DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:datePickerMode="calendar"/> The above code of DatePicker can be seen in android application like this We can also show the DatePicker in spinner format like selecting the day, month and year separately, by using android:datePickerMode attribute and set android:calendarViewShown=”false”, otherwise both spinner and calendar can be seen simultaneously. XML <DatePicker android:id="@+id/datePicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:datePickerMode="spinner" android:calendarViewShown="false"/> The above code of DatePicker can be seen in android application like this In this file, we will add the DatePicker and Button widget and set their attributes so that it can be accessed in the kotlin file. XML <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/linear_layout" android:gravity = "center"> <DatePicker android:id="@+id/date_Picker" android:layout_width="match_parent" android:layout_height="match_parent"/></LinearLayout> In this file, we will add the DatePicker and Button widget and set their attributes so that it can be accessed in the kotlin file. XML <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/linear_layout" android:gravity = "center"> <DatePicker android:id="@+id/date_Picker" android:layout_width="match_parent" android:layout_height="match_parent" android:datePickerMode = "spinner" android:calendarViewShown="false"/></LinearLayout> Here, we will specify the name of the activity. XML <resources> <string name="app_name">DatePickerInKotlin</string></resources> First of all, we declare a variable datePicker to access the DatePicker widget from the XML layout. val datePicker = findViewById<DatePicker>(R.id.date_Picker) then, we declare another variable today to get the current get like this. val today = Calendar.getInstance() datePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH) To display the selected date from the calendar we will use { view, year, month, day -> val month = month + 1 val msg = "You Selected: $day/$month/$year" Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() } We are familiar with further activities in previous articles like accessing button and set OnClickListener etc. Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.*import java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val datePicker = findViewById<DatePicker>(R.id.date_Picker) val today = Calendar.getInstance() datePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH) ) { view, year, month, day -> val month = month + 1 val msg = "You Selected: $day/$month/$year" Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() } }} XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <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> clintra ayushpandey3july Android-Date-time Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Content Providers in Android with Example Android RecyclerView in Kotlin Flutter - Custom Bottom Navigation Bar Broadcast Receiver in Android With Example Content Providers in Android with Example Android UI Layouts Android RecyclerView in Kotlin Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 24063, "s": 24035, "text": "\n21 Jan, 2022" }, { "code": null, "e": 24574, "s": 24063, "text": "Android DatePicker is a user interface control which is used to select the date by day, month and year in our android application. DatePicker is used to ensure that the users will select a valid date.In android DatePicker having two modes, first one to show the complete calendar and second one shows the dates in spinner view.We can create a DatePicker control in two ways either manually in XML file or create it in Activity file programmatically.First we create a new project by following the below steps: " }, { "code": null, "e": 24783, "s": 24574, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 24823, "s": 24783, "text": "Click on File, then New => New Project." }, { "code": null, "e": 24880, "s": 24823, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 24945, "s": 24880, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 24995, "s": 24945, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 25129, "s": 24997, "text": "We can use android:datePickerMode to show only calendar view. In the below example, we are using the DatePicker in Calendar mode. " }, { "code": null, "e": 25133, "s": 25129, "text": "XML" }, { "code": "<DatePicker android:id=\"@+id/datePicker\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:datePickerMode=\"calendar\"/>", "e": 25295, "s": 25133, "text": null }, { "code": null, "e": 25371, "s": 25295, "text": "The above code of DatePicker can be seen in android application like this " }, { "code": null, "e": 25625, "s": 25373, "text": "We can also show the DatePicker in spinner format like selecting the day, month and year separately, by using android:datePickerMode attribute and set android:calendarViewShown=”false”, otherwise both spinner and calendar can be seen simultaneously. " }, { "code": null, "e": 25629, "s": 25625, "text": "XML" }, { "code": "<DatePicker android:id=\"@+id/datePicker1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:datePickerMode=\"spinner\" android:calendarViewShown=\"false\"/>", "e": 25828, "s": 25629, "text": null }, { "code": null, "e": 25904, "s": 25828, "text": "The above code of DatePicker can be seen in android application like this " }, { "code": null, "e": 26043, "s": 25910, "text": "In this file, we will add the DatePicker and Button widget and set their attributes so that it can be accessed in the kotlin file. " }, { "code": null, "e": 26047, "s": 26043, "text": "XML" }, { "code": "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/linear_layout\" android:gravity = \"center\"> <DatePicker android:id=\"@+id/date_Picker\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/></LinearLayout>", "e": 26457, "s": 26047, "text": null }, { "code": null, "e": 26590, "s": 26457, "text": "In this file, we will add the DatePicker and Button widget and set their attributes so that it can be accessed in the kotlin file. " }, { "code": null, "e": 26594, "s": 26590, "text": "XML" }, { "code": "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/linear_layout\" android:gravity = \"center\"> <DatePicker android:id=\"@+id/date_Picker\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:datePickerMode = \"spinner\" android:calendarViewShown=\"false\"/></LinearLayout>", "e": 27087, "s": 26594, "text": null }, { "code": null, "e": 27137, "s": 27087, "text": "Here, we will specify the name of the activity. " }, { "code": null, "e": 27141, "s": 27137, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">DatePickerInKotlin</string></resources>", "e": 27220, "s": 27141, "text": null }, { "code": null, "e": 27322, "s": 27220, "text": "First of all, we declare a variable datePicker to access the DatePicker widget from the XML layout. " }, { "code": null, "e": 27382, "s": 27322, "text": "val datePicker = findViewById<DatePicker>(R.id.date_Picker)" }, { "code": null, "e": 27458, "s": 27382, "text": "then, we declare another variable today to get the current get like this. " }, { "code": null, "e": 27603, "s": 27458, "text": "val today = Calendar.getInstance()\n datePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH),\n today.get(Calendar.DAY_OF_MONTH)" }, { "code": null, "e": 27664, "s": 27603, "text": "To display the selected date from the calendar we will use " }, { "code": null, "e": 27864, "s": 27664, "text": " { view, year, month, day ->\n val month = month + 1\n val msg = \"You Selected: $day/$month/$year\"\n Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()\n }" }, { "code": null, "e": 27978, "s": 27864, "text": "We are familiar with further activities in previous articles like accessing button and set OnClickListener etc. " }, { "code": null, "e": 27985, "s": 27978, "text": "Kotlin" }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.*import java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val datePicker = findViewById<DatePicker>(R.id.date_Picker) val today = Calendar.getInstance() datePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH) ) { view, year, month, day -> val month = month + 1 val msg = \"You Selected: $day/$month/$year\" Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() } }}", "e": 28782, "s": 27985, "text": null }, { "code": null, "e": 28786, "s": 28782, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <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>", "e": 29441, "s": 28786, "text": null }, { "code": null, "e": 29456, "s": 29448, "text": "clintra" }, { "code": null, "e": 29473, "s": 29456, "text": "ayushpandey3july" }, { "code": null, "e": 29491, "s": 29473, "text": "Android-Date-time" }, { "code": null, "e": 29506, "s": 29491, "text": "Kotlin Android" }, { "code": null, "e": 29514, "s": 29506, "text": "Android" }, { "code": null, "e": 29521, "s": 29514, "text": "Kotlin" }, { "code": null, "e": 29529, "s": 29521, "text": "Android" }, { "code": null, "e": 29627, "s": 29529, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29685, "s": 29627, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 29728, "s": 29685, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29770, "s": 29728, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29801, "s": 29770, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29840, "s": 29801, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29883, "s": 29840, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29925, "s": 29883, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29944, "s": 29925, "text": "Android UI Layouts" }, { "code": null, "e": 29975, "s": 29944, "text": "Android RecyclerView in Kotlin" } ]
Understanding Neural Networks: What, How and Why? | by Euge Inzaugarat | Towards Data Science
Neural networks is one of the most powerful and widely used algorithms when it comes to the subfield of machine learning called deep learning. At first look, neural networks may seem a black box; an input layer gets the data into the “hidden layers” and after a magic trick we can see the information provided by the output layer. However, understanding what the hidden layers are doing is the key step to neural network implementation and optimization. In our path to understand neural networks, we are going to answer three questions: What, How and Why? The neural networks that we are going to considered are strictly called artificial neural networks, and as the name suggests, are based on what science knows about the human brain’s structure and function. Briefly, a neural network is defined as a computing system that consist of a number of simple but highly interconnected elements or nodes, called ‘neurons’, which are organized in layers which process information using dynamic state responses to external inputs. This algorithm is extremely useful, as we will explain later, in finding patterns that are too complex for being manually extracted and taught to recognize to the machine. In the context of this structure, patterns are introduced to the neural network by the input layer that has one neuron for each component present in the input data and is communicated to one or more hidden layers present in the network; called ‘hidden’ only due to the fact that they do not constitute the input or output layer. It is in the hidden layers where all the processing actually happens through a system of connections characterized by weights and biases (commonly referred as W and b): the input is received, the neuron calculate a weighted sum adding also the bias and according to the result and a pre-set activation function (most common one is sigmoid, σ, even though it almost not used anymore and there are better ones like ReLu), it decides whether it should be ‘fired’ or activated. Afterwards, the neuron transmit the information downstream to other connected neurons in a process called ‘forward pass’. At the end of this process, the last hidden layer is linked to the output layer which has one neuron for each possible desired output. Now that we have an idea on how the basic structure of a Neural Network look likes, we will go ahead and explain how it works. In order to do so, we need to explain the different type of neurons that we can include in our network. The first type of neuron that we are going to explain is Perceptron. Even though its use has decayed today, understanding how they work will give us a good clue about how more modern neurons function. A perceptron uses a function to learn a binary classifier by mapping a vector of binary variables to a single binary output and it can also be used in supervised learning. In this context, the perceptron follows these steps: Multiply all the inputs by their weights w, real numbers that express how important the corresponding inputs are to the output,Add them together referred as weighted sum: ∑ wj xj,Apply the activation function, in other words, determine whether the weighted sum is greater than a threshold value, where -threshold is equivalent to bias, and assign 1 or less and assign 0 as an output. Multiply all the inputs by their weights w, real numbers that express how important the corresponding inputs are to the output, Add them together referred as weighted sum: ∑ wj xj, Apply the activation function, in other words, determine whether the weighted sum is greater than a threshold value, where -threshold is equivalent to bias, and assign 1 or less and assign 0 as an output. We can also write the perceptron function in the following terms: One of the strongest point in this algorithm is that we can vary the weights and the bias to obtain distinct models of decision-making. We can assign more weight to those inputs so that if they are positive, it will favor our desired output. Also, because the bias can be understood as a measure of how difficult or easy is to output 1, we can drop or raise its value if we want to make more or less likely the desired output to happen. If we pay attention to the formula, we can observe that a big positive bias will make it very easy to output 1; however a very negative bias will make the task of output 1 very unlikely. In consequence, a perceptron can analyze different evidence or data and make a decision according to the set preferences. It is possible, in fact, to create more complex networks including more layers of perceptrons where every layer takes the output of the previous one and weights it and make a more and more complex decisions. What wait a minute: If perceptrons can do a good job in making complex decisions, why do we need other type of neuron? One of the disadvantages about a network containing perceptrons is that small changes in weights or bias, even in only one perceptron, can severely change our output going from 0 to 1 or vice versa. What we really want is to be able to gradually change the behaviour of our network by introducing small modifications in the weights or bias. Here is where a more modern type of neuron come in handy (Nowadays its use has been replaced by other types like Tanh and lately, by ReLu): Sigmoid neurons. The main difference between a sigmoid neuron and a perceptron is that the input and the output can be any continuous value between 0 and 1. The output is obtained after applying the sigmoid function to the inputs considering the weights, w, and the bias, b. To visualize it better, we can write the following: So, the formula of the output is: If we perform a mathematical analysis of this function, we can make a graph of our function σ , shown below, and conclude that when z is large and positive the function reaches its maximum asymptotic value of 1; however, if z is large and negative, the function reaches its minimum asymptotic value of 0. Here is where the sigmoid function becomes very interesting because it is with moderate values of z that the function takes a smooth and close to linear shape. In this interval, small changes in weights (Δwj) or in bias (Δbj) will generate small changes in the output; the desired behaviour that we were looking for as an improvement from a perceptron. z = np.arange(-10, 10, 0.3) sigm = 1 / (1 + np.exp(-z)) plt.plot(z, sigm, color = 'mediumvioletred', linewidth= 1.5) plt.xlabel('Z', size = 14, alpha = 0.8) plt.ylabel('σ(z)', size = 14, alpha = 0.8) a = plt.title('Sigmoid Function', size = 14) a = a.set_position([.5, 1.05]) We know that the derivative of a function is the measure of the rate at which the value y changes with respect to the change of the variable x. In this case, the variable y is our output and the variable x is a function of the weights and the bias. We can take advantage of this and calculate the change in the output using the derivatives, and particularly, the partial derivatives (with respect to w and with respect to b). You can read this post to follow the calculations but in the case of sigmoid function, the derivative will be reduce to calculate: f(z)*(1-f(z)). Here it’s a simple code that can be used to model a sigmoid function: We have just explain the functioning of every neuron in our network, but now, we can examine how the rest of the it works. A neural networks in which the output from one layer is used as the input of the next layer is called feedforward, particularly because there is no loops involved and the information is only pass forward and never back. Suppose that we have a training set and we want to use a 3-layer neural network, in which we also use the sigmoid neuron we saw above, to predict a certain feature. Taking what we explain about the structure of a neural network, weights and bias need to be first assigned to the connections between neurons in one layer and the next layer. Normally, the biases and weights are all initialized randomly in a synapsis matrix. If we are coding the neural network in python, we can use the Numpy function np.random.random generating a Gaussian distributions (where mean is equal to 0 and standard deviation to 1) to have a place to start learning. After that, we will build the neural network starting with the Feedforward step to calculate the predicted output; in other words, we just need to build the different layers involved in the network: layer0 is the input layer; our training set read as a matrix (We can called it X) layer1 is obtained by apply the activation function a’ = σ(w.X+b), in our case, performing the dot multiplication between input layer0 and the synapsis matrix syn0 layer2is the output layer obtained by the dot multiplication between layer1 and its synapsis syn1 We will also need to iterate over the training set to let the network learn (we will see this later). In order to do so, we will add a for loop. Until now, we have create the basic structure of the neural network: the different layers, the weights and bias of the connection between the neurons, and the sigmoid function. But none of this explains how the neural network can do such a good job in predicting patterns in a dataset. And this is what will take us to our last question. The main strength of machine learning algorithms is their ability to learn and improve every time in predicting an output. But what does it mean that they can learn? In the context of neural networks, it implies that the weights and biases that define the connection between neurons become more precise; this is, eventually, the weights and biases are selected such as the output from the network approximates the real value y(x) for all the training inputs. So, how do we quantify how far our prediction is from our real value in order for us to know if we need to keep searching for more precise parameters? For this aim, we need to calculate an error or in other words, define a cost function (Cost function is not other thing that the error in predicting the correct output that our network has; in other terms, it is the difference between the expected and the predicted output). In neural networks, the most commonly used one is the quadratic cost function, also called mean squared error, defined by the formula: This function is preferred over the linear error due to the fact that in neural networks small changes in weights and biases do not produces any change in the number of correct outputs; so using a quadratic function where big differences have more effect on the cost function than small ones help figuring out how to modify these parameters. On the other hand, we can see that our cost function become smaller as the output is closer to the real value y, for all training inputs. The main goal of our algorithm is to minimize this cost function by finding a set of weights and biases to make it as small as possible. And the main tool to achieve this goal is an algorithm called Gradient Descent. Then, the next question that we should answer is how we can minimize the cost function. From calculus, we know that a function can have global maximum and/or minimum, that is, where the function achieves the maximum or minimum value that it can have. We also know that one way to obtained that point is calculating derivatives. However, it is easy to calculate when we have a function with two variables but in the case of neural network, they include a lot of variables which make this computation quite impossible to make. Instead, let’s take a look at the graph below of a random function: We can see that this function has a global minimum. We could, as we said before, compute the derivatives to calculate where the minimum is located or we could take another approach. We can start in a random point and try to make a small move in the direction of the arrow, we would mathematically speaking, move Δx in the direction x and Δy in the direction of y, and calculate the change in our function ΔC. Because the rate of change in a direction is the derivative of a function, we could express the change in the function as: Here, we will take the definition from calculus of the gradient of a function: Now, we can rewrite the change in our function as: So now, we can see what happens with cost function when we choose a certain change in our parameters. The amount that we choose to move in any direction is called learning rate, and it is what define how fast we move towards the global minimum. If we choose a very small number, we will need to make a too many moves to reach this point; however, if we choose a very big number, we are at risk of passing the point and never be able to reach it. So the challenge is to choose the learning rate small enough. After choosing the learning rate, we can update our weights and biases and make another move; process that we repeat in each iteration. So, in few words, the gradient descent works by computing the gradient ∇C repeatedly, and then updating the weights and biases, and trying to find the correct values that minimize, in that way, the cost of function. And this is how the neural network learns. Sometimes, calculating the gradient can be very complex. There is, however, a way to speed up this calculations called stochastic gradient descent. This works by estimating the gradient ∇C by computing instead the gradient for a small sample of randomly chosen training inputs. Then, this small samples are average to get a good estimate of the true gradient, speeding up gradient descent, and thus learning faster. But wait a second? How do we compute the gradient of the cost function? Here is where another algorithm makes an entry: Backpropagation. The goal of this algorithm is to compute the partial derivatives of the cost function with respect to any weight w and any bias b; in practice, this means calculating the error vectors starting from the final layer and then, propagating this back to update the weights and biases. The reason why we need to go back is that the cost is a function of the output of our network. There are several calculations and errors that we need to compute whose formula are given by the backpropagation algorithm: 1) Output error (δL) related to the element wise (⦿) product of the gradient (▽C) by the derivative of activation function (σ′(z)), 2) error of one layer (ẟl) in terms of the error in the next layer related to the transpose matrix of the weights (Wl+1) multiplied by the error of the next layer (ẟl+1) and the element wise multiplication of the derivative of activation function, 3) rate of change of the cost with respect to any bias in the network: this means that the partial derivative of C with respect to any bias (∂C/∂bj) is equal to the error ẟl, 4) rate of change of the cost with respect to any weight in the network: meaning that the partial derivative of C with respect to any weight (∂C/∂wj) is equal to the error (ẟl) multiplied by activation of the neuron input. These last two calculation constitute the gradient of the cost function. Here, we can observe the formulas. The backpropagation algorithm calculates the gradient of the cost function for only one single training example. As a consequence, we need to combine backpropagation with a learning algorithm, for instance stochastic gradient descent, in order to compute the gradient for all the training set. Now, how do we apply this to our neural network in python?. Here, we can see step by step the calculations: Now we can put all of these formulas and concepts that we have seen in terms of an algorithm to see how we can implement this: INPUT: We input a set of training examples and we set the activation a that correspond for the input layer. FEEDFORWARD: For each layer, we compute the function z = w . a + b, being a = σ(z) OUTPUT ERROR: We compute the output error by using the formula #1 cited above. BACKPROPAGATION: Now we backpropagate the error; for each layer, we compute the formula #2 cited above. OUTPUT: We calculate the gradient descent with respect to any weight and bias by using the formulas #3 and #4. Of course, that there are more concepts, implementations and improvements that can be done to neural networks, which can become more and more widely used and powerful through the last years. But I hope this information can give you a hint on what a neural network is, how it works and learns using gradient descent and backpropagation. References: Neural Networks and Deep Learning. Michael Nielsen Build a Neural Network in 4 minutes. Siraj Raval Some rights reserved
[ { "code": null, "e": 501, "s": 47, "text": "Neural networks is one of the most powerful and widely used algorithms when it comes to the subfield of machine learning called deep learning. At first look, neural networks may seem a black box; an input layer gets the data into the “hidden layers” and after a magic trick we can see the information provided by the output layer. However, understanding what the hidden layers are doing is the key step to neural network implementation and optimization." }, { "code": null, "e": 603, "s": 501, "text": "In our path to understand neural networks, we are going to answer three questions: What, How and Why?" }, { "code": null, "e": 809, "s": 603, "text": "The neural networks that we are going to considered are strictly called artificial neural networks, and as the name suggests, are based on what science knows about the human brain’s structure and function." }, { "code": null, "e": 2304, "s": 809, "text": "Briefly, a neural network is defined as a computing system that consist of a number of simple but highly interconnected elements or nodes, called ‘neurons’, which are organized in layers which process information using dynamic state responses to external inputs. This algorithm is extremely useful, as we will explain later, in finding patterns that are too complex for being manually extracted and taught to recognize to the machine. In the context of this structure, patterns are introduced to the neural network by the input layer that has one neuron for each component present in the input data and is communicated to one or more hidden layers present in the network; called ‘hidden’ only due to the fact that they do not constitute the input or output layer. It is in the hidden layers where all the processing actually happens through a system of connections characterized by weights and biases (commonly referred as W and b): the input is received, the neuron calculate a weighted sum adding also the bias and according to the result and a pre-set activation function (most common one is sigmoid, σ, even though it almost not used anymore and there are better ones like ReLu), it decides whether it should be ‘fired’ or activated. Afterwards, the neuron transmit the information downstream to other connected neurons in a process called ‘forward pass’. At the end of this process, the last hidden layer is linked to the output layer which has one neuron for each possible desired output." }, { "code": null, "e": 2535, "s": 2304, "text": "Now that we have an idea on how the basic structure of a Neural Network look likes, we will go ahead and explain how it works. In order to do so, we need to explain the different type of neurons that we can include in our network." }, { "code": null, "e": 2736, "s": 2535, "text": "The first type of neuron that we are going to explain is Perceptron. Even though its use has decayed today, understanding how they work will give us a good clue about how more modern neurons function." }, { "code": null, "e": 2961, "s": 2736, "text": "A perceptron uses a function to learn a binary classifier by mapping a vector of binary variables to a single binary output and it can also be used in supervised learning. In this context, the perceptron follows these steps:" }, { "code": null, "e": 3345, "s": 2961, "text": "Multiply all the inputs by their weights w, real numbers that express how important the corresponding inputs are to the output,Add them together referred as weighted sum: ∑ wj xj,Apply the activation function, in other words, determine whether the weighted sum is greater than a threshold value, where -threshold is equivalent to bias, and assign 1 or less and assign 0 as an output." }, { "code": null, "e": 3473, "s": 3345, "text": "Multiply all the inputs by their weights w, real numbers that express how important the corresponding inputs are to the output," }, { "code": null, "e": 3526, "s": 3473, "text": "Add them together referred as weighted sum: ∑ wj xj," }, { "code": null, "e": 3731, "s": 3526, "text": "Apply the activation function, in other words, determine whether the weighted sum is greater than a threshold value, where -threshold is equivalent to bias, and assign 1 or less and assign 0 as an output." }, { "code": null, "e": 3797, "s": 3731, "text": "We can also write the perceptron function in the following terms:" }, { "code": null, "e": 4421, "s": 3797, "text": "One of the strongest point in this algorithm is that we can vary the weights and the bias to obtain distinct models of decision-making. We can assign more weight to those inputs so that if they are positive, it will favor our desired output. Also, because the bias can be understood as a measure of how difficult or easy is to output 1, we can drop or raise its value if we want to make more or less likely the desired output to happen. If we pay attention to the formula, we can observe that a big positive bias will make it very easy to output 1; however a very negative bias will make the task of output 1 very unlikely." }, { "code": null, "e": 4751, "s": 4421, "text": "In consequence, a perceptron can analyze different evidence or data and make a decision according to the set preferences. It is possible, in fact, to create more complex networks including more layers of perceptrons where every layer takes the output of the previous one and weights it and make a more and more complex decisions." }, { "code": null, "e": 5678, "s": 4751, "text": "What wait a minute: If perceptrons can do a good job in making complex decisions, why do we need other type of neuron? One of the disadvantages about a network containing perceptrons is that small changes in weights or bias, even in only one perceptron, can severely change our output going from 0 to 1 or vice versa. What we really want is to be able to gradually change the behaviour of our network by introducing small modifications in the weights or bias. Here is where a more modern type of neuron come in handy (Nowadays its use has been replaced by other types like Tanh and lately, by ReLu): Sigmoid neurons. The main difference between a sigmoid neuron and a perceptron is that the input and the output can be any continuous value between 0 and 1. The output is obtained after applying the sigmoid function to the inputs considering the weights, w, and the bias, b. To visualize it better, we can write the following:" }, { "code": null, "e": 5712, "s": 5678, "text": "So, the formula of the output is:" }, { "code": null, "e": 6370, "s": 5712, "text": "If we perform a mathematical analysis of this function, we can make a graph of our function σ , shown below, and conclude that when z is large and positive the function reaches its maximum asymptotic value of 1; however, if z is large and negative, the function reaches its minimum asymptotic value of 0. Here is where the sigmoid function becomes very interesting because it is with moderate values of z that the function takes a smooth and close to linear shape. In this interval, small changes in weights (Δwj) or in bias (Δbj) will generate small changes in the output; the desired behaviour that we were looking for as an improvement from a perceptron." }, { "code": null, "e": 6647, "s": 6370, "text": "z = np.arange(-10, 10, 0.3)\nsigm = 1 / (1 + np.exp(-z))\nplt.plot(z, sigm, color = 'mediumvioletred', linewidth= 1.5)\nplt.xlabel('Z', size = 14, alpha = 0.8)\nplt.ylabel('σ(z)', size = 14, alpha = 0.8)\na = plt.title('Sigmoid Function', size = 14)\na = a.set_position([.5, 1.05])\n" }, { "code": null, "e": 7222, "s": 6650, "text": "We know that the derivative of a function is the measure of the rate at which the value y changes with respect to the change of the variable x. In this case, the variable y is our output and the variable x is a function of the weights and the bias. We can take advantage of this and calculate the change in the output using the derivatives, and particularly, the partial derivatives (with respect to w and with respect to b). You can read this post to follow the calculations but in the case of sigmoid function, the derivative will be reduce to calculate: f(z)*(1-f(z))." }, { "code": null, "e": 7292, "s": 7222, "text": "Here it’s a simple code that can be used to model a sigmoid function:" }, { "code": null, "e": 7635, "s": 7292, "text": "We have just explain the functioning of every neuron in our network, but now, we can examine how the rest of the it works. A neural networks in which the output from one layer is used as the input of the next layer is called feedforward, particularly because there is no loops involved and the information is only pass forward and never back." }, { "code": null, "e": 8279, "s": 7635, "text": "Suppose that we have a training set and we want to use a 3-layer neural network, in which we also use the sigmoid neuron we saw above, to predict a certain feature. Taking what we explain about the structure of a neural network, weights and bias need to be first assigned to the connections between neurons in one layer and the next layer. Normally, the biases and weights are all initialized randomly in a synapsis matrix. If we are coding the neural network in python, we can use the Numpy function np.random.random generating a Gaussian distributions (where mean is equal to 0 and standard deviation to 1) to have a place to start learning." }, { "code": null, "e": 8478, "s": 8279, "text": "After that, we will build the neural network starting with the Feedforward step to calculate the predicted output; in other words, we just need to build the different layers involved in the network:" }, { "code": null, "e": 8560, "s": 8478, "text": "layer0 is the input layer; our training set read as a matrix (We can called it X)" }, { "code": null, "e": 8724, "s": 8560, "text": "layer1 is obtained by apply the activation function a’ = σ(w.X+b), in our case, performing the dot multiplication between input layer0 and the synapsis matrix syn0" }, { "code": null, "e": 8822, "s": 8724, "text": "layer2is the output layer obtained by the dot multiplication between layer1 and its synapsis syn1" }, { "code": null, "e": 8967, "s": 8822, "text": "We will also need to iterate over the training set to let the network learn (we will see this later). In order to do so, we will add a for loop." }, { "code": null, "e": 9305, "s": 8967, "text": "Until now, we have create the basic structure of the neural network: the different layers, the weights and bias of the connection between the neurons, and the sigmoid function. But none of this explains how the neural network can do such a good job in predicting patterns in a dataset. And this is what will take us to our last question." }, { "code": null, "e": 9764, "s": 9305, "text": "The main strength of machine learning algorithms is their ability to learn and improve every time in predicting an output. But what does it mean that they can learn? In the context of neural networks, it implies that the weights and biases that define the connection between neurons become more precise; this is, eventually, the weights and biases are selected such as the output from the network approximates the real value y(x) for all the training inputs." }, { "code": null, "e": 10325, "s": 9764, "text": "So, how do we quantify how far our prediction is from our real value in order for us to know if we need to keep searching for more precise parameters? For this aim, we need to calculate an error or in other words, define a cost function (Cost function is not other thing that the error in predicting the correct output that our network has; in other terms, it is the difference between the expected and the predicted output). In neural networks, the most commonly used one is the quadratic cost function, also called mean squared error, defined by the formula:" }, { "code": null, "e": 10667, "s": 10325, "text": "This function is preferred over the linear error due to the fact that in neural networks small changes in weights and biases do not produces any change in the number of correct outputs; so using a quadratic function where big differences have more effect on the cost function than small ones help figuring out how to modify these parameters." }, { "code": null, "e": 11022, "s": 10667, "text": "On the other hand, we can see that our cost function become smaller as the output is closer to the real value y, for all training inputs. The main goal of our algorithm is to minimize this cost function by finding a set of weights and biases to make it as small as possible. And the main tool to achieve this goal is an algorithm called Gradient Descent." }, { "code": null, "e": 11547, "s": 11022, "text": "Then, the next question that we should answer is how we can minimize the cost function. From calculus, we know that a function can have global maximum and/or minimum, that is, where the function achieves the maximum or minimum value that it can have. We also know that one way to obtained that point is calculating derivatives. However, it is easy to calculate when we have a function with two variables but in the case of neural network, they include a lot of variables which make this computation quite impossible to make." }, { "code": null, "e": 11615, "s": 11547, "text": "Instead, let’s take a look at the graph below of a random function:" }, { "code": null, "e": 12147, "s": 11615, "text": "We can see that this function has a global minimum. We could, as we said before, compute the derivatives to calculate where the minimum is located or we could take another approach. We can start in a random point and try to make a small move in the direction of the arrow, we would mathematically speaking, move Δx in the direction x and Δy in the direction of y, and calculate the change in our function ΔC. Because the rate of change in a direction is the derivative of a function, we could express the change in the function as:" }, { "code": null, "e": 12226, "s": 12147, "text": "Here, we will take the definition from calculus of the gradient of a function:" }, { "code": null, "e": 12277, "s": 12226, "text": "Now, we can rewrite the change in our function as:" }, { "code": null, "e": 12921, "s": 12277, "text": "So now, we can see what happens with cost function when we choose a certain change in our parameters. The amount that we choose to move in any direction is called learning rate, and it is what define how fast we move towards the global minimum. If we choose a very small number, we will need to make a too many moves to reach this point; however, if we choose a very big number, we are at risk of passing the point and never be able to reach it. So the challenge is to choose the learning rate small enough. After choosing the learning rate, we can update our weights and biases and make another move; process that we repeat in each iteration." }, { "code": null, "e": 13180, "s": 12921, "text": "So, in few words, the gradient descent works by computing the gradient ∇C repeatedly, and then updating the weights and biases, and trying to find the correct values that minimize, in that way, the cost of function. And this is how the neural network learns." }, { "code": null, "e": 13596, "s": 13180, "text": "Sometimes, calculating the gradient can be very complex. There is, however, a way to speed up this calculations called stochastic gradient descent. This works by estimating the gradient ∇C by computing instead the gradient for a small sample of randomly chosen training inputs. Then, this small samples are average to get a good estimate of the true gradient, speeding up gradient descent, and thus learning faster." }, { "code": null, "e": 15119, "s": 13596, "text": "But wait a second? How do we compute the gradient of the cost function? Here is where another algorithm makes an entry: Backpropagation. The goal of this algorithm is to compute the partial derivatives of the cost function with respect to any weight w and any bias b; in practice, this means calculating the error vectors starting from the final layer and then, propagating this back to update the weights and biases. The reason why we need to go back is that the cost is a function of the output of our network. There are several calculations and errors that we need to compute whose formula are given by the backpropagation algorithm: 1) Output error (δL) related to the element wise (⦿) product of the gradient (▽C) by the derivative of activation function (σ′(z)), 2) error of one layer (ẟl) in terms of the error in the next layer related to the transpose matrix of the weights (Wl+1) multiplied by the error of the next layer (ẟl+1) and the element wise multiplication of the derivative of activation function, 3) rate of change of the cost with respect to any bias in the network: this means that the partial derivative of C with respect to any bias (∂C/∂bj) is equal to the error ẟl, 4) rate of change of the cost with respect to any weight in the network: meaning that the partial derivative of C with respect to any weight (∂C/∂wj) is equal to the error (ẟl) multiplied by activation of the neuron input. These last two calculation constitute the gradient of the cost function. Here, we can observe the formulas." }, { "code": null, "e": 15413, "s": 15119, "text": "The backpropagation algorithm calculates the gradient of the cost function for only one single training example. As a consequence, we need to combine backpropagation with a learning algorithm, for instance stochastic gradient descent, in order to compute the gradient for all the training set." }, { "code": null, "e": 15521, "s": 15413, "text": "Now, how do we apply this to our neural network in python?. Here, we can see step by step the calculations:" }, { "code": null, "e": 15648, "s": 15521, "text": "Now we can put all of these formulas and concepts that we have seen in terms of an algorithm to see how we can implement this:" }, { "code": null, "e": 15756, "s": 15648, "text": "INPUT: We input a set of training examples and we set the activation a that correspond for the input layer." }, { "code": null, "e": 15839, "s": 15756, "text": "FEEDFORWARD: For each layer, we compute the function z = w . a + b, being a = σ(z)" }, { "code": null, "e": 15918, "s": 15839, "text": "OUTPUT ERROR: We compute the output error by using the formula #1 cited above." }, { "code": null, "e": 16022, "s": 15918, "text": "BACKPROPAGATION: Now we backpropagate the error; for each layer, we compute the formula #2 cited above." }, { "code": null, "e": 16133, "s": 16022, "text": "OUTPUT: We calculate the gradient descent with respect to any weight and bias by using the formulas #3 and #4." }, { "code": null, "e": 16469, "s": 16133, "text": "Of course, that there are more concepts, implementations and improvements that can be done to neural networks, which can become more and more widely used and powerful through the last years. But I hope this information can give you a hint on what a neural network is, how it works and learns using gradient descent and backpropagation." }, { "code": null, "e": 16481, "s": 16469, "text": "References:" }, { "code": null, "e": 16532, "s": 16481, "text": "Neural Networks and Deep Learning. Michael Nielsen" }, { "code": null, "e": 16581, "s": 16532, "text": "Build a Neural Network in 4 minutes. Siraj Raval" } ]
How to Win in the NFL with Machine Learning | by Rich Folsom | Towards Data Science
You have been hired as the defensive coordinator for the Dallas Cowboys, and you are coaching against the New England Patriots in the Super Bowl. I realize this is a highly unlikely scenario given that the Cowboys don’t look anything like a Super Bowl contender. However, we can still use this as an example project for the steps to create an AI/ML model. The Patriots have been the best team in the NFL over the last two decades, and Tom Brady, the Patriots’ quarterback has been arguably the best player in the NFL over the same timespan. As a defensive coordinator, it will be a huge task to stop the Patriots. However, we have an advantage on our side: AI/ML. Let’s lay out a process to see if we can predict the plays before they happen, which will enable us to adjust our defensive scheme accordingly. We will be using Python and sklearn for this example. Here is the process we will follow: Acquire or generate dataPrepare the data for Exploratory Data Analysis (EDA).Analyze the data to look for potential patterns.Prepare the data for AI/ML models.Train and evaluate your chosen AI/ML model. Acquire or generate data Prepare the data for Exploratory Data Analysis (EDA). Analyze the data to look for potential patterns. Prepare the data for AI/ML models. Train and evaluate your chosen AI/ML model. The first thing you’re going to need is a dataset. If you don’t have access to a relevant dataset, you can generate a sample dataset using a process like this article. For our example, we will be using this dataset containing information on every NFL play that has been run since 2009. It’s hosted on Kaggle. If you’re not familiar with Kaggle, it’s a coding competition website with many different datasets; this is usually the first place I check when I want to find some data. Once we have downloaded and unzipped the file, we need it in a format that enables us to explore the data. For this, we will be using Pandas, a Python library that contains numerous functions to modify and explore the dataset. Here is the code to load the dataframe from our CSV file: import pandas as pdimport matplotlibfrom sklearn import preprocessing%matplotlib inlinedf = pd.read_csv('data/nfl_plays.csv') EDA is the process of exploring the data for issues (missing values, incorrectly typed data, etc...) and hopefully, we can see some trends in the data. First off, let’s see how many rows and columns we’ve loaded: df.shape which gives: (449371, 255) As you can see, there is a lot of information in this data set (255 columns). It would be nice to know what each field represents. It took some digging, but I ended up finding this page, which describes all of the columns and what they mean. I am interested in these fields: posteam — the team with possession (in this case, we only want NE) game_seconds_remaining — how much time remains in the game yardline_100 — what yard line is the team on (scaled to 100) down — what down are we on(1.0, 2.0, 3.0, 4.0) ydstogo — yards needed for a first down shotgun — are they lined up in the shotgun formation? score_differential — their score-our score play_type — the type of play(run, pass, etc...) run_location — which way did they run(left, middle, right) pass_location — which way did they pass(left, middle, right) There are other fields that we could use to help predict, but let’s use these for starters. Here’s the code to filter by these rows and columns #filter rowsnedf = df[(df.posteam=='NE') & (df.down.isin([1.0, 2.0, 3.0, 4.0])) & ((df.play_type=='run') | (df.play_type == 'pass'))]#filter columnsnedf = nedf[['game_seconds_remaining', 'yardline_100', 'down', 'ydstogo', 'shotgun', 'score_differential', 'play_type', 'pass_length', 'pass_location', 'run_location']]nedf.head() At this point, we have one more step before we can begin EDA. The value we’re trying to predict is represented by four columns which are dependent on the play_type. For example: If the play type is ‘run,’ run_location would be populated, but pass_location would not be. If the play type is ‘pass,’ pass_location would be populated but run_location would not be. We need to combine all of these values into a single field. Here’s the code to do that (note, we are also filtering out location=’unknown’): import numpy as npdef get_full_play_type(play): play_type, pass_location, run_location = play if(play_type == 'run'): return play_type+'_'+ run_location else: return play_type+'_'+ pass_locationnedf = nedf.replace(np.nan, 'unknown', regex=True) nedf['full_play_type'] = nedf[['play_type','pass_location', 'run_location']].apply(get_full_play_type, axis=1)nedf = nedf[(nedf.full_play_type.isin(['pass_left', 'pass_middle','pass_right','run_left', 'run_middle', 'run_right']))] This code will create a column called full_play_type, which is what we’re trying to predict. Let’s take one last look at our data to make sure everything looks ok: nedf.head() First, let’s see what values our full_play_type contains: nedf.groupby(['full_play_type']).count()[['play_type']] As you can see, if we were to randomly guess the next play, we’d have a one in six chance (16.66%) of being correct. We will use this as our baseline to see if we can improve. Sometimes it helps to view this in chart format: nedf.groupby(['full_play_type']).count()[['play_type']].plot(kind='bar') Next, let’s get an idea of which plays are called by percent of total: nedf.groupby(['full_play_type']).count()[['play_type']].apply(lambda x:100 * x / float(x.sum())) We’ve already got improvement in our predictions! If we predict pass_left for every play, we’d be correct 23% of the time vs. 16.66% of the time. We can still do better. AI/ML models require numeric inputs and outputs. They also work better when the scale of the numbers are similar. In this section, we will utilize some different techniques to achieve this. First, we will use sklearn’s preprocessing library to convert our full_play_types to numeric: le = preprocessing.LabelEncoder()le.fit(nedf.full_play_type)nedf['full_play_type_code'] = le.transform(nedf['full_play_type']) This creates a column called full_play_type_code, which is a numeric representation of full_play_type. Let’s look at the full_play_type_code data and make sure that it still matches full_play_type. nedf.groupby(['full_play_type_code']).count()[['down']].plot(kind='bar') As you can see, the chart matches the one above, but now the x-axis is a numeric value, instead of text. Next, I want to simplify the ydstogo value. Technically speaking this can be a value between 1 and 99. However, I want to put this distance into some buckets (1–4yds, 5–8yds, 9–12yds, 13–16yds, ≥17yds) which should enable our model to identify patterns. The ranges I picked are arbitrary and can be easily modified. def bucketize(val, size, count): i=0 for i in range(count): if val <= (i+1)*size: return i return idef bucketize_df(df): df['ydstogo'] = [bucketize(x, 4, 5) for x in df['ydstogo']] return dfnedf = bucketize_df(nedf) Now, I want to one hot encode the down and ydstogo columns, which means we will ‘pivot’ the rows to columns and populate the column containing the value we’re encoding with a ‘1’, otherwise zeros. For instance, there are four downs in football. When we one hot encode the down column, we will end up with four columns in which a one will be populated only once. If we were to one hot encode a row that represented third down, we’d end up with these values for our new columns[0, 0, 1, 0]. Notice the 3rd column is the only one to contain a one. The advantage of doing this is that our down and ydstogo data is now represented as zeros and ones, which should also help our model learn. The code for this is very simple in sklearn: nedf = pd.concat([nedf, pd.get_dummies(nedf['down'], prefix='down')], axis=1)nedf = pd.concat([nedf, pd.get_dummies(nedf['ydstogo'], prefix='ydstogo')], axis=1) Here’s what a sample of our data looks like at this point: Now, you can see that ydstogo_* and down_* are represented by zeroes and ones. However, the game_seconds_remaining, yardline_100 and score differential columns are still on a different scale than zero and one. For instance, game seconds remaining contains a value between zero and 3600. We can fix that by adding some math to the columns. First, let’s see what the ranges of values these columns contain. nedf.describe() For this exercise, we will be looking at the min and max values and use those to normalize the data to a value between zero and one. The min for game_seconds_remaining is 3, while the max is 3600. We will divide game_seconds_remaining by 3600. Yardline_100 will be divided by 100. For score differential, we’ll apply this formula: (score_diff + min_diff) / (max_diff-min_diff) However, to simplify, we’ll just use -50 for min_diff, and 50 for max_diff. Our logic is that if you’re winning or losing by more than 50 points, you’ve got other things on your mind at this point. Here’s our code to apply these formulas: nedf['game_seconds_remaining']/=3600nedf['yardline_100']/=100nedf['score_differential']=(nedf['score_differential']+50)/100 Now, if we look at our dataset, here’s what we get: We now have all of our input fields converted to values between zero and one, so we’re ready to try it out on a model. For this tutorial, we will be using the RandomForestClassifier to see if we can predict the next play. But first, we need to get rid of all the columns we don’t want for our model. Then, we need to split our data into a train and test set, each containing an X (input data) and y(result data). This can be done quickly with three lines of Python. from sklearn.model_selection import train_test_split#select important columns for inputX=nedf[['yardline_100', 'shotgun', 'score_differential', 'game_seconds_remaining', 'down_1.0', 'down_2.0', 'down_3.0', 'down_4.0','ydstogo_0','ydstogo_1','ydstogo_2','ydstogo_3','ydstogo_4']]#select result column for outputY=nedf['full_play_type_code']#split data for train and testtrain_x, test_x, train_y, test_y = train_test_split(X, Y, random_state = 0) At this point, we can train our model to fit the input data. from sklearn.ensemble import RandomForestClassifierthe_clf=RandomForestClassifier(max_depth=8, n_estimators=64)the_clf.fit(train_x, train_y) Now that our model has been trained, let’s see how it scores on our test data. from sklearn.metrics import accuracy_scorepred = the_clf.predict(test_x)acc =accuracy_score(test_y, pred)print(acc) We are now able to predict the correct play 31% of the time, which may not sound great, but keep in mind that it’s almost double where we started by randomly guessing (16.66%) and 25% better than just guessing the play they like to run the most (pass_left, 23%). With just a few lines of Python code, we have almost doubled our coaching skills. You may have noticed, however, that the majority of the code we’ve written is related to organizing and curating our data. Now that we’ve done that, we can use this data to train more complex models. In our next article, we will explore four techniques to generate even better predictions utilizing the data we have processed: Oversampling/data augmentationModel selectionModel evaluationModel tuning Oversampling/data augmentation Model selection Model evaluation Model tuning Thanks for reading, the code for this article will be hosted on github.
[ { "code": null, "e": 528, "s": 172, "text": "You have been hired as the defensive coordinator for the Dallas Cowboys, and you are coaching against the New England Patriots in the Super Bowl. I realize this is a highly unlikely scenario given that the Cowboys don’t look anything like a Super Bowl contender. However, we can still use this as an example project for the steps to create an AI/ML model." }, { "code": null, "e": 1070, "s": 528, "text": "The Patriots have been the best team in the NFL over the last two decades, and Tom Brady, the Patriots’ quarterback has been arguably the best player in the NFL over the same timespan. As a defensive coordinator, it will be a huge task to stop the Patriots. However, we have an advantage on our side: AI/ML. Let’s lay out a process to see if we can predict the plays before they happen, which will enable us to adjust our defensive scheme accordingly. We will be using Python and sklearn for this example. Here is the process we will follow:" }, { "code": null, "e": 1273, "s": 1070, "text": "Acquire or generate dataPrepare the data for Exploratory Data Analysis (EDA).Analyze the data to look for potential patterns.Prepare the data for AI/ML models.Train and evaluate your chosen AI/ML model." }, { "code": null, "e": 1298, "s": 1273, "text": "Acquire or generate data" }, { "code": null, "e": 1352, "s": 1298, "text": "Prepare the data for Exploratory Data Analysis (EDA)." }, { "code": null, "e": 1401, "s": 1352, "text": "Analyze the data to look for potential patterns." }, { "code": null, "e": 1436, "s": 1401, "text": "Prepare the data for AI/ML models." }, { "code": null, "e": 1480, "s": 1436, "text": "Train and evaluate your chosen AI/ML model." }, { "code": null, "e": 1960, "s": 1480, "text": "The first thing you’re going to need is a dataset. If you don’t have access to a relevant dataset, you can generate a sample dataset using a process like this article. For our example, we will be using this dataset containing information on every NFL play that has been run since 2009. It’s hosted on Kaggle. If you’re not familiar with Kaggle, it’s a coding competition website with many different datasets; this is usually the first place I check when I want to find some data." }, { "code": null, "e": 2245, "s": 1960, "text": "Once we have downloaded and unzipped the file, we need it in a format that enables us to explore the data. For this, we will be using Pandas, a Python library that contains numerous functions to modify and explore the dataset. Here is the code to load the dataframe from our CSV file:" }, { "code": null, "e": 2371, "s": 2245, "text": "import pandas as pdimport matplotlibfrom sklearn import preprocessing%matplotlib inlinedf = pd.read_csv('data/nfl_plays.csv')" }, { "code": null, "e": 2523, "s": 2371, "text": "EDA is the process of exploring the data for issues (missing values, incorrectly typed data, etc...) and hopefully, we can see some trends in the data." }, { "code": null, "e": 2584, "s": 2523, "text": "First off, let’s see how many rows and columns we’ve loaded:" }, { "code": null, "e": 2593, "s": 2584, "text": "df.shape" }, { "code": null, "e": 2606, "s": 2593, "text": "which gives:" }, { "code": null, "e": 2620, "s": 2606, "text": "(449371, 255)" }, { "code": null, "e": 2895, "s": 2620, "text": "As you can see, there is a lot of information in this data set (255 columns). It would be nice to know what each field represents. It took some digging, but I ended up finding this page, which describes all of the columns and what they mean. I am interested in these fields:" }, { "code": null, "e": 2962, "s": 2895, "text": "posteam — the team with possession (in this case, we only want NE)" }, { "code": null, "e": 3021, "s": 2962, "text": "game_seconds_remaining — how much time remains in the game" }, { "code": null, "e": 3082, "s": 3021, "text": "yardline_100 — what yard line is the team on (scaled to 100)" }, { "code": null, "e": 3129, "s": 3082, "text": "down — what down are we on(1.0, 2.0, 3.0, 4.0)" }, { "code": null, "e": 3169, "s": 3129, "text": "ydstogo — yards needed for a first down" }, { "code": null, "e": 3223, "s": 3169, "text": "shotgun — are they lined up in the shotgun formation?" }, { "code": null, "e": 3266, "s": 3223, "text": "score_differential — their score-our score" }, { "code": null, "e": 3314, "s": 3266, "text": "play_type — the type of play(run, pass, etc...)" }, { "code": null, "e": 3373, "s": 3314, "text": "run_location — which way did they run(left, middle, right)" }, { "code": null, "e": 3434, "s": 3373, "text": "pass_location — which way did they pass(left, middle, right)" }, { "code": null, "e": 3578, "s": 3434, "text": "There are other fields that we could use to help predict, but let’s use these for starters. Here’s the code to filter by these rows and columns" }, { "code": null, "e": 3906, "s": 3578, "text": "#filter rowsnedf = df[(df.posteam=='NE') & (df.down.isin([1.0, 2.0, 3.0, 4.0])) & ((df.play_type=='run') | (df.play_type == 'pass'))]#filter columnsnedf = nedf[['game_seconds_remaining', 'yardline_100', 'down', 'ydstogo', 'shotgun', 'score_differential', 'play_type', 'pass_length', 'pass_location', 'run_location']]nedf.head()" }, { "code": null, "e": 4084, "s": 3906, "text": "At this point, we have one more step before we can begin EDA. The value we’re trying to predict is represented by four columns which are dependent on the play_type. For example:" }, { "code": null, "e": 4176, "s": 4084, "text": "If the play type is ‘run,’ run_location would be populated, but pass_location would not be." }, { "code": null, "e": 4268, "s": 4176, "text": "If the play type is ‘pass,’ pass_location would be populated but run_location would not be." }, { "code": null, "e": 4409, "s": 4268, "text": "We need to combine all of these values into a single field. Here’s the code to do that (note, we are also filtering out location=’unknown’):" }, { "code": null, "e": 4911, "s": 4409, "text": "import numpy as npdef get_full_play_type(play): play_type, pass_location, run_location = play if(play_type == 'run'): return play_type+'_'+ run_location else: return play_type+'_'+ pass_locationnedf = nedf.replace(np.nan, 'unknown', regex=True) nedf['full_play_type'] = nedf[['play_type','pass_location', 'run_location']].apply(get_full_play_type, axis=1)nedf = nedf[(nedf.full_play_type.isin(['pass_left', 'pass_middle','pass_right','run_left', 'run_middle', 'run_right']))]" }, { "code": null, "e": 5075, "s": 4911, "text": "This code will create a column called full_play_type, which is what we’re trying to predict. Let’s take one last look at our data to make sure everything looks ok:" }, { "code": null, "e": 5087, "s": 5075, "text": "nedf.head()" }, { "code": null, "e": 5145, "s": 5087, "text": "First, let’s see what values our full_play_type contains:" }, { "code": null, "e": 5201, "s": 5145, "text": "nedf.groupby(['full_play_type']).count()[['play_type']]" }, { "code": null, "e": 5377, "s": 5201, "text": "As you can see, if we were to randomly guess the next play, we’d have a one in six chance (16.66%) of being correct. We will use this as our baseline to see if we can improve." }, { "code": null, "e": 5426, "s": 5377, "text": "Sometimes it helps to view this in chart format:" }, { "code": null, "e": 5499, "s": 5426, "text": "nedf.groupby(['full_play_type']).count()[['play_type']].plot(kind='bar')" }, { "code": null, "e": 5570, "s": 5499, "text": "Next, let’s get an idea of which plays are called by percent of total:" }, { "code": null, "e": 5667, "s": 5570, "text": "nedf.groupby(['full_play_type']).count()[['play_type']].apply(lambda x:100 * x / float(x.sum()))" }, { "code": null, "e": 5837, "s": 5667, "text": "We’ve already got improvement in our predictions! If we predict pass_left for every play, we’d be correct 23% of the time vs. 16.66% of the time. We can still do better." }, { "code": null, "e": 6027, "s": 5837, "text": "AI/ML models require numeric inputs and outputs. They also work better when the scale of the numbers are similar. In this section, we will utilize some different techniques to achieve this." }, { "code": null, "e": 6121, "s": 6027, "text": "First, we will use sklearn’s preprocessing library to convert our full_play_types to numeric:" }, { "code": null, "e": 6248, "s": 6121, "text": "le = preprocessing.LabelEncoder()le.fit(nedf.full_play_type)nedf['full_play_type_code'] = le.transform(nedf['full_play_type'])" }, { "code": null, "e": 6446, "s": 6248, "text": "This creates a column called full_play_type_code, which is a numeric representation of full_play_type. Let’s look at the full_play_type_code data and make sure that it still matches full_play_type." }, { "code": null, "e": 6519, "s": 6446, "text": "nedf.groupby(['full_play_type_code']).count()[['down']].plot(kind='bar')" }, { "code": null, "e": 6624, "s": 6519, "text": "As you can see, the chart matches the one above, but now the x-axis is a numeric value, instead of text." }, { "code": null, "e": 6940, "s": 6624, "text": "Next, I want to simplify the ydstogo value. Technically speaking this can be a value between 1 and 99. However, I want to put this distance into some buckets (1–4yds, 5–8yds, 9–12yds, 13–16yds, ≥17yds) which should enable our model to identify patterns. The ranges I picked are arbitrary and can be easily modified." }, { "code": null, "e": 7189, "s": 6940, "text": "def bucketize(val, size, count): i=0 for i in range(count): if val <= (i+1)*size: return i return idef bucketize_df(df): df['ydstogo'] = [bucketize(x, 4, 5) for x in df['ydstogo']] return dfnedf = bucketize_df(nedf)" }, { "code": null, "e": 7919, "s": 7189, "text": "Now, I want to one hot encode the down and ydstogo columns, which means we will ‘pivot’ the rows to columns and populate the column containing the value we’re encoding with a ‘1’, otherwise zeros. For instance, there are four downs in football. When we one hot encode the down column, we will end up with four columns in which a one will be populated only once. If we were to one hot encode a row that represented third down, we’d end up with these values for our new columns[0, 0, 1, 0]. Notice the 3rd column is the only one to contain a one. The advantage of doing this is that our down and ydstogo data is now represented as zeros and ones, which should also help our model learn. The code for this is very simple in sklearn:" }, { "code": null, "e": 8080, "s": 7919, "text": "nedf = pd.concat([nedf, pd.get_dummies(nedf['down'], prefix='down')], axis=1)nedf = pd.concat([nedf, pd.get_dummies(nedf['ydstogo'], prefix='ydstogo')], axis=1)" }, { "code": null, "e": 8139, "s": 8080, "text": "Here’s what a sample of our data looks like at this point:" }, { "code": null, "e": 8426, "s": 8139, "text": "Now, you can see that ydstogo_* and down_* are represented by zeroes and ones. However, the game_seconds_remaining, yardline_100 and score differential columns are still on a different scale than zero and one. For instance, game seconds remaining contains a value between zero and 3600." }, { "code": null, "e": 8544, "s": 8426, "text": "We can fix that by adding some math to the columns. First, let’s see what the ranges of values these columns contain." }, { "code": null, "e": 8560, "s": 8544, "text": "nedf.describe()" }, { "code": null, "e": 8891, "s": 8560, "text": "For this exercise, we will be looking at the min and max values and use those to normalize the data to a value between zero and one. The min for game_seconds_remaining is 3, while the max is 3600. We will divide game_seconds_remaining by 3600. Yardline_100 will be divided by 100. For score differential, we’ll apply this formula:" }, { "code": null, "e": 8937, "s": 8891, "text": "(score_diff + min_diff) / (max_diff-min_diff)" }, { "code": null, "e": 9176, "s": 8937, "text": "However, to simplify, we’ll just use -50 for min_diff, and 50 for max_diff. Our logic is that if you’re winning or losing by more than 50 points, you’ve got other things on your mind at this point. Here’s our code to apply these formulas:" }, { "code": null, "e": 9300, "s": 9176, "text": "nedf['game_seconds_remaining']/=3600nedf['yardline_100']/=100nedf['score_differential']=(nedf['score_differential']+50)/100" }, { "code": null, "e": 9352, "s": 9300, "text": "Now, if we look at our dataset, here’s what we get:" }, { "code": null, "e": 9471, "s": 9352, "text": "We now have all of our input fields converted to values between zero and one, so we’re ready to try it out on a model." }, { "code": null, "e": 9818, "s": 9471, "text": "For this tutorial, we will be using the RandomForestClassifier to see if we can predict the next play. But first, we need to get rid of all the columns we don’t want for our model. Then, we need to split our data into a train and test set, each containing an X (input data) and y(result data). This can be done quickly with three lines of Python." }, { "code": null, "e": 10263, "s": 9818, "text": "from sklearn.model_selection import train_test_split#select important columns for inputX=nedf[['yardline_100', 'shotgun', 'score_differential', 'game_seconds_remaining', 'down_1.0', 'down_2.0', 'down_3.0', 'down_4.0','ydstogo_0','ydstogo_1','ydstogo_2','ydstogo_3','ydstogo_4']]#select result column for outputY=nedf['full_play_type_code']#split data for train and testtrain_x, test_x, train_y, test_y = train_test_split(X, Y, random_state = 0)" }, { "code": null, "e": 10324, "s": 10263, "text": "At this point, we can train our model to fit the input data." }, { "code": null, "e": 10465, "s": 10324, "text": "from sklearn.ensemble import RandomForestClassifierthe_clf=RandomForestClassifier(max_depth=8, n_estimators=64)the_clf.fit(train_x, train_y)" }, { "code": null, "e": 10544, "s": 10465, "text": "Now that our model has been trained, let’s see how it scores on our test data." }, { "code": null, "e": 10660, "s": 10544, "text": "from sklearn.metrics import accuracy_scorepred = the_clf.predict(test_x)acc =accuracy_score(test_y, pred)print(acc)" }, { "code": null, "e": 10923, "s": 10660, "text": "We are now able to predict the correct play 31% of the time, which may not sound great, but keep in mind that it’s almost double where we started by randomly guessing (16.66%) and 25% better than just guessing the play they like to run the most (pass_left, 23%)." }, { "code": null, "e": 11205, "s": 10923, "text": "With just a few lines of Python code, we have almost doubled our coaching skills. You may have noticed, however, that the majority of the code we’ve written is related to organizing and curating our data. Now that we’ve done that, we can use this data to train more complex models." }, { "code": null, "e": 11332, "s": 11205, "text": "In our next article, we will explore four techniques to generate even better predictions utilizing the data we have processed:" }, { "code": null, "e": 11406, "s": 11332, "text": "Oversampling/data augmentationModel selectionModel evaluationModel tuning" }, { "code": null, "e": 11437, "s": 11406, "text": "Oversampling/data augmentation" }, { "code": null, "e": 11453, "s": 11437, "text": "Model selection" }, { "code": null, "e": 11470, "s": 11453, "text": "Model evaluation" }, { "code": null, "e": 11483, "s": 11470, "text": "Model tuning" } ]
Is it possible to synchronize the string type in Java?
A thread is a piece of code (under execution) in a program, which executes a sub task of the process independently. independent process. In other words, a thread is a light weight process which executes a piece of code independently. If a process has multiple threads running independently at the same time (multi-threading) and if all of them trying to access a same resource an issue occurs. To resolve this, Java provides synchronized blocks/ synchronized methods. If you define a resource (variable/object/array) inside a synchronized block or a synchronized method, if one thread is using/accessing it, other threads are not allowed to access. synchronized (Lock1) { System.out.println("Thread 1: Holding lock 1..."); } It is not recommended to use objects which are pooled and reused, if you do so there is a chance of getting into deadlock condition down the line. Since Strings are pooled in String constant pool and reused, it is not suggestable lock String types with Synchronization.
[ { "code": null, "e": 1199, "s": 1062, "text": "A thread is a piece of code (under execution) in a program, which executes a sub task of the process independently. independent process." }, { "code": null, "e": 1296, "s": 1199, "text": "In other words, a thread is a light weight process which executes a piece of code independently." }, { "code": null, "e": 1456, "s": 1296, "text": "If a process has multiple threads running independently at the same time (multi-threading) and if all of them trying to access a same resource an issue occurs." }, { "code": null, "e": 1711, "s": 1456, "text": "To resolve this, Java provides synchronized blocks/ synchronized methods. If you define a resource (variable/object/array) inside a synchronized block or a synchronized method, if one thread is using/accessing it, other threads are not allowed to access." }, { "code": null, "e": 1790, "s": 1711, "text": "synchronized (Lock1) {\n System.out.println(\"Thread 1: Holding lock 1...\");\n}" }, { "code": null, "e": 1937, "s": 1790, "text": "It is not recommended to use objects which are pooled and reused, if you do so there is a chance of getting into deadlock condition down the line." }, { "code": null, "e": 2060, "s": 1937, "text": "Since Strings are pooled in String constant pool and reused, it is not suggestable lock String types with Synchronization." } ]
Maximum and minimum sums from two numbers with digit replacements - GeeksforGeeks
05 May, 2021 Given two positive numbers calculate the minimum and maximum possible sums of two numbers. We are allowed to replace digit 5 with digit 6 and vice versa in either or both the given numbers.Examples : Input : x1 = 645 x2 = 666 Output : Minimum Sum: 1100 (545 + 555) Maximum Sum: 1312 (646 + 666) Input: x1 = 5466 x2 = 4555 Output: Minimum sum: 10010 Maximum Sum: 11132 Since both numbers are positive, we always get maximum sum if replace 5 with 6 in both numbers. And we get a minimum sum if we replace 6 with 5 in both numbers. Below is C++ implementation based on this fact. C++ Java Python3 C# PHP Javascript // C++ program to find maximum and minimum// possible sums of two numbers that we can// get if replacing digit from 5 to 6 and vice// versa are allowed.#include<bits/stdc++.h>using namespace std; // Find new value of x after replacing digit// "from" to "to"int replaceDig(int x, int from, int to){ int result = 0; int multiply = 1; while (x > 0) { int reminder = x % 10; // Required digit found, replace it if (reminder == from) result = result + to * multiply; else result = result + reminder * multiply; multiply *= 10; x = x / 10; } return result;} // Returns maximum and minimum possible sums of// x1 and x2 if digit replacements are allowed.void calculateMinMaxSum(int x1, int x2){ // We always get minimum sum if we replace // 6 with 5. int minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5); // We always get maximum sum if we replace // 5 with 6. int maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6); cout << "Minimum sum = " << minSum; cout << "nMaximum sum = " << maxSum;} // Driver codeint main(){ int x1 = 5466, x2 = 4555; calculateMinMaxSum(x1, x2); return 0;} // Java program to find maximum and minimum// possible sums of two numbers that we can// get if replacing digit from 5 to 6 and vice// versa are allowed.class GFG { // Find new value of x after replacing digit // "from" to "to" static int replaceDig(int x, int from, int to) { int result = 0; int multiply = 1; while (x > 0) { int reminder = x % 10; // Required digit found, replace it if (reminder == from) result = result + to * multiply; else result = result + reminder * multiply; multiply *= 10; x = x / 10; } return result; } // Returns maximum and minimum possible sums of // x1 and x2 if digit replacements are allowed. static void calculateMinMaxSum(int x1, int x2) { // We always get minimum sum if we replace // 6 with 5. int minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5); // We always get maximum sum if we replace // 5 with 6. int maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6); System.out.print("Minimum sum = " + minSum); System.out.print("\nMaximum sum = " + maxSum); } // Driver code public static void main (String[] args) { int x1 = 5466, x2 = 4555; calculateMinMaxSum(x1, x2); }} // This code is contributed by Anant Agarwal. # Python3 program to find maximum# and minimum possible sums of# two numbers that we can get if# replacing digit from 5 to 6# and vice versa are allowed. # Find new value of x after# replacing digit "from" to "to"def replaceDig(x, from1, to): result = 0 multiply = 1 while (x > 0): reminder = x % 10 # Required digit found, # replace it if (reminder == from1): result = result + to * multiply else: result = result + reminder * multiply multiply *= 10 x = int(x / 10) return result # Returns maximum and minimum# possible sums of x1 and x2# if digit replacements are allowed.def calculateMinMaxSum(x1, x2): # We always get minimum sum # if we replace 6 with 5. minSum = replaceDig(x1, 6, 5) +replaceDig(x2, 6, 5) # We always get maximum sum # if we replace 5 with 6. maxSum = replaceDig(x1, 5, 6) +replaceDig(x2, 5, 6) print("Minimum sum =" , minSum) print("Maximum sum =" , maxSum,end=" ") # Driver codeif __name__=='__main__': x1 = 5466 x2 = 4555 calculateMinMaxSum(x1, x2) # This code is contributed# by mits // C# program to find maximum and minimum// possible sums of two numbers that we can// get if replacing digit from 5 to 6 and vice// versa are allowed.using System; class GFG { // Find new value of x after // replacing digit "from" to "to" static int replaceDig(int x, int from, int to) { int result = 0; int multiply = 1; while (x > 0) { int reminder = x % 10; // Required digit found, // replace it if (reminder == from) result = result + to * multiply; else result = result + reminder * multiply; multiply *= 10; x = x / 10; } return result; } // Returns maximum and minimum // possible sums of x1 and x2 // if digit replacements are allowed. static void calculateMinMaxSum(int x1, int x2) { // We always get minimum sum if // we replace 6 with 5. int minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5); // We always get maximum sum if // we replace 5 with 6. int maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6); Console.Write("Minimum sum = " + minSum); Console.Write("\nMaximum sum = " + maxSum); } // Driver code public static void Main () { int x1 = 5466, x2 = 4555; calculateMinMaxSum(x1, x2); }} // This code is contributed by Nitin Mittal. <?php// PHP program to find maximum// and minimum possible sums of// two numbers that we can get if// replacing digit from 5 to 6// and vice versa are allowed. // Find new value of x after// replacing digit "from" to "to"function replaceDig($x, $from, $to){ $result = 0; $multiply = 1; while ($x > 0) { $reminder = $x % 10; // Required digit found, // replace it if ($reminder == $from) $result = $result + $to * $multiply; else $result = $result + $reminder * $multiply; $multiply *= 10; $x = $x / 10; } return $result;} // Returns maximum and minimum// possible sums of x1 and x2// if digit replacements are allowed.function calculateMinMaxSum($x1, $x2){ // We always get minimum sum // if we replace 6 with 5.$minSum = replaceDig($x1, 6, 5) + replaceDig($x2, 6, 5); // We always get maximum sum // if we replace 5 with 6. $maxSum = replaceDig($x1, 5, 6) + replaceDig($x2, 5, 6); echo "Minimum sum = " , $minSum,"\n"; echo "Maximum sum = " , $maxSum;} // Driver code$x1 = 5466; $x2 = 4555;calculateMinMaxSum($x1, $x2); // This code is contributed// by nitin mittal.?> <script> // Javascript program to find maximum and minimum// possible sums of two numbers that we can// get if replacing digit from 5 to 6 and vice// versa are allowed. // Find new value of x after replacing digit// "from" to "to"function replaceDig(x , from , to){ var result = 0; var multiply = 1; while (x > 0) { var reminder = x % 10; // Required digit found, replace it if (reminder == from) result = result + to * multiply; else result = result + reminder * multiply; multiply *= 10; x = parseInt(x / 10); } return result;} // Returns maximum and minimum possible sums of// x1 and x2 if digit replacements are allowed.function calculateMinMaxSum(x1 , x2){ // We always get minimum sum if we replace // 6 with 5. var minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5); // We always get maximum sum if we replace // 5 with 6. var maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6); document.write("Minimum sum = " + minSum); document.write("<br>Maximum sum = " + maxSum);} // Driver codevar x1 = 5466, x2 = 4555;calculateMinMaxSum(x1, x2); // This code contributed by shikhasingrajput </script> Output : Minimum sum = 10010 Maximum sum = 11132 This article is contributed by Roshni Agarwal. 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. nitin mittal Mithun Kumar shubhamkumarsahu shikhasingrajput number-digits Mathematical Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Program to find GCD or HCF of two numbers Prime Numbers Modulo Operator (%) in C/C++ with Examples Sieve of Eratosthenes Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 24945, "s": 24917, "text": "\n05 May, 2021" }, { "code": null, "e": 25147, "s": 24945, "text": "Given two positive numbers calculate the minimum and maximum possible sums of two numbers. We are allowed to replace digit 5 with digit 6 and vice versa in either or both the given numbers.Examples : " }, { "code": null, "e": 25334, "s": 25147, "text": "Input : x1 = 645 x2 = 666\nOutput : Minimum Sum: 1100 (545 + 555)\n Maximum Sum: 1312 (646 + 666)\n\nInput: x1 = 5466 x2 = 4555\nOutput: Minimum sum: 10010\n Maximum Sum: 11132" }, { "code": null, "e": 25546, "s": 25336, "text": "Since both numbers are positive, we always get maximum sum if replace 5 with 6 in both numbers. And we get a minimum sum if we replace 6 with 5 in both numbers. Below is C++ implementation based on this fact. " }, { "code": null, "e": 25550, "s": 25546, "text": "C++" }, { "code": null, "e": 25555, "s": 25550, "text": "Java" }, { "code": null, "e": 25563, "s": 25555, "text": "Python3" }, { "code": null, "e": 25566, "s": 25563, "text": "C#" }, { "code": null, "e": 25570, "s": 25566, "text": "PHP" }, { "code": null, "e": 25581, "s": 25570, "text": "Javascript" }, { "code": "// C++ program to find maximum and minimum// possible sums of two numbers that we can// get if replacing digit from 5 to 6 and vice// versa are allowed.#include<bits/stdc++.h>using namespace std; // Find new value of x after replacing digit// \"from\" to \"to\"int replaceDig(int x, int from, int to){ int result = 0; int multiply = 1; while (x > 0) { int reminder = x % 10; // Required digit found, replace it if (reminder == from) result = result + to * multiply; else result = result + reminder * multiply; multiply *= 10; x = x / 10; } return result;} // Returns maximum and minimum possible sums of// x1 and x2 if digit replacements are allowed.void calculateMinMaxSum(int x1, int x2){ // We always get minimum sum if we replace // 6 with 5. int minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5); // We always get maximum sum if we replace // 5 with 6. int maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6); cout << \"Minimum sum = \" << minSum; cout << \"nMaximum sum = \" << maxSum;} // Driver codeint main(){ int x1 = 5466, x2 = 4555; calculateMinMaxSum(x1, x2); return 0;}", "e": 26813, "s": 25581, "text": null }, { "code": "// Java program to find maximum and minimum// possible sums of two numbers that we can// get if replacing digit from 5 to 6 and vice// versa are allowed.class GFG { // Find new value of x after replacing digit // \"from\" to \"to\" static int replaceDig(int x, int from, int to) { int result = 0; int multiply = 1; while (x > 0) { int reminder = x % 10; // Required digit found, replace it if (reminder == from) result = result + to * multiply; else result = result + reminder * multiply; multiply *= 10; x = x / 10; } return result; } // Returns maximum and minimum possible sums of // x1 and x2 if digit replacements are allowed. static void calculateMinMaxSum(int x1, int x2) { // We always get minimum sum if we replace // 6 with 5. int minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5); // We always get maximum sum if we replace // 5 with 6. int maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6); System.out.print(\"Minimum sum = \" + minSum); System.out.print(\"\\nMaximum sum = \" + maxSum); } // Driver code public static void main (String[] args) { int x1 = 5466, x2 = 4555; calculateMinMaxSum(x1, x2); }} // This code is contributed by Anant Agarwal.", "e": 28319, "s": 26813, "text": null }, { "code": "# Python3 program to find maximum# and minimum possible sums of# two numbers that we can get if# replacing digit from 5 to 6# and vice versa are allowed. # Find new value of x after# replacing digit \"from\" to \"to\"def replaceDig(x, from1, to): result = 0 multiply = 1 while (x > 0): reminder = x % 10 # Required digit found, # replace it if (reminder == from1): result = result + to * multiply else: result = result + reminder * multiply multiply *= 10 x = int(x / 10) return result # Returns maximum and minimum# possible sums of x1 and x2# if digit replacements are allowed.def calculateMinMaxSum(x1, x2): # We always get minimum sum # if we replace 6 with 5. minSum = replaceDig(x1, 6, 5) +replaceDig(x2, 6, 5) # We always get maximum sum # if we replace 5 with 6. maxSum = replaceDig(x1, 5, 6) +replaceDig(x2, 5, 6) print(\"Minimum sum =\" , minSum) print(\"Maximum sum =\" , maxSum,end=\" \") # Driver codeif __name__=='__main__': x1 = 5466 x2 = 4555 calculateMinMaxSum(x1, x2) # This code is contributed# by mits", "e": 29458, "s": 28319, "text": null }, { "code": "// C# program to find maximum and minimum// possible sums of two numbers that we can// get if replacing digit from 5 to 6 and vice// versa are allowed.using System; class GFG { // Find new value of x after // replacing digit \"from\" to \"to\" static int replaceDig(int x, int from, int to) { int result = 0; int multiply = 1; while (x > 0) { int reminder = x % 10; // Required digit found, // replace it if (reminder == from) result = result + to * multiply; else result = result + reminder * multiply; multiply *= 10; x = x / 10; } return result; } // Returns maximum and minimum // possible sums of x1 and x2 // if digit replacements are allowed. static void calculateMinMaxSum(int x1, int x2) { // We always get minimum sum if // we replace 6 with 5. int minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5); // We always get maximum sum if // we replace 5 with 6. int maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6); Console.Write(\"Minimum sum = \" + minSum); Console.Write(\"\\nMaximum sum = \" + maxSum); } // Driver code public static void Main () { int x1 = 5466, x2 = 4555; calculateMinMaxSum(x1, x2); }} // This code is contributed by Nitin Mittal.", "e": 31003, "s": 29458, "text": null }, { "code": "<?php// PHP program to find maximum// and minimum possible sums of// two numbers that we can get if// replacing digit from 5 to 6// and vice versa are allowed. // Find new value of x after// replacing digit \"from\" to \"to\"function replaceDig($x, $from, $to){ $result = 0; $multiply = 1; while ($x > 0) { $reminder = $x % 10; // Required digit found, // replace it if ($reminder == $from) $result = $result + $to * $multiply; else $result = $result + $reminder * $multiply; $multiply *= 10; $x = $x / 10; } return $result;} // Returns maximum and minimum// possible sums of x1 and x2// if digit replacements are allowed.function calculateMinMaxSum($x1, $x2){ // We always get minimum sum // if we replace 6 with 5.$minSum = replaceDig($x1, 6, 5) + replaceDig($x2, 6, 5); // We always get maximum sum // if we replace 5 with 6. $maxSum = replaceDig($x1, 5, 6) + replaceDig($x2, 5, 6); echo \"Minimum sum = \" , $minSum,\"\\n\"; echo \"Maximum sum = \" , $maxSum;} // Driver code$x1 = 5466; $x2 = 4555;calculateMinMaxSum($x1, $x2); // This code is contributed// by nitin mittal.?>", "e": 32281, "s": 31003, "text": null }, { "code": "<script> // Javascript program to find maximum and minimum// possible sums of two numbers that we can// get if replacing digit from 5 to 6 and vice// versa are allowed. // Find new value of x after replacing digit// \"from\" to \"to\"function replaceDig(x , from , to){ var result = 0; var multiply = 1; while (x > 0) { var reminder = x % 10; // Required digit found, replace it if (reminder == from) result = result + to * multiply; else result = result + reminder * multiply; multiply *= 10; x = parseInt(x / 10); } return result;} // Returns maximum and minimum possible sums of// x1 and x2 if digit replacements are allowed.function calculateMinMaxSum(x1 , x2){ // We always get minimum sum if we replace // 6 with 5. var minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5); // We always get maximum sum if we replace // 5 with 6. var maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6); document.write(\"Minimum sum = \" + minSum); document.write(\"<br>Maximum sum = \" + maxSum);} // Driver codevar x1 = 5466, x2 = 4555;calculateMinMaxSum(x1, x2); // This code contributed by shikhasingrajput </script>", "e": 33540, "s": 32281, "text": null }, { "code": null, "e": 33551, "s": 33540, "text": "Output : " }, { "code": null, "e": 33591, "s": 33551, "text": "Minimum sum = 10010\nMaximum sum = 11132" }, { "code": null, "e": 34014, "s": 33591, "text": "This article is contributed by Roshni Agarwal. 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": 34027, "s": 34014, "text": "nitin mittal" }, { "code": null, "e": 34040, "s": 34027, "text": "Mithun Kumar" }, { "code": null, "e": 34057, "s": 34040, "text": "shubhamkumarsahu" }, { "code": null, "e": 34074, "s": 34057, "text": "shikhasingrajput" }, { "code": null, "e": 34088, "s": 34074, "text": "number-digits" }, { "code": null, "e": 34101, "s": 34088, "text": "Mathematical" }, { "code": null, "e": 34109, "s": 34101, "text": "Strings" }, { "code": null, "e": 34117, "s": 34109, "text": "Strings" }, { "code": null, "e": 34130, "s": 34117, "text": "Mathematical" }, { "code": null, "e": 34228, "s": 34130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34237, "s": 34228, "text": "Comments" }, { "code": null, "e": 34250, "s": 34237, "text": "Old Comments" }, { "code": null, "e": 34274, "s": 34250, "text": "Merge two sorted arrays" }, { "code": null, "e": 34316, "s": 34274, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 34330, "s": 34316, "text": "Prime Numbers" }, { "code": null, "e": 34373, "s": 34330, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 34395, "s": 34373, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 34420, "s": 34395, "text": "Reverse a string in Java" }, { "code": null, "e": 34466, "s": 34420, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34500, "s": 34466, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 34557, "s": 34500, "text": "Python program to check if a string is palindrome or not" } ]
How to create Hover animations on Button ?
05 Mar, 2021 In this project, we are going to create animated buttons using HTML and CSS. In these buttons when we hover over them an emoji get displayed on them for better UX. Glimpse of the Buttons: CDN Link: For button icons, we will use the fontawesome CDN link. Place this link in the script tag. https://kit.fontawesome.com/704ff50790.js HTML: Create an HTML file, then create the structure of all the buttons that will be a hover effect(switch to icon). Create a div container inside that container place all the buttons. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div class="container"> <div class="button-effect"> <h2>Animated Buttons on Hover</h2> <a class="effect effect-4" href="#" title="Confirm Delivery"> Confirm Delivery </a> <a class="effect effect-3" href="#" title="Download">Download</a> <a class="effect effect-2" href="#" title="Upload">Upload</a> <a class="effect effect-1" href="#" title="Delete">Delete</a> <a class="effect effect-5" href="#" title="Click Here to Message"> Message </a> </div> </div> <script src="https://kit.fontawesome.com/704ff50790.js" crossorigin="anonymous"> </script> </body></html> CSS: It is used to give different types of animations and effects to our HTML page so that it looks interactive to all users. Restore all the browser effects. Use classes and ids to give effects to HTML elements. Use @keyframes{} for giving the animation to HTML elements. Use of nth-child selector feature of CSS to call different links. CSS <style> body { background-color: black; } body .container { width: 850px; margin: 70px auto 0px auto; text-align: center; } body .container .button-effect { padding: 30px 0px; } body .container .button-effect h2 { font-family: "Droid Serif", serif; font-size: 20px; color: #fff; margin-bottom: 40px; } body .container .button-effect a { margin-right: 17px; } body .container .button-effect a:nth-child(2) { background-color: #520a8d; } body .container .button-effect a:nth-child(3) { background-color: #4d0325; } body .container .button-effect a:nth-child(4) { background-color: #09858a; } body .container .button-effect a:nth-child(5) { background-color: #e60d2a; } body .container .button-effect a:nth-child(6) { background-color: #c45f0d; } body .container .button-effect a:last-child { margin-right: 0px; } .effect { text-align: center; display: inline-block; position: relative; text-decoration: none; color: #fff; text-transform: capitalize; /* background-color: - add your own background-color */ font-family: "Roboto", sans-serif; /* put your font-family */ font-size: 18px; padding: 20px 0px; width: 150px; border-radius: 6px; overflow: hidden; } /* effect-4 styles */ .effect.effect-4 { transition: all 0.2s linear 0s; } .effect.effect-4:before { content: "\f0d1"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-4:hover { text-indent: -9999px; } .effect.effect-4:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-3 { transition: all 0.2s linear 0s; } .effect.effect-3:before { content: "\f019"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-3:hover { text-indent: -9999px; } .effect.effect-3:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-2 { transition: all 0.2s linear 0s; } .effect.effect-2:before { content: "\f093"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-2:hover { text-indent: -9999px; } .effect.effect-2:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-1 { transition: all 0.2s linear 0s; } .effect.effect-1:before { content: "\f2ed"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-1:hover { text-indent: -9999px; } .effect.effect-1:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-5 { transition: all 0.2s linear 0s; } .effect.effect-5:before { content: "\f1d8"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-5:hover { text-indent: -9999px; } .effect.effect-5:hover:before { transform: scale(1, 1); text-indent: 0; } </style> Complete Solution: In this section, we will put the above sections together and create attractive Hover animated buttons. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> body { background-color: black; } body .container { width: 850px; margin: 70px auto 0px auto; text-align: center; } body .container .button-effect { padding: 30px 0px; } body .container .button-effect h2 { font-family: "Droid Serif", serif; font-size: 20px; color: #fff; margin-bottom: 40px; } body .container .button-effect a { margin-right: 17px; } body .container .button-effect a:nth-child(2) { background-color: #520a8d; } body .container .button-effect a:nth-child(3) { background-color: #4d0325; } body .container .button-effect a:nth-child(4) { background-color: #09858a; } body .container .button-effect a:nth-child(5) { background-color: #e60d2a; } body .container .button-effect a:nth-child(6) { background-color: #c45f0d; } body .container .button-effect a:last-child { margin-right: 0px; } .effect { text-align: center; display: inline-block; position: relative; text-decoration: none; color: #fff; text-transform: capitalize; /* background-color: - add your own background-color */ font-family: "Roboto", sans-serif; /* put your font-family */ font-size: 18px; padding: 20px 0px; width: 150px; border-radius: 6px; overflow: hidden; } /* effect-4 styles */ .effect.effect-4 { transition: all 0.2s linear 0s; } .effect.effect-4:before { content: "\f0d1"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-4:hover { text-indent: -9999px; } .effect.effect-4:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-3 { transition: all 0.2s linear 0s; } .effect.effect-3:before { content: "\f019"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-3:hover { text-indent: -9999px; } .effect.effect-3:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-2 { transition: all 0.2s linear 0s; } .effect.effect-2:before { content: "\f093"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-2:hover { text-indent: -9999px; } .effect.effect-2:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-1 { transition: all 0.2s linear 0s; } .effect.effect-1:before { content: "\f2ed"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-1:hover { text-indent: -9999px; } .effect.effect-1:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-5 { transition: all 0.2s linear 0s; } .effect.effect-5:before { content: "\f1d8"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-5:hover { text-indent: -9999px; } .effect.effect-5:hover:before { transform: scale(1, 1); text-indent: 0; } </style> </head> <body> <div class="container"> <div class="button-effect"> <h2>Animated Buttons on Hover</h2> <a class="effect effect-4" href="#" title="Confirm Delivery"> Confirm Delivery </a> <a class="effect effect-3" href="#" title="Download">Download</a> <a class="effect effect-2" href="#" title="Upload">Upload</a> <a class="effect effect-1" href="#" title="Delete">Delete</a> <a class="effect effect-5" href="#" title="Click Here to Message"> Message </a> </div> </div> <script src="https://kit.fontawesome.com/704ff50790.js" crossorigin="anonymous"></script> </body></html> Output: CSS-Properties CSS-Questions CSS-Selectors Technical Scripter 2020 CSS HTML Technical Scripter HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Mar, 2021" }, { "code": null, "e": 192, "s": 28, "text": "In this project, we are going to create animated buttons using HTML and CSS. In these buttons when we hover over them an emoji get displayed on them for better UX." }, { "code": null, "e": 216, "s": 192, "text": "Glimpse of the Buttons:" }, { "code": null, "e": 317, "s": 216, "text": "CDN Link: For button icons, we will use the fontawesome CDN link. Place this link in the script tag." }, { "code": null, "e": 359, "s": 317, "text": "https://kit.fontawesome.com/704ff50790.js" }, { "code": null, "e": 544, "s": 359, "text": "HTML: Create an HTML file, then create the structure of all the buttons that will be a hover effect(switch to icon). Create a div container inside that container place all the buttons." }, { "code": null, "e": 549, "s": 544, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> </head> <body> <div class=\"container\"> <div class=\"button-effect\"> <h2>Animated Buttons on Hover</h2> <a class=\"effect effect-4\" href=\"#\" title=\"Confirm Delivery\"> Confirm Delivery </a> <a class=\"effect effect-3\" href=\"#\" title=\"Download\">Download</a> <a class=\"effect effect-2\" href=\"#\" title=\"Upload\">Upload</a> <a class=\"effect effect-1\" href=\"#\" title=\"Delete\">Delete</a> <a class=\"effect effect-5\" href=\"#\" title=\"Click Here to Message\"> Message </a> </div> </div> <script src=\"https://kit.fontawesome.com/704ff50790.js\" crossorigin=\"anonymous\"> </script> </body></html>", "e": 1446, "s": 549, "text": null }, { "code": null, "e": 1575, "s": 1446, "text": "CSS: It is used to give different types of animations and effects to our HTML page so that it looks interactive to all users. " }, { "code": null, "e": 1608, "s": 1575, "text": "Restore all the browser effects." }, { "code": null, "e": 1662, "s": 1608, "text": "Use classes and ids to give effects to HTML elements." }, { "code": null, "e": 1722, "s": 1662, "text": "Use @keyframes{} for giving the animation to HTML elements." }, { "code": null, "e": 1788, "s": 1722, "text": "Use of nth-child selector feature of CSS to call different links." }, { "code": null, "e": 1792, "s": 1788, "text": "CSS" }, { "code": "<style> body { background-color: black; } body .container { width: 850px; margin: 70px auto 0px auto; text-align: center; } body .container .button-effect { padding: 30px 0px; } body .container .button-effect h2 { font-family: \"Droid Serif\", serif; font-size: 20px; color: #fff; margin-bottom: 40px; } body .container .button-effect a { margin-right: 17px; } body .container .button-effect a:nth-child(2) { background-color: #520a8d; } body .container .button-effect a:nth-child(3) { background-color: #4d0325; } body .container .button-effect a:nth-child(4) { background-color: #09858a; } body .container .button-effect a:nth-child(5) { background-color: #e60d2a; } body .container .button-effect a:nth-child(6) { background-color: #c45f0d; } body .container .button-effect a:last-child { margin-right: 0px; } .effect { text-align: center; display: inline-block; position: relative; text-decoration: none; color: #fff; text-transform: capitalize; /* background-color: - add your own background-color */ font-family: \"Roboto\", sans-serif; /* put your font-family */ font-size: 18px; padding: 20px 0px; width: 150px; border-radius: 6px; overflow: hidden; } /* effect-4 styles */ .effect.effect-4 { transition: all 0.2s linear 0s; } .effect.effect-4:before { content: \"\\f0d1\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-4:hover { text-indent: -9999px; } .effect.effect-4:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-3 { transition: all 0.2s linear 0s; } .effect.effect-3:before { content: \"\\f019\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-3:hover { text-indent: -9999px; } .effect.effect-3:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-2 { transition: all 0.2s linear 0s; } .effect.effect-2:before { content: \"\\f093\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-2:hover { text-indent: -9999px; } .effect.effect-2:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-1 { transition: all 0.2s linear 0s; } .effect.effect-1:before { content: \"\\f2ed\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-1:hover { text-indent: -9999px; } .effect.effect-1:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-5 { transition: all 0.2s linear 0s; } .effect.effect-5:before { content: \"\\f1d8\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-5:hover { text-indent: -9999px; } .effect.effect-5:hover:before { transform: scale(1, 1); text-indent: 0; } </style>", "e": 6499, "s": 1792, "text": null }, { "code": null, "e": 6621, "s": 6499, "text": "Complete Solution: In this section, we will put the above sections together and create attractive Hover animated buttons." }, { "code": null, "e": 6626, "s": 6621, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <style> body { background-color: black; } body .container { width: 850px; margin: 70px auto 0px auto; text-align: center; } body .container .button-effect { padding: 30px 0px; } body .container .button-effect h2 { font-family: \"Droid Serif\", serif; font-size: 20px; color: #fff; margin-bottom: 40px; } body .container .button-effect a { margin-right: 17px; } body .container .button-effect a:nth-child(2) { background-color: #520a8d; } body .container .button-effect a:nth-child(3) { background-color: #4d0325; } body .container .button-effect a:nth-child(4) { background-color: #09858a; } body .container .button-effect a:nth-child(5) { background-color: #e60d2a; } body .container .button-effect a:nth-child(6) { background-color: #c45f0d; } body .container .button-effect a:last-child { margin-right: 0px; } .effect { text-align: center; display: inline-block; position: relative; text-decoration: none; color: #fff; text-transform: capitalize; /* background-color: - add your own background-color */ font-family: \"Roboto\", sans-serif; /* put your font-family */ font-size: 18px; padding: 20px 0px; width: 150px; border-radius: 6px; overflow: hidden; } /* effect-4 styles */ .effect.effect-4 { transition: all 0.2s linear 0s; } .effect.effect-4:before { content: \"\\f0d1\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-4:hover { text-indent: -9999px; } .effect.effect-4:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-3 { transition: all 0.2s linear 0s; } .effect.effect-3:before { content: \"\\f019\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-3:hover { text-indent: -9999px; } .effect.effect-3:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-2 { transition: all 0.2s linear 0s; } .effect.effect-2:before { content: \"\\f093\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-2:hover { text-indent: -9999px; } .effect.effect-2:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-1 { transition: all 0.2s linear 0s; } .effect.effect-1:before { content: \"\\f2ed\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-1:hover { text-indent: -9999px; } .effect.effect-1:hover:before { transform: scale(1, 1); text-indent: 0; } .effect.effect-5 { transition: all 0.2s linear 0s; } .effect.effect-5:before { content: \"\\f1d8\"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0px; width: 100%; height: 100%; text-align: center; font-size: 30px; transform: scale(0, 1); transition: all 0.2s linear 0s; } .effect.effect-5:hover { text-indent: -9999px; } .effect.effect-5:hover:before { transform: scale(1, 1); text-indent: 0; } </style> </head> <body> <div class=\"container\"> <div class=\"button-effect\"> <h2>Animated Buttons on Hover</h2> <a class=\"effect effect-4\" href=\"#\" title=\"Confirm Delivery\"> Confirm Delivery </a> <a class=\"effect effect-3\" href=\"#\" title=\"Download\">Download</a> <a class=\"effect effect-2\" href=\"#\" title=\"Upload\">Upload</a> <a class=\"effect effect-1\" href=\"#\" title=\"Delete\">Delete</a> <a class=\"effect effect-5\" href=\"#\" title=\"Click Here to Message\"> Message </a> </div> </div> <script src=\"https://kit.fontawesome.com/704ff50790.js\" crossorigin=\"anonymous\"></script> </body></html>", "e": 12229, "s": 6626, "text": null }, { "code": null, "e": 12239, "s": 12229, "text": " Output: " }, { "code": null, "e": 12254, "s": 12239, "text": "CSS-Properties" }, { "code": null, "e": 12268, "s": 12254, "text": "CSS-Questions" }, { "code": null, "e": 12282, "s": 12268, "text": "CSS-Selectors" }, { "code": null, "e": 12306, "s": 12282, "text": "Technical Scripter 2020" }, { "code": null, "e": 12310, "s": 12306, "text": "CSS" }, { "code": null, "e": 12315, "s": 12310, "text": "HTML" }, { "code": null, "e": 12334, "s": 12315, "text": "Technical Scripter" }, { "code": null, "e": 12339, "s": 12334, "text": "HTML" } ]
Program to Convert Milliseconds to a Date Format in Java
07 Dec, 2021 Given milliseconds. The task is to write a program in Java to convert Milliseconds to a Date which Displays the date in dd MMM yyyy HH:mm:ss:SSS Z format.The Date class in Java internally stores Date in milliseconds. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and the Date class provides a constructor which can be used to create Date from milliseconds.The SimpleDateFormat class helps in formatting and parsing of data. We can change the date from one format to other. It allows the user to interpret string date format into a Date object. We can modify Date accordingly.Constructors of SimpleDateFormat: SimpleDateFormat(String pattern_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the default FORMAT locale. SimpleDateFormat(String pattern_arg, Locale locale_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the given FORMAT Locale – locale_arg. SimpleDateFormat(String pattern_arg, DateFormatSymbols formatSymbols) : Constructs a SimpleDateFormat using the given pattern – pattern_arg and date format symbols. Below is the program to convert milliseconds to a Date Format in Java: Java // Java program to convert milliseconds// to a Date format import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date; public class SectoDate { public static void main(String args[]) { // milliseconds long milliSec = 3010; // Creating date format DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z"); // Creating date from milliseconds // using Date() constructor Date result = new Date(milliSec); // Formatting Date according to the // given format System.out.println(simple.format(result)); }} 01 Jan 1970 00:00:03:010 +0000 adnanirshad158 date-time-program Java - util package Java-Date-Time Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Dec, 2021" }, { "code": null, "e": 678, "s": 28, "text": "Given milliseconds. The task is to write a program in Java to convert Milliseconds to a Date which Displays the date in dd MMM yyyy HH:mm:ss:SSS Z format.The Date class in Java internally stores Date in milliseconds. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and the Date class provides a constructor which can be used to create Date from milliseconds.The SimpleDateFormat class helps in formatting and parsing of data. We can change the date from one format to other. It allows the user to interpret string date format into a Date object. We can modify Date accordingly.Constructors of SimpleDateFormat: " }, { "code": null, "e": 847, "s": 678, "text": "SimpleDateFormat(String pattern_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the default FORMAT locale." }, { "code": null, "e": 1046, "s": 847, "text": "SimpleDateFormat(String pattern_arg, Locale locale_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the given FORMAT Locale – locale_arg." }, { "code": null, "e": 1211, "s": 1046, "text": "SimpleDateFormat(String pattern_arg, DateFormatSymbols formatSymbols) : Constructs a SimpleDateFormat using the given pattern – pattern_arg and date format symbols." }, { "code": null, "e": 1284, "s": 1211, "text": "Below is the program to convert milliseconds to a Date Format in Java: " }, { "code": null, "e": 1289, "s": 1284, "text": "Java" }, { "code": "// Java program to convert milliseconds// to a Date format import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date; public class SectoDate { public static void main(String args[]) { // milliseconds long milliSec = 3010; // Creating date format DateFormat simple = new SimpleDateFormat(\"dd MMM yyyy HH:mm:ss:SSS Z\"); // Creating date from milliseconds // using Date() constructor Date result = new Date(milliSec); // Formatting Date according to the // given format System.out.println(simple.format(result)); }}", "e": 1911, "s": 1289, "text": null }, { "code": null, "e": 1942, "s": 1911, "text": "01 Jan 1970 00:00:03:010 +0000" }, { "code": null, "e": 1959, "s": 1944, "text": "adnanirshad158" }, { "code": null, "e": 1977, "s": 1959, "text": "date-time-program" }, { "code": null, "e": 1997, "s": 1977, "text": "Java - util package" }, { "code": null, "e": 2012, "s": 1997, "text": "Java-Date-Time" }, { "code": null, "e": 2017, "s": 2012, "text": "Java" }, { "code": null, "e": 2022, "s": 2017, "text": "Java" } ]
Minimum steps to make all the elements of the array divisible by 4
27 Oct, 2021 Given an array of size n, the task is to find the minimum number of steps required to make all the elements of the array divisible by 4. A step is defined as removal of any two elements from the array and adding the sum of these elements to the array. Examples: Input: array = {1, 2, 3, 1, 2, 3, 8} Output: 3 Explanation: As we can see in the image, combining array[0] and array[2] makes it 4. Similarly for array[1] and array[4] as well as array[3] and array[5]. array[6] is already divisible by 4. So by doing 3 steps, all the elements in the array become divisible by 4.Input: array = {12, 31, 47, 32, 93, 24, 61, 29, 21, 34} Output: 4 Approach: The idea here is to convert all the elements in the array to modulus 4. First, sum of all the elements of the array should be divisible by 4. If not, this task is not possible. Initialize an array modulus with size 4 to 0. Initialize a counter count to 0 to keep track of number of steps done. Traverse through the input array and take modulus 4 of each element. Increment the value of the mod 4 value in the modulus array by 1. modulus[0] is the count of elements that are already divisible by 4. So no need to pair them with any other element. modulus[1] and modulus[3] elements can be combined to get a number divisible by 4. So, increment count to the minimum value of the both. Every 2 elements of modulus[2] can be combined to get an element divisible to 4. For the remaining elements, increment value modulus[2] by half of modulus[1] and modulus[3]. Now, increment count by half modulus[2]. We take half because every two elements are combined as one. The final value of count is the number of steps required to convert the all the elements of the input array divisible by 4. Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; int getSteps(int arr[], int n){ // Count to keep track of the // number of steps done. int count = 0; // Modulus array to store all elements mod 4 int modulus[4] = { 0 }; // sum to check if given task is possible int sum = 0; // Loop to store all elements mod 4 // and calculate sum; int i; for (i = 0; i < n; i++) { int mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, // not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] / 2; modulus[2] += modulus[3] / 2; // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += modulus[1] / 2; count += modulus[3] / 2; // increment count by half of modulus[2] count += modulus[2] / 2; return count; }} // Driver Codeint main(){ // size of array int n = 7; // input array int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int count = getSteps(arr, n); cout << count;} // This code is contributed// by Akanksha Rai #include <stdio.h>#include <string.h> int getSteps(int arr[], int n){ // Count to keep track of the number of steps done. int count = 0; // Modulus array to store all elements mod 4 int modulus[4] = { 0 }; // sum to check if given task is possible int sum = 0; // Loop to store all elements mod 4 and calculate sum; int i; for (i = 0; i < n; i++) { int mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] / 2; modulus[2] += modulus[3] / 2; // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += modulus[1] / 2; count += modulus[3] / 2; // increment count by half of modulus[2] count += modulus[2] / 2; return count; }} // Driver Codeint main(){ // size of array int n = 7; // input array int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int count = getSteps(arr, n); printf("%d", count);} // Java program for the above approachclass GFG{ static int getSteps(int arr[], int n){ // Count to keep track of the number of steps done. int count = 0; // Modulus array to store all elements mod 4 int modulus[] = new int[4]; // sum to check if given task is possible int sum = 0; // Loop to store all elements // mod 4 and calculate sum; int i; for (i = 0; i < n; i++) { int mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] / 2; modulus[2] += modulus[3] / 2; // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += modulus[1] / 2; count += modulus[3] / 2; // increment count by half of modulus[2] count += modulus[2] / 2; return count; }} // Driver Codepublic static void main(String[] args){ // size of array int n = 7; // input array int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int count = getSteps(arr, n); System.out.printf("%d", count);}} // This code has been contributed by 29AjayKumar # Python 3 program for the above approachdef getSteps(arr, n): # Count to keep track of the # number of steps done. count = 0 # Modulus array to store all elements mod 4 modulus = [0 for i in range(4)] # Sum to check if given task is possible Sum = 0 # Loop to store all elements mod 4 # and calculate Sum i = 0 for i in range(n): mod = arr[i] % 4 Sum += mod modulus[mod] += 1 # If Sum is not divisible by 4, # not possible if (Sum % 4 != 0): return -1 else: # Find minimum of modulus[1] and modulus[3] # and increment the count by the minimum if (modulus[1] > modulus[3]): count += modulus[3] else: count += modulus[1] # Update the values in modulus array. modulus[1] -= count modulus[3] -= count # Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] // 2 modulus[2] += modulus[3] // 2 # increment count to half of remaining # modulus[1] or modulus of [3] elements. count += modulus[1] // 2 count += modulus[3] // 2 # increment count by half of modulus[2] count += modulus[2] // 2 return count # Driver Code # size of arrayn = 7 # input arrayarr = [1, 2, 3, 1, 2, 3, 8] count = getSteps(arr, n)print(count) # This code is contributed by mohit kumar // C# program for the above approachusing System; class GFG{ static int getSteps(int []arr, int n){ // Count to keep track of the number of steps done. int count = 0; // Modulus array to store all elements mod 4 int []modulus = new int[4]; // sum to check if given task is possible int sum = 0; // Loop to store all elements // mod 4 and calculate sum; int i; for (i = 0; i < n; i++) { int mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] / 2; modulus[2] += modulus[3] / 2; // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += modulus[1] / 2; count += modulus[3] / 2; // increment count by half of modulus[2] count += modulus[2] / 2; return count; }} // Driver Codepublic static void Main(String[] args){ // size of array int n = 7; // input array int []arr = { 1, 2, 3, 1, 2, 3, 8 }; int count = getSteps(arr, n); Console.Write("{0}", count);}} // This code contributed by Rajput-Ji <?php// PHP program for the above approach function getSteps($arr, $n){ // Count to keep track of the number // of steps done. $count = 0; // Modulus array to store all elements mod 4 $modulus = array_fill(0, 4, 0); // sum to check if given task is possible $sum = 0; // Loop to store all elements // mod 4 and calculate sum; for ($i = 0; $i < $n; $i++) { $mod = $arr[$i] % 4; $sum += $mod; $modulus[$mod]++; } // If sum is not divisible by 4, not possible if ($sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if ($modulus[1] > $modulus[3]) { $count += $modulus[3]; } else { $count += $modulus[1]; } // Update the values in modulus array. $modulus[1] -= $count; $modulus[3] -= $count; // Use modulus[2] to pair remaining elements. $modulus[2] += (int)($modulus[1] / 2); $modulus[2] += (int)($modulus[3] / 2); // increment count to half of remaining // modulus[1] or modulus of [3] elements. $count += (int)($modulus[1] / 2); $count += (int)($modulus[3] / 2); // increment count by half of modulus[2] $count += (int)($modulus[2] / 2); return $count; }} // Driver Code // size of array$n = 7; // input array$arr = array( 1, 2, 3, 1, 2, 3, 8 ); $count = getSteps($arr, $n);print($count); // This code contributed by mits?> <script> function getSteps(arr, n) { // Count to keep track of the // number of steps done. let count = 0; // Modulus array to store all elements mod 4 let modulus = new Array(4); modulus.fill(0); // sum to check if given task is possible let sum = 0; // Loop to store all elements mod 4 // and calculate sum; let i; for (i = 0; i < n; i++) { let mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, // not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += parseInt(modulus[1] / 2, 10); modulus[2] += parseInt(modulus[3] / 2, 10); // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += parseInt(modulus[1] / 2, 10); count += parseInt(modulus[3] / 2, 10); // increment count by half of modulus[2] count += parseInt(modulus[2] / 2, 10); return count; } } // size of array let n = 7; // input array let arr = [ 1, 2, 3, 1, 2, 3, 8 ]; let count = getSteps(arr, n); document.write(count); // This code is contributed by divyeshrabadiya07.</script> 3 mohit kumar 29 29AjayKumar Rajput-Ji Mithun Kumar Akanksha_Rai nidhi_biet divyeshrabadiya07 akshaysingh98088 Number Divisibility Arrays Competitive Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Oct, 2021" }, { "code": null, "e": 316, "s": 52, "text": "Given an array of size n, the task is to find the minimum number of steps required to make all the elements of the array divisible by 4. A step is defined as removal of any two elements from the array and adding the sum of these elements to the array. Examples: " }, { "code": null, "e": 378, "s": 316, "text": "Input: array = {1, 2, 3, 1, 2, 3, 8} Output: 3 Explanation: " }, { "code": null, "e": 697, "s": 378, "text": "As we can see in the image, combining array[0] and array[2] makes it 4. Similarly for array[1] and array[4] as well as array[3] and array[5]. array[6] is already divisible by 4. So by doing 3 steps, all the elements in the array become divisible by 4.Input: array = {12, 31, 47, 32, 93, 24, 61, 29, 21, 34} Output: 4 " }, { "code": null, "e": 888, "s": 699, "text": "Approach: The idea here is to convert all the elements in the array to modulus 4. First, sum of all the elements of the array should be divisible by 4. If not, this task is not possible. " }, { "code": null, "e": 935, "s": 888, "text": "Initialize an array modulus with size 4 to 0. " }, { "code": null, "e": 1007, "s": 935, "text": "Initialize a counter count to 0 to keep track of number of steps done. " }, { "code": null, "e": 1077, "s": 1007, "text": "Traverse through the input array and take modulus 4 of each element. " }, { "code": null, "e": 1144, "s": 1077, "text": "Increment the value of the mod 4 value in the modulus array by 1. " }, { "code": null, "e": 1262, "s": 1144, "text": "modulus[0] is the count of elements that are already divisible by 4. So no need to pair them with any other element. " }, { "code": null, "e": 1400, "s": 1262, "text": "modulus[1] and modulus[3] elements can be combined to get a number divisible by 4. So, increment count to the minimum value of the both. " }, { "code": null, "e": 1482, "s": 1400, "text": "Every 2 elements of modulus[2] can be combined to get an element divisible to 4. " }, { "code": null, "e": 1576, "s": 1482, "text": "For the remaining elements, increment value modulus[2] by half of modulus[1] and modulus[3]. " }, { "code": null, "e": 1679, "s": 1576, "text": "Now, increment count by half modulus[2]. We take half because every two elements are combined as one. " }, { "code": null, "e": 1804, "s": 1679, "text": "The final value of count is the number of steps required to convert the all the elements of the input array divisible by 4. " }, { "code": null, "e": 1857, "s": 1804, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1861, "s": 1857, "text": "C++" }, { "code": null, "e": 1863, "s": 1861, "text": "C" }, { "code": null, "e": 1868, "s": 1863, "text": "Java" }, { "code": null, "e": 1876, "s": 1868, "text": "Python3" }, { "code": null, "e": 1879, "s": 1876, "text": "C#" }, { "code": null, "e": 1883, "s": 1879, "text": "PHP" }, { "code": null, "e": 1894, "s": 1883, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int getSteps(int arr[], int n){ // Count to keep track of the // number of steps done. int count = 0; // Modulus array to store all elements mod 4 int modulus[4] = { 0 }; // sum to check if given task is possible int sum = 0; // Loop to store all elements mod 4 // and calculate sum; int i; for (i = 0; i < n; i++) { int mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, // not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] / 2; modulus[2] += modulus[3] / 2; // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += modulus[1] / 2; count += modulus[3] / 2; // increment count by half of modulus[2] count += modulus[2] / 2; return count; }} // Driver Codeint main(){ // size of array int n = 7; // input array int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int count = getSteps(arr, n); cout << count;} // This code is contributed// by Akanksha Rai", "e": 3471, "s": 1894, "text": null }, { "code": "#include <stdio.h>#include <string.h> int getSteps(int arr[], int n){ // Count to keep track of the number of steps done. int count = 0; // Modulus array to store all elements mod 4 int modulus[4] = { 0 }; // sum to check if given task is possible int sum = 0; // Loop to store all elements mod 4 and calculate sum; int i; for (i = 0; i < n; i++) { int mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] / 2; modulus[2] += modulus[3] / 2; // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += modulus[1] / 2; count += modulus[3] / 2; // increment count by half of modulus[2] count += modulus[2] / 2; return count; }} // Driver Codeint main(){ // size of array int n = 7; // input array int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int count = getSteps(arr, n); printf(\"%d\", count);}", "e": 4946, "s": 3471, "text": null }, { "code": "// Java program for the above approachclass GFG{ static int getSteps(int arr[], int n){ // Count to keep track of the number of steps done. int count = 0; // Modulus array to store all elements mod 4 int modulus[] = new int[4]; // sum to check if given task is possible int sum = 0; // Loop to store all elements // mod 4 and calculate sum; int i; for (i = 0; i < n; i++) { int mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] / 2; modulus[2] += modulus[3] / 2; // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += modulus[1] / 2; count += modulus[3] / 2; // increment count by half of modulus[2] count += modulus[2] / 2; return count; }} // Driver Codepublic static void main(String[] args){ // size of array int n = 7; // input array int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int count = getSteps(arr, n); System.out.printf(\"%d\", count);}} // This code has been contributed by 29AjayKumar", "e": 6562, "s": 4946, "text": null }, { "code": "# Python 3 program for the above approachdef getSteps(arr, n): # Count to keep track of the # number of steps done. count = 0 # Modulus array to store all elements mod 4 modulus = [0 for i in range(4)] # Sum to check if given task is possible Sum = 0 # Loop to store all elements mod 4 # and calculate Sum i = 0 for i in range(n): mod = arr[i] % 4 Sum += mod modulus[mod] += 1 # If Sum is not divisible by 4, # not possible if (Sum % 4 != 0): return -1 else: # Find minimum of modulus[1] and modulus[3] # and increment the count by the minimum if (modulus[1] > modulus[3]): count += modulus[3] else: count += modulus[1] # Update the values in modulus array. modulus[1] -= count modulus[3] -= count # Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] // 2 modulus[2] += modulus[3] // 2 # increment count to half of remaining # modulus[1] or modulus of [3] elements. count += modulus[1] // 2 count += modulus[3] // 2 # increment count by half of modulus[2] count += modulus[2] // 2 return count # Driver Code # size of arrayn = 7 # input arrayarr = [1, 2, 3, 1, 2, 3, 8] count = getSteps(arr, n)print(count) # This code is contributed by mohit kumar", "e": 7965, "s": 6562, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ static int getSteps(int []arr, int n){ // Count to keep track of the number of steps done. int count = 0; // Modulus array to store all elements mod 4 int []modulus = new int[4]; // sum to check if given task is possible int sum = 0; // Loop to store all elements // mod 4 and calculate sum; int i; for (i = 0; i < n; i++) { int mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += modulus[1] / 2; modulus[2] += modulus[3] / 2; // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += modulus[1] / 2; count += modulus[3] / 2; // increment count by half of modulus[2] count += modulus[2] / 2; return count; }} // Driver Codepublic static void Main(String[] args){ // size of array int n = 7; // input array int []arr = { 1, 2, 3, 1, 2, 3, 8 }; int count = getSteps(arr, n); Console.Write(\"{0}\", count);}} // This code contributed by Rajput-Ji", "e": 9591, "s": 7965, "text": null }, { "code": "<?php// PHP program for the above approach function getSteps($arr, $n){ // Count to keep track of the number // of steps done. $count = 0; // Modulus array to store all elements mod 4 $modulus = array_fill(0, 4, 0); // sum to check if given task is possible $sum = 0; // Loop to store all elements // mod 4 and calculate sum; for ($i = 0; $i < $n; $i++) { $mod = $arr[$i] % 4; $sum += $mod; $modulus[$mod]++; } // If sum is not divisible by 4, not possible if ($sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if ($modulus[1] > $modulus[3]) { $count += $modulus[3]; } else { $count += $modulus[1]; } // Update the values in modulus array. $modulus[1] -= $count; $modulus[3] -= $count; // Use modulus[2] to pair remaining elements. $modulus[2] += (int)($modulus[1] / 2); $modulus[2] += (int)($modulus[3] / 2); // increment count to half of remaining // modulus[1] or modulus of [3] elements. $count += (int)($modulus[1] / 2); $count += (int)($modulus[3] / 2); // increment count by half of modulus[2] $count += (int)($modulus[2] / 2); return $count; }} // Driver Code // size of array$n = 7; // input array$arr = array( 1, 2, 3, 1, 2, 3, 8 ); $count = getSteps($arr, $n);print($count); // This code contributed by mits?>", "e": 11158, "s": 9591, "text": null }, { "code": "<script> function getSteps(arr, n) { // Count to keep track of the // number of steps done. let count = 0; // Modulus array to store all elements mod 4 let modulus = new Array(4); modulus.fill(0); // sum to check if given task is possible let sum = 0; // Loop to store all elements mod 4 // and calculate sum; let i; for (i = 0; i < n; i++) { let mod = arr[i] % 4; sum += mod; modulus[mod]++; } // If sum is not divisible by 4, // not possible if (sum % 4 != 0) { return -1; } else { // Find minimum of modulus[1] and modulus[3] // and increment the count by the minimum if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } // Update the values in modulus array. modulus[1] -= count; modulus[3] -= count; // Use modulus[2] to pair remaining elements. modulus[2] += parseInt(modulus[1] / 2, 10); modulus[2] += parseInt(modulus[3] / 2, 10); // increment count to half of remaining // modulus[1] or modulus of [3] elements. count += parseInt(modulus[1] / 2, 10); count += parseInt(modulus[3] / 2, 10); // increment count by half of modulus[2] count += parseInt(modulus[2] / 2, 10); return count; } } // size of array let n = 7; // input array let arr = [ 1, 2, 3, 1, 2, 3, 8 ]; let count = getSteps(arr, n); document.write(count); // This code is contributed by divyeshrabadiya07.</script>", "e": 12998, "s": 11158, "text": null }, { "code": null, "e": 13000, "s": 12998, "text": "3" }, { "code": null, "e": 13017, "s": 13002, "text": "mohit kumar 29" }, { "code": null, "e": 13029, "s": 13017, "text": "29AjayKumar" }, { "code": null, "e": 13039, "s": 13029, "text": "Rajput-Ji" }, { "code": null, "e": 13052, "s": 13039, "text": "Mithun Kumar" }, { "code": null, "e": 13065, "s": 13052, "text": "Akanksha_Rai" }, { "code": null, "e": 13076, "s": 13065, "text": "nidhi_biet" }, { "code": null, "e": 13094, "s": 13076, "text": "divyeshrabadiya07" }, { "code": null, "e": 13111, "s": 13094, "text": "akshaysingh98088" }, { "code": null, "e": 13131, "s": 13111, "text": "Number Divisibility" }, { "code": null, "e": 13138, "s": 13131, "text": "Arrays" }, { "code": null, "e": 13162, "s": 13138, "text": "Competitive Programming" }, { "code": null, "e": 13169, "s": 13162, "text": "Arrays" } ]
How to Execute Multiple SQL Commands on a Database Simultaneously in JDBC?
08 Jun, 2022 Java Database Connectivity also is known as JDBC is an application programming interface in Java that is used to establish connectivity between a Java application and database. JDBC commands can be used to perform SQL operations from the Java application. Demonstrating execution of multiple SQL commands on a database simultaneously using the addBatch() and executeBatch() commands of JDBC. The addBatch() command is used to queue the SQL statements and executeBatch() command is used to execute the queued SQL statements all at once. In order to use SQL statements in the Java application, ”java.sql” package needs to be imported in the beginning of the Java application. The Java application is connected to the database using the getConnection() method of DriverManager class. The getConnection() method takes three parameters URLs, username and password. Goal: Demonstrates two examples of which one uses the Statement Interface and the other uses PreparedStatement Interface. The PreparedStatement performs better than the Statement interface. Statement interface can be used to execute static SQL queries whereas PreparedStatement interface is used to execute dynamic SQL queries multiple times. Example 1: Using Statement Interface In this example, the java.sql package classes and interfaces are imported. The Statement interface is used to execute the sql statements. The table is creation sql statement along with record insertion sql statement are added to the batch using the addBatch() command. When all the statements are batched the executeBatch() command is executed which runs all the batched queries simultaneously. The sql statements may throw SQL Exceptions which must be handled in a try catch block to avoid abrupt termination of the program. After the table is created and records are inserted, to view the data in the table the select query is executed. The result obtained by executing the select query is stored in the ResultSet cursor. The cursor is iterated using the next() method and the records are displayed on the screen. Implementation: Using the standard interface Java // Step 1: Create a database// SQL database importedimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement; public class BatchCommand { // Main driver method public static void main(String args[]) { // Try block to check if exception occurs try { // Step 2: Loading driver class // Using forName() Class.forName("oracle.jdbc.OracleDriver"); // Step 3: Create connection object Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "username", "password"); Statement s = con.createStatement(); // Step 4: Create a statement / create table String sql1 = "CREATE TABLE STUDENT(STUDENTID VARCHAR2(10) PRIMARY KEY,NAME VARCHAR2(20),DEPARTMENT VARCHAR2(10))"; // Step 5: Process a query // Insert records in the table String sql2 = "INSERT INTO STUDENT VALUES('S101','JEAN','CSE')"; String sql3 = "INSERT INTO STUDENT VALUES('S102','ANA','CSE')"; String sql4 = "INSERT INTO STUDENT VALUES('S103','ROBERT','ECE')"; String sql5 = "INSERT INTO STUDENT VALUES('S104','ALEX','IT')"; String sql6 = "INSERT INTO STUDENT VALUES('S105','DIANA','IT')"; s.addBatch(sql1); s.addBatch(sql2); s.addBatch(sql3); s.addBatch(sql4); s.addBatch(sql5); s.addBatch(sql6); // Step 6: Process the results // execute the sql statements s.executeBatch(); ResultSet rs = s.executeQuery("Select * from Student"); // Print commands System.out.println( "StudentID\tName\t\tDepartment"); System.out.println( "-------------------------------------------------------"); // Condition to check pointer pointing while (rs.next()) { System.out.println(rs.getString(1) + "\t\t" + rs.getString(2) + "\t\t" + rs.getString(3)); } // Step 7: Close the connection con.commit(); con.close(); } // Catch block to handle exceptions catch (Exception e) { // Print line number if exception occurred System.out.println(e); } }} SQL commands over database using addBatch() method with the involvement of executeBatch() Java // Step 1: Importing database// SQL database importedimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement; public class BatchCommand { // Main driver method public static void main(String args[]) { // Try block to handle if exception occurs try { // Step 2: loading driver class Class.forName("oracle.jdbc.OracleDriver"); // Step 3: create connection object Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "username", "password"); Statement s = con.createStatement(); // Step 4: Create a statement // Create table String sql1 = "CREATE TABLE STUDENT(STUDENTID VARCHAR2(10) PRIMARY KEY,NAME VARCHAR2(20),DEPARTMENT VARCHAR2(10))"; // Step 5: Execute a query // Insert records in the table String sql2 = "INSERT INTO STUDENT VALUES('S101','JEAN','CSE')"; String sql3 = "INSERT INTO STUDENT VALUES('S102','ANA','CSE')"; String sql4 = "INSERT INTO STUDENT VALUES('S103','ROBERT','ECE')"; String sql5 = "INSERT INTO STUDENT VALUES('S104','ALEX','IT')"; String sql6 = "INSERT INTO STUDENT VALUES('S105','DIANA','IT')"; s.addBatch(sql1); s.addBatch(sql2); s.addBatch(sql3); s.addBatch(sql4); s.addBatch(sql5); s.addBatch(sql6); // Step 6: Process the statements // Create an int[] to hold returned values s.executeBatch(); ResultSet rs = s.executeQuery("Select * from Student"); // Print statements System.out.println( "StudentID\tName\t\tDepartment"); System.out.println( "-------------------------------------------------------"); // Condition check for pointer pointing which // record while (rs.next()) { System.out.println(rs.getString(1) + "\t\t" + rs.getString(2) + "\t\t" + rs.getString(3)); } // Step 7: Close the connection con.commit(); con.close(); } // Catch block to handle exception catch (Exception e) { // Print line number where exception occurred System.out.println(e); } }} Output Example 2: In this example, the java.sql package classes and interfaces are imported. The PreparedStatement interface is used to execute the SQL statements. The table is the creation SQL statement along with record insertion SQL statement are added to the batch using the addBatch() command. When all the statements are batched the executeBatch() command is executed which runs all the batched queries simultaneously. The sql statements may throw SQL Exceptions which must be handled in a try-catch block to avoid abrupt termination of the program. After the table is created and records are inserted, to view the data in the table the select query is executed. The result obtained by executing the select query is stored in the ResultSet cursor. The cursor is iterated using the next() method and the records are displayed on the screen. Unlike the previous example, it takes dynamic input from the user. Hence, using the PreparedStatement has performance benefits. Code Implementation Java import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;import java.util.*;public class AddBatchCommand { public static void main(String args[]) { Scanner scan = new Scanner(System.in); try { // loading driver class Class.forName("oracle.jdbc.OracleDriver"); // create connection object Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "username", "password"); // create the table String sql1 = "CREATE TABLE STUDENTS(STUDENTID VARCHAR2(10) PRIMARY KEY,NAME VARCHAR2(20),DEPARTMENT VARCHAR2(10))"; PreparedStatement ps = con.prepareStatement(sql1); ps.execute(sql1); // inserting records String sql = "Insert into Students values(?,?,?)"; PreparedStatement ps1 = con.prepareStatement(sql); for (int i = 0; i < 3; i++) { System.out.println("Enter Student ID"); String id = scan.nextLine(); System.out.println("Enter Student Name"); String name = scan.nextLine(); System.out.println("Enter the Department"); String dept = scan.nextLine(); ps1.setString(1, id); ps1.setString(2, name); ps1.setString(3, dept); // adding to batch ps1.addBatch(); } // executing the batch ps1.executeBatch(); // viewing the table ResultSet rs = ps.executeQuery("Select * from Students"); System.out.println( "StudentID\tName\t\tDepartment"); System.out.println( "-------------------------------------------------------"); while (rs.next()) { System.out.println(rs.getString(1) + "\t\t" + rs.getString(2) + "\t\t" + rs.getString(3)); } con.commit(); con.close(); } catch (Exception e) { System.out.println(e); } }} Output: Illustrating multiple SQL commands on a database simultaneously: simranarora5sos gabaa406 nikhatkhan11 JDBC Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2022" }, { "code": null, "e": 421, "s": 28, "text": "Java Database Connectivity also is known as JDBC is an application programming interface in Java that is used to establish connectivity between a Java application and database. JDBC commands can be used to perform SQL operations from the Java application. Demonstrating execution of multiple SQL commands on a database simultaneously using the addBatch() and executeBatch() commands of JDBC. " }, { "code": null, "e": 889, "s": 421, "text": "The addBatch() command is used to queue the SQL statements and executeBatch() command is used to execute the queued SQL statements all at once. In order to use SQL statements in the Java application, ”java.sql” package needs to be imported in the beginning of the Java application. The Java application is connected to the database using the getConnection() method of DriverManager class. The getConnection() method takes three parameters URLs, username and password." }, { "code": null, "e": 1232, "s": 889, "text": "Goal: Demonstrates two examples of which one uses the Statement Interface and the other uses PreparedStatement Interface. The PreparedStatement performs better than the Statement interface. Statement interface can be used to execute static SQL queries whereas PreparedStatement interface is used to execute dynamic SQL queries multiple times." }, { "code": null, "e": 1269, "s": 1232, "text": "Example 1: Using Statement Interface" }, { "code": null, "e": 2085, "s": 1269, "text": "In this example, the java.sql package classes and interfaces are imported. The Statement interface is used to execute the sql statements. The table is creation sql statement along with record insertion sql statement are added to the batch using the addBatch() command. When all the statements are batched the executeBatch() command is executed which runs all the batched queries simultaneously. The sql statements may throw SQL Exceptions which must be handled in a try catch block to avoid abrupt termination of the program. After the table is created and records are inserted, to view the data in the table the select query is executed. The result obtained by executing the select query is stored in the ResultSet cursor. The cursor is iterated using the next() method and the records are displayed on the screen." }, { "code": null, "e": 2130, "s": 2085, "text": "Implementation: Using the standard interface" }, { "code": null, "e": 2135, "s": 2130, "text": "Java" }, { "code": "// Step 1: Create a database// SQL database importedimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement; public class BatchCommand { // Main driver method public static void main(String args[]) { // Try block to check if exception occurs try { // Step 2: Loading driver class // Using forName() Class.forName(\"oracle.jdbc.OracleDriver\"); // Step 3: Create connection object Connection con = DriverManager.getConnection( \"jdbc:oracle:thin:@localhost:1521:xe\", \"username\", \"password\"); Statement s = con.createStatement(); // Step 4: Create a statement / create table String sql1 = \"CREATE TABLE STUDENT(STUDENTID VARCHAR2(10) PRIMARY KEY,NAME VARCHAR2(20),DEPARTMENT VARCHAR2(10))\"; // Step 5: Process a query // Insert records in the table String sql2 = \"INSERT INTO STUDENT VALUES('S101','JEAN','CSE')\"; String sql3 = \"INSERT INTO STUDENT VALUES('S102','ANA','CSE')\"; String sql4 = \"INSERT INTO STUDENT VALUES('S103','ROBERT','ECE')\"; String sql5 = \"INSERT INTO STUDENT VALUES('S104','ALEX','IT')\"; String sql6 = \"INSERT INTO STUDENT VALUES('S105','DIANA','IT')\"; s.addBatch(sql1); s.addBatch(sql2); s.addBatch(sql3); s.addBatch(sql4); s.addBatch(sql5); s.addBatch(sql6); // Step 6: Process the results // execute the sql statements s.executeBatch(); ResultSet rs = s.executeQuery(\"Select * from Student\"); // Print commands System.out.println( \"StudentID\\tName\\t\\tDepartment\"); System.out.println( \"-------------------------------------------------------\"); // Condition to check pointer pointing while (rs.next()) { System.out.println(rs.getString(1) + \"\\t\\t\" + rs.getString(2) + \"\\t\\t\" + rs.getString(3)); } // Step 7: Close the connection con.commit(); con.close(); } // Catch block to handle exceptions catch (Exception e) { // Print line number if exception occurred System.out.println(e); } }}", "e": 4748, "s": 2135, "text": null }, { "code": null, "e": 4838, "s": 4748, "text": "SQL commands over database using addBatch() method with the involvement of executeBatch()" }, { "code": null, "e": 4843, "s": 4838, "text": "Java" }, { "code": "// Step 1: Importing database// SQL database importedimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement; public class BatchCommand { // Main driver method public static void main(String args[]) { // Try block to handle if exception occurs try { // Step 2: loading driver class Class.forName(\"oracle.jdbc.OracleDriver\"); // Step 3: create connection object Connection con = DriverManager.getConnection( \"jdbc:oracle:thin:@localhost:1521:xe\", \"username\", \"password\"); Statement s = con.createStatement(); // Step 4: Create a statement // Create table String sql1 = \"CREATE TABLE STUDENT(STUDENTID VARCHAR2(10) PRIMARY KEY,NAME VARCHAR2(20),DEPARTMENT VARCHAR2(10))\"; // Step 5: Execute a query // Insert records in the table String sql2 = \"INSERT INTO STUDENT VALUES('S101','JEAN','CSE')\"; String sql3 = \"INSERT INTO STUDENT VALUES('S102','ANA','CSE')\"; String sql4 = \"INSERT INTO STUDENT VALUES('S103','ROBERT','ECE')\"; String sql5 = \"INSERT INTO STUDENT VALUES('S104','ALEX','IT')\"; String sql6 = \"INSERT INTO STUDENT VALUES('S105','DIANA','IT')\"; s.addBatch(sql1); s.addBatch(sql2); s.addBatch(sql3); s.addBatch(sql4); s.addBatch(sql5); s.addBatch(sql6); // Step 6: Process the statements // Create an int[] to hold returned values s.executeBatch(); ResultSet rs = s.executeQuery(\"Select * from Student\"); // Print statements System.out.println( \"StudentID\\tName\\t\\tDepartment\"); System.out.println( \"-------------------------------------------------------\"); // Condition check for pointer pointing which // record while (rs.next()) { System.out.println(rs.getString(1) + \"\\t\\t\" + rs.getString(2) + \"\\t\\t\" + rs.getString(3)); } // Step 7: Close the connection con.commit(); con.close(); } // Catch block to handle exception catch (Exception e) { // Print line number where exception occurred System.out.println(e); } }}", "e": 7478, "s": 4843, "text": null }, { "code": null, "e": 7486, "s": 7478, "text": "Output " }, { "code": null, "e": 8453, "s": 7486, "text": "Example 2: In this example, the java.sql package classes and interfaces are imported. The PreparedStatement interface is used to execute the SQL statements. The table is the creation SQL statement along with record insertion SQL statement are added to the batch using the addBatch() command. When all the statements are batched the executeBatch() command is executed which runs all the batched queries simultaneously. The sql statements may throw SQL Exceptions which must be handled in a try-catch block to avoid abrupt termination of the program. After the table is created and records are inserted, to view the data in the table the select query is executed. The result obtained by executing the select query is stored in the ResultSet cursor. The cursor is iterated using the next() method and the records are displayed on the screen. Unlike the previous example, it takes dynamic input from the user. Hence, using the PreparedStatement has performance benefits." }, { "code": null, "e": 8474, "s": 8453, "text": "Code Implementation " }, { "code": null, "e": 8479, "s": 8474, "text": "Java" }, { "code": "import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;import java.util.*;public class AddBatchCommand { public static void main(String args[]) { Scanner scan = new Scanner(System.in); try { // loading driver class Class.forName(\"oracle.jdbc.OracleDriver\"); // create connection object Connection con = DriverManager.getConnection( \"jdbc:oracle:thin:@localhost:1521:xe\", \"username\", \"password\"); // create the table String sql1 = \"CREATE TABLE STUDENTS(STUDENTID VARCHAR2(10) PRIMARY KEY,NAME VARCHAR2(20),DEPARTMENT VARCHAR2(10))\"; PreparedStatement ps = con.prepareStatement(sql1); ps.execute(sql1); // inserting records String sql = \"Insert into Students values(?,?,?)\"; PreparedStatement ps1 = con.prepareStatement(sql); for (int i = 0; i < 3; i++) { System.out.println(\"Enter Student ID\"); String id = scan.nextLine(); System.out.println(\"Enter Student Name\"); String name = scan.nextLine(); System.out.println(\"Enter the Department\"); String dept = scan.nextLine(); ps1.setString(1, id); ps1.setString(2, name); ps1.setString(3, dept); // adding to batch ps1.addBatch(); } // executing the batch ps1.executeBatch(); // viewing the table ResultSet rs = ps.executeQuery(\"Select * from Students\"); System.out.println( \"StudentID\\tName\\t\\tDepartment\"); System.out.println( \"-------------------------------------------------------\"); while (rs.next()) { System.out.println(rs.getString(1) + \"\\t\\t\" + rs.getString(2) + \"\\t\\t\" + rs.getString(3)); } con.commit(); con.close(); } catch (Exception e) { System.out.println(e); } }}", "e": 10835, "s": 8479, "text": null }, { "code": null, "e": 10910, "s": 10835, "text": "Output: Illustrating multiple SQL commands on a database simultaneously: " }, { "code": null, "e": 10928, "s": 10912, "text": "simranarora5sos" }, { "code": null, "e": 10937, "s": 10928, "text": "gabaa406" }, { "code": null, "e": 10950, "s": 10937, "text": "nikhatkhan11" }, { "code": null, "e": 10955, "s": 10950, "text": "JDBC" }, { "code": null, "e": 10962, "s": 10955, "text": "Picked" }, { "code": null, "e": 10986, "s": 10962, "text": "Technical Scripter 2020" }, { "code": null, "e": 10991, "s": 10986, "text": "Java" }, { "code": null, "e": 11010, "s": 10991, "text": "Technical Scripter" }, { "code": null, "e": 11015, "s": 11010, "text": "Java" } ]
Logistic Regression From Scratch in Python | by Suraj Verma | Towards Data Science
In this article, we are going to implement the most commonly used Classification algorithm called the Logistic Regression. First, we will understand the Sigmoid function, Hypothesis function, Decision Boundary, the Log Loss function and code them alongside. After that, we will apply the Gradient Descent Algorithm to find the parameters, weights and bias . Finally, we will measure accuracy and plot the decision boundary for a linearly separable dataset and a non-linearly separable dataset. We will implement it all using Python NumPy and Matplotlib. towardsdatascience.com n →number of features m →number of training examples X →input data matrix of shape (m x n) y →true/ target value (can be 0 or 1 only) x(i), y(i)→ith training example w → weights (parameters) of shape (n x 1) b →bias (parameter), a real number that can be broadcasted. y_hat(y with a cap/hat)→ hypothesis (outputs values between 0 and 1) We are going to do binary classification, so the value of y (true/target) is going to be either 0 or 1. For example, suppose we have a breast cancer dataset with X being the tumor size and y being whether the lump is malignant(cancerous) or benign(non-cancerous). Whenever a patient visits, your job is to tell him/her whether the lump is malignant(0) or benign(1) given the size of the tumor. There are only two classes in this case. So, y is going to be either 0 or 1. Let’s use the following randomly generated data as a motivating example to understand Logistic Regression. from sklearn.datasets import make_classificationX, y = make_classification(n_features=2, n_redundant=0, n_informative=2, random_state=1, n_clusters_per_class=1) There are 2 features, n=2. There are 2 classes, blue and green. For a binary classification problem, we naturally want our hypothesis (y_hat) function to output values between 0 and 1 which means all Real numbers from 0 to 1. So, we want to choose a function that squishes all its inputs between 0 and 1. One such function is the Sigmoid or Logistic function. The Sigmoid Function squishes all its inputs (values on the x-axis) between 0 and 1 as we can see on the y-axis in the graph below. The range of inputs for this function is the set of all Real Numbers and the range of outputs is between 0 and 1. We can see that as z increases towards positive infinity the output gets closer to 1, and as z decreases towards negative infinity the output gets closer to 0. def sigmoid(z): return 1.0/(1 + np.exp(-z)) For Linear Regression, we had the hypothesis y_hat = w.X +b , whose output range was the set of all Real Numbers. Now, for Logistic Regression our hypothesis is — y_hat = sigmoid(w.X + b) , whose output range is between 0 and 1 because by applying a sigmoid function, we always output a number between 0 and 1. y_hat = z = w.X +b Now, you might wonder that there are lots of continuous function that outputs values between 0 and 1. Why did we choose the Logistic Function only, why not any other? Actually, there is a broader class of algorithms called Generalized Linear Models of which this is a special case. Sigmoid function falls out very naturally from it given our set of assumptions. For every parametric machine learning algorithm, we need a loss function, which we want to minimize (find the global minimum of) to determine the optimal parameters(w and b) which will help us make the best predictions. For Linear Regression, we had the mean squared error as the loss function. But that was a regression problem. For a binary classification problem, we need to be able to output the probability of y being 1(tumor is benign for example), then we can determine the probability of y being 0(tumor is malignant) or vice versa. So, we assume that the values that our hypothesis(y_hat) outputs between 0 and 1, is a probability of y being 1, then the probability of y being 0 will be (1-y_hat) . Remember that y is only 0 or 1. y_hat is a number between 0 and 1. More formally, the probability of y=1 given X , parameterized by w and b is y_hat (hypothesis). Then, logically the probability of y=0 given X , parameterized by w and b should be 1-y_hat . This can be written as — P(y = 1 | X; w, b) = y_hat P(y = 0 | X; w, b) = (1-y_hat) Then, based on our assumptions, we can calculate the loglikelihood of parameters using the above two equations and consequently determine the loss function which we have to minimize. The following is the Binary Coss-Entropy Loss or the Log Loss function — For reference — Understanding the Logistic Regression and likelihood J(w,b) is the overall cost/loss of the training set and L is the cost for ith training example. def loss(y, y_hat): loss = -np.mean(y*(np.log(y_hat)) - (1-y)*np.log(1-y_hat)) return loss By looking at the Loss function, we can see that loss approaches 0 when we predict correctly, i.e, when y=0 and y_hat=0 or, y=1 and y_hat=1, and loss function approaches infinity if we predict incorrectly, i.e, when y=0 but y_hat=1 or, y=1 but y_hat=1. Now that we know our hypothesis function and the loss function, all we need to do is use the Gradient Descent Algorithm to find the optimal values of our parameters like this(lr →learning rate) — w := w-lr*dw b := b-lr*db where, dw is the partial derivative of the Loss function with respect to w and db is the partial derivative of the Loss function with respect to b . dw = (1/m)*(y_hat — y).X db = (1/m)*(y_hat — y) Let’s write a function gradients to calculate dw and db . See comments(#). def gradients(X, y, y_hat): # X --> Input. # y --> true/target value. # y_hat --> hypothesis/predictions. # w --> weights (parameter). # b --> bias (parameter). # m-> number of training examples. m = X.shape[0] # Gradient of loss w.r.t weights. dw = (1/m)*np.dot(X.T, (y_hat - y)) # Gradient of loss w.r.t bias. db = (1/m)*np.sum((y_hat - y)) return dw, db Now, we want to know how our hypothesis(y_hat) is going to make predictions of whether y=1 or y=0. The way we defined hypothesis is the probability of y being 1 given X and parameterized by w and b . So, we will say that it will make a prediction of — y=1 when y_hat ≥ 0.5 y=0 when y_hat < 0.5 Looking at the graph of the sigmoid function, we see that for — y_hat ≥ 0.5, z or w.X + b ≥ 0 y_hat < 0.5, z or w.X + b < 0 which means, we make a prediction for — y=1 when w.X + b ≥ 0 y=0 when w.X + b < 0 So, w.X + b = 0 is going to be our Decision boundary. The following code for plotting the Decision Boundary only works when we have only two features in X. def plot_decision_boundary(X, w, b): # X --> Inputs # w --> weights # b --> bias # The Line is y=mx+c # So, Equate mx+c = w.X + b # Solving we find m and c x1 = [min(X[:,0]), max(X[:,0])] m = -w[0]/w[1] c = -b/w[1] x2 = m*x1 + c # Plotting fig = plt.figure(figsize=(10,8)) plt.plot(X[:, 0][y==0], X[:, 1][y==0], "g^") plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") plt.xlim([-2, 2]) plt.ylim([0, 2.2]) plt.xlabel("feature 1") plt.ylabel("feature 2") plt.title('Decision Boundary') plt.plot(x1, x2, 'y-') Function to normalize the inputs. See comments(#). def normalize(X): # X --> Input. # m-> number of training examples # n-> number of features m, n = X.shape # Normalizing all the n features of X. for i in range(n): X = (X - X.mean(axis=0))/X.std(axis=0) return X The train the function includes initializing the weights and bias and the training loop with mini-batch gradient descent. See comments(#). def train(X, y, bs, epochs, lr): # X --> Input. # y --> true/target value. # bs --> Batch Size. # epochs --> Number of iterations. # lr --> Learning rate. # m-> number of training examples # n-> number of features m, n = X.shape # Initializing weights and bias to zeros. w = np.zeros((n,1)) b = 0 # Reshaping y. y = y.reshape(m,1) # Normalizing the inputs. x = normalize(X) # Empty list to store losses. losses = [] # Training loop. for epoch in range(epochs): for i in range((m-1)//bs + 1): # Defining batches. SGD. start_i = i*bs end_i = start_i + bs xb = X[start_i:end_i] yb = y[start_i:end_i] # Calculating hypothesis/prediction. y_hat = sigmoid(np.dot(xb, w) + b) # Getting the gradients of loss w.r.t parameters. dw, db = gradients(xb, yb, y_hat) # Updating the parameters. w -= lr*dw b -= lr*db # Calculating loss and appending it in the list. l = loss(y, sigmoid(np.dot(X, w) + b)) losses.append(l) # returning weights, bias and losses(List). return w, b, losses See comments(#). def predict(X): # X --> Input. # Normalizing the inputs. x = normalize(X) # Calculating presictions/y_hat. preds = sigmoid(np.dot(X, w) + b) # Empty List to store predictions. pred_class = [] # if y_hat >= 0.5 --> round up to 1 # if y_hat < 0.5 --> round up to 1 pred_class = [1 if i > 0.5 else 0 for i in preds] return np.array(pred_class) # Training w, b, l = train(X, y, bs=100, epochs=1000, lr=0.01)# Plotting Decision Boundaryplot_decision_boundary(X, w, b) We check how many examples did we get right and divide it by the total number of examples. def accuracy(y, y_hat): accuracy = np.sum(y == y_hat) / len(y) return accuracyaccuracy(X, y_hat=predict(X))>> 1.0 We get an accuracy of 100%. We can see from the above decision boundary graph that we are able to separate the green and blue classes perfectly. Let’s test out our code for data that is not linearly separable. from sklearn.datasets import make_moonsX, y = make_moons(n_samples=100, noise=0.24) # Training w, b, l = train(X, y, bs=100, epochs=1000, lr=0.01)# Plotting Decision Boundaryplot_decision_boundary(X, w, b) Since Logistic Regression is only a linear classifier, we were able to put a decent straight line which was able to separate as many blues and greens from each other as possible. Let’s check accuracy for this — accuracy(y, predict(X))>> 0.87 87 % accuracy. Not bad. When I was training the data using my code, I always got the NaN values in my losses list. Later I discovered the I was not normalizing my inputs, and that was the reason my losses were full of NaNs. If you are getting NaN values or overflow during training — Normalize your Data — X . Lower your Learning rate. Thanks for reading. For questions, comments, concerns, talk to be in the response section. More ML from scratch is coming soon. Check out the Machine Learning from scratch series — Part 1: Linear Regression from scratch in Python Part 2: Locally Weighted Linear Regression in Python Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression Part 4: Polynomial Regression From Scratch in Python
[ { "code": null, "e": 429, "s": 171, "text": "In this article, we are going to implement the most commonly used Classification algorithm called the Logistic Regression. First, we will understand the Sigmoid function, Hypothesis function, Decision Boundary, the Log Loss function and code them alongside." }, { "code": null, "e": 665, "s": 429, "text": "After that, we will apply the Gradient Descent Algorithm to find the parameters, weights and bias . Finally, we will measure accuracy and plot the decision boundary for a linearly separable dataset and a non-linearly separable dataset." }, { "code": null, "e": 725, "s": 665, "text": "We will implement it all using Python NumPy and Matplotlib." }, { "code": null, "e": 748, "s": 725, "text": "towardsdatascience.com" }, { "code": null, "e": 770, "s": 748, "text": "n →number of features" }, { "code": null, "e": 801, "s": 770, "text": "m →number of training examples" }, { "code": null, "e": 839, "s": 801, "text": "X →input data matrix of shape (m x n)" }, { "code": null, "e": 882, "s": 839, "text": "y →true/ target value (can be 0 or 1 only)" }, { "code": null, "e": 914, "s": 882, "text": "x(i), y(i)→ith training example" }, { "code": null, "e": 956, "s": 914, "text": "w → weights (parameters) of shape (n x 1)" }, { "code": null, "e": 1016, "s": 956, "text": "b →bias (parameter), a real number that can be broadcasted." }, { "code": null, "e": 1085, "s": 1016, "text": "y_hat(y with a cap/hat)→ hypothesis (outputs values between 0 and 1)" }, { "code": null, "e": 1189, "s": 1085, "text": "We are going to do binary classification, so the value of y (true/target) is going to be either 0 or 1." }, { "code": null, "e": 1520, "s": 1189, "text": "For example, suppose we have a breast cancer dataset with X being the tumor size and y being whether the lump is malignant(cancerous) or benign(non-cancerous). Whenever a patient visits, your job is to tell him/her whether the lump is malignant(0) or benign(1) given the size of the tumor. There are only two classes in this case." }, { "code": null, "e": 1556, "s": 1520, "text": "So, y is going to be either 0 or 1." }, { "code": null, "e": 1663, "s": 1556, "text": "Let’s use the following randomly generated data as a motivating example to understand Logistic Regression." }, { "code": null, "e": 1878, "s": 1663, "text": "from sklearn.datasets import make_classificationX, y = make_classification(n_features=2, n_redundant=0, n_informative=2, random_state=1, n_clusters_per_class=1)" }, { "code": null, "e": 1942, "s": 1878, "text": "There are 2 features, n=2. There are 2 classes, blue and green." }, { "code": null, "e": 2104, "s": 1942, "text": "For a binary classification problem, we naturally want our hypothesis (y_hat) function to output values between 0 and 1 which means all Real numbers from 0 to 1." }, { "code": null, "e": 2238, "s": 2104, "text": "So, we want to choose a function that squishes all its inputs between 0 and 1. One such function is the Sigmoid or Logistic function." }, { "code": null, "e": 2370, "s": 2238, "text": "The Sigmoid Function squishes all its inputs (values on the x-axis) between 0 and 1 as we can see on the y-axis in the graph below." }, { "code": null, "e": 2484, "s": 2370, "text": "The range of inputs for this function is the set of all Real Numbers and the range of outputs is between 0 and 1." }, { "code": null, "e": 2644, "s": 2484, "text": "We can see that as z increases towards positive infinity the output gets closer to 1, and as z decreases towards negative infinity the output gets closer to 0." }, { "code": null, "e": 2691, "s": 2644, "text": "def sigmoid(z): return 1.0/(1 + np.exp(-z))" }, { "code": null, "e": 2805, "s": 2691, "text": "For Linear Regression, we had the hypothesis y_hat = w.X +b , whose output range was the set of all Real Numbers." }, { "code": null, "e": 3002, "s": 2805, "text": "Now, for Logistic Regression our hypothesis is — y_hat = sigmoid(w.X + b) , whose output range is between 0 and 1 because by applying a sigmoid function, we always output a number between 0 and 1." }, { "code": null, "e": 3010, "s": 3002, "text": "y_hat =" }, { "code": null, "e": 3021, "s": 3010, "text": "z = w.X +b" }, { "code": null, "e": 3383, "s": 3021, "text": "Now, you might wonder that there are lots of continuous function that outputs values between 0 and 1. Why did we choose the Logistic Function only, why not any other? Actually, there is a broader class of algorithms called Generalized Linear Models of which this is a special case. Sigmoid function falls out very naturally from it given our set of assumptions." }, { "code": null, "e": 3603, "s": 3383, "text": "For every parametric machine learning algorithm, we need a loss function, which we want to minimize (find the global minimum of) to determine the optimal parameters(w and b) which will help us make the best predictions." }, { "code": null, "e": 3713, "s": 3603, "text": "For Linear Regression, we had the mean squared error as the loss function. But that was a regression problem." }, { "code": null, "e": 3924, "s": 3713, "text": "For a binary classification problem, we need to be able to output the probability of y being 1(tumor is benign for example), then we can determine the probability of y being 0(tumor is malignant) or vice versa." }, { "code": null, "e": 4091, "s": 3924, "text": "So, we assume that the values that our hypothesis(y_hat) outputs between 0 and 1, is a probability of y being 1, then the probability of y being 0 will be (1-y_hat) ." }, { "code": null, "e": 4158, "s": 4091, "text": "Remember that y is only 0 or 1. y_hat is a number between 0 and 1." }, { "code": null, "e": 4373, "s": 4158, "text": "More formally, the probability of y=1 given X , parameterized by w and b is y_hat (hypothesis). Then, logically the probability of y=0 given X , parameterized by w and b should be 1-y_hat . This can be written as —" }, { "code": null, "e": 4400, "s": 4373, "text": "P(y = 1 | X; w, b) = y_hat" }, { "code": null, "e": 4431, "s": 4400, "text": "P(y = 0 | X; w, b) = (1-y_hat)" }, { "code": null, "e": 4687, "s": 4431, "text": "Then, based on our assumptions, we can calculate the loglikelihood of parameters using the above two equations and consequently determine the loss function which we have to minimize. The following is the Binary Coss-Entropy Loss or the Log Loss function —" }, { "code": null, "e": 4756, "s": 4687, "text": "For reference — Understanding the Logistic Regression and likelihood" }, { "code": null, "e": 4852, "s": 4756, "text": "J(w,b) is the overall cost/loss of the training set and L is the cost for ith training example." }, { "code": null, "e": 4949, "s": 4852, "text": "def loss(y, y_hat): loss = -np.mean(y*(np.log(y_hat)) - (1-y)*np.log(1-y_hat)) return loss" }, { "code": null, "e": 5202, "s": 4949, "text": "By looking at the Loss function, we can see that loss approaches 0 when we predict correctly, i.e, when y=0 and y_hat=0 or, y=1 and y_hat=1, and loss function approaches infinity if we predict incorrectly, i.e, when y=0 but y_hat=1 or, y=1 but y_hat=1." }, { "code": null, "e": 5398, "s": 5202, "text": "Now that we know our hypothesis function and the loss function, all we need to do is use the Gradient Descent Algorithm to find the optimal values of our parameters like this(lr →learning rate) —" }, { "code": null, "e": 5411, "s": 5398, "text": "w := w-lr*dw" }, { "code": null, "e": 5424, "s": 5411, "text": "b := b-lr*db" }, { "code": null, "e": 5573, "s": 5424, "text": "where, dw is the partial derivative of the Loss function with respect to w and db is the partial derivative of the Loss function with respect to b ." }, { "code": null, "e": 5598, "s": 5573, "text": "dw = (1/m)*(y_hat — y).X" }, { "code": null, "e": 5621, "s": 5598, "text": "db = (1/m)*(y_hat — y)" }, { "code": null, "e": 5679, "s": 5621, "text": "Let’s write a function gradients to calculate dw and db ." }, { "code": null, "e": 5696, "s": 5679, "text": "See comments(#)." }, { "code": null, "e": 6110, "s": 5696, "text": "def gradients(X, y, y_hat): # X --> Input. # y --> true/target value. # y_hat --> hypothesis/predictions. # w --> weights (parameter). # b --> bias (parameter). # m-> number of training examples. m = X.shape[0] # Gradient of loss w.r.t weights. dw = (1/m)*np.dot(X.T, (y_hat - y)) # Gradient of loss w.r.t bias. db = (1/m)*np.sum((y_hat - y)) return dw, db" }, { "code": null, "e": 6310, "s": 6110, "text": "Now, we want to know how our hypothesis(y_hat) is going to make predictions of whether y=1 or y=0. The way we defined hypothesis is the probability of y being 1 given X and parameterized by w and b ." }, { "code": null, "e": 6362, "s": 6310, "text": "So, we will say that it will make a prediction of —" }, { "code": null, "e": 6383, "s": 6362, "text": "y=1 when y_hat ≥ 0.5" }, { "code": null, "e": 6404, "s": 6383, "text": "y=0 when y_hat < 0.5" }, { "code": null, "e": 6468, "s": 6404, "text": "Looking at the graph of the sigmoid function, we see that for —" }, { "code": null, "e": 6498, "s": 6468, "text": "y_hat ≥ 0.5, z or w.X + b ≥ 0" }, { "code": null, "e": 6528, "s": 6498, "text": "y_hat < 0.5, z or w.X + b < 0" }, { "code": null, "e": 6568, "s": 6528, "text": "which means, we make a prediction for —" }, { "code": null, "e": 6589, "s": 6568, "text": "y=1 when w.X + b ≥ 0" }, { "code": null, "e": 6610, "s": 6589, "text": "y=0 when w.X + b < 0" }, { "code": null, "e": 6664, "s": 6610, "text": "So, w.X + b = 0 is going to be our Decision boundary." }, { "code": null, "e": 6766, "s": 6664, "text": "The following code for plotting the Decision Boundary only works when we have only two features in X." }, { "code": null, "e": 7340, "s": 6766, "text": "def plot_decision_boundary(X, w, b): # X --> Inputs # w --> weights # b --> bias # The Line is y=mx+c # So, Equate mx+c = w.X + b # Solving we find m and c x1 = [min(X[:,0]), max(X[:,0])] m = -w[0]/w[1] c = -b/w[1] x2 = m*x1 + c # Plotting fig = plt.figure(figsize=(10,8)) plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"g^\") plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\") plt.xlim([-2, 2]) plt.ylim([0, 2.2]) plt.xlabel(\"feature 1\") plt.ylabel(\"feature 2\") plt.title('Decision Boundary') plt.plot(x1, x2, 'y-')" }, { "code": null, "e": 7391, "s": 7340, "text": "Function to normalize the inputs. See comments(#)." }, { "code": null, "e": 7653, "s": 7391, "text": "def normalize(X): # X --> Input. # m-> number of training examples # n-> number of features m, n = X.shape # Normalizing all the n features of X. for i in range(n): X = (X - X.mean(axis=0))/X.std(axis=0) return X" }, { "code": null, "e": 7775, "s": 7653, "text": "The train the function includes initializing the weights and bias and the training loop with mini-batch gradient descent." }, { "code": null, "e": 7792, "s": 7775, "text": "See comments(#)." }, { "code": null, "e": 9083, "s": 7792, "text": "def train(X, y, bs, epochs, lr): # X --> Input. # y --> true/target value. # bs --> Batch Size. # epochs --> Number of iterations. # lr --> Learning rate. # m-> number of training examples # n-> number of features m, n = X.shape # Initializing weights and bias to zeros. w = np.zeros((n,1)) b = 0 # Reshaping y. y = y.reshape(m,1) # Normalizing the inputs. x = normalize(X) # Empty list to store losses. losses = [] # Training loop. for epoch in range(epochs): for i in range((m-1)//bs + 1): # Defining batches. SGD. start_i = i*bs end_i = start_i + bs xb = X[start_i:end_i] yb = y[start_i:end_i] # Calculating hypothesis/prediction. y_hat = sigmoid(np.dot(xb, w) + b) # Getting the gradients of loss w.r.t parameters. dw, db = gradients(xb, yb, y_hat) # Updating the parameters. w -= lr*dw b -= lr*db # Calculating loss and appending it in the list. l = loss(y, sigmoid(np.dot(X, w) + b)) losses.append(l) # returning weights, bias and losses(List). return w, b, losses" }, { "code": null, "e": 9100, "s": 9083, "text": "See comments(#)." }, { "code": null, "e": 9494, "s": 9100, "text": "def predict(X): # X --> Input. # Normalizing the inputs. x = normalize(X) # Calculating presictions/y_hat. preds = sigmoid(np.dot(X, w) + b) # Empty List to store predictions. pred_class = [] # if y_hat >= 0.5 --> round up to 1 # if y_hat < 0.5 --> round up to 1 pred_class = [1 if i > 0.5 else 0 for i in preds] return np.array(pred_class)" }, { "code": null, "e": 9616, "s": 9494, "text": "# Training w, b, l = train(X, y, bs=100, epochs=1000, lr=0.01)# Plotting Decision Boundaryplot_decision_boundary(X, w, b)" }, { "code": null, "e": 9707, "s": 9616, "text": "We check how many examples did we get right and divide it by the total number of examples." }, { "code": null, "e": 9827, "s": 9707, "text": "def accuracy(y, y_hat): accuracy = np.sum(y == y_hat) / len(y) return accuracyaccuracy(X, y_hat=predict(X))>> 1.0" }, { "code": null, "e": 9972, "s": 9827, "text": "We get an accuracy of 100%. We can see from the above decision boundary graph that we are able to separate the green and blue classes perfectly." }, { "code": null, "e": 10037, "s": 9972, "text": "Let’s test out our code for data that is not linearly separable." }, { "code": null, "e": 10121, "s": 10037, "text": "from sklearn.datasets import make_moonsX, y = make_moons(n_samples=100, noise=0.24)" }, { "code": null, "e": 10243, "s": 10121, "text": "# Training w, b, l = train(X, y, bs=100, epochs=1000, lr=0.01)# Plotting Decision Boundaryplot_decision_boundary(X, w, b)" }, { "code": null, "e": 10422, "s": 10243, "text": "Since Logistic Regression is only a linear classifier, we were able to put a decent straight line which was able to separate as many blues and greens from each other as possible." }, { "code": null, "e": 10454, "s": 10422, "text": "Let’s check accuracy for this —" }, { "code": null, "e": 10485, "s": 10454, "text": "accuracy(y, predict(X))>> 0.87" }, { "code": null, "e": 10509, "s": 10485, "text": "87 % accuracy. Not bad." }, { "code": null, "e": 10600, "s": 10509, "text": "When I was training the data using my code, I always got the NaN values in my losses list." }, { "code": null, "e": 10709, "s": 10600, "text": "Later I discovered the I was not normalizing my inputs, and that was the reason my losses were full of NaNs." }, { "code": null, "e": 10769, "s": 10709, "text": "If you are getting NaN values or overflow during training —" }, { "code": null, "e": 10795, "s": 10769, "text": "Normalize your Data — X ." }, { "code": null, "e": 10821, "s": 10795, "text": "Lower your Learning rate." }, { "code": null, "e": 10949, "s": 10821, "text": "Thanks for reading. For questions, comments, concerns, talk to be in the response section. More ML from scratch is coming soon." }, { "code": null, "e": 11002, "s": 10949, "text": "Check out the Machine Learning from scratch series —" }, { "code": null, "e": 11051, "s": 11002, "text": "Part 1: Linear Regression from scratch in Python" }, { "code": null, "e": 11104, "s": 11051, "text": "Part 2: Locally Weighted Linear Regression in Python" }, { "code": null, "e": 11189, "s": 11104, "text": "Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression" } ]
How do I convert between big-endian and little-endian values in C++?
Here we will see how to convert Little endian value to Big endian or big endian value to little endian in C++. Before going to the actual discussion, we will see what is the big endian and the little endian? In different architectures, the multi-byte data can be stored in two different ways. Sometimes the higher order bytes are stored first, in that case these are known as big endian, and sometimes the lower order bytes are stored first, then it is called little endian. For example, if the number is 0x9876543210, then the big endian will be − The little endian will be like this − In this section we will see how to convert little endian to big endian and vice versa. To do this we have to interchange the 1st and 4th bytes, and 2nd and 3rd bytes. We can interchange them using logical expressions. Make Copy of the number four times, then for the first copy, shift the 1st byte 24 times to the right, for the second copy, mask it with 00FF0000, then swap 8 bits to the right, for the 3rd copy mask it with 0000FF00, then shift left 8 bits, and for the last copy swap the elements to the left 24 times. Then Logically OR these four copies to get the reversed result. #include <iostream> #define SWAP_INT32(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | ((x) << 24)) using namespace std; void memory_represent(char *value, int n) { int i; for (i = 0; i < n; i++) printf(" %.2x", value[i]); } int main() { unsigned int x = 0x9876543210; int y; cout << "The little endian value is: "; memory_represent((char*)&x, sizeof(x)); cout << endl; y = SWAP_INT32(x); cout << "The Big endian value after conversion is: "; memory_represent((char*)&y, sizeof(y)); cout << endl; } The little endian value is: 10 32 54 76 The Big endian value after conversion is: 76 54 32 10
[ { "code": null, "e": 1270, "s": 1062, "text": "Here we will see how to convert Little endian value to Big endian or big endian value to little endian in C++. Before going to the actual discussion, we will see what is the big endian and the little endian?" }, { "code": null, "e": 1537, "s": 1270, "text": "In different architectures, the multi-byte data can be stored in two different ways. Sometimes the higher order bytes are stored first, in that case these are known as big endian, and sometimes the lower order bytes are stored first, then it is called little endian." }, { "code": null, "e": 1611, "s": 1537, "text": "For example, if the number is 0x9876543210, then the big endian will be −" }, { "code": null, "e": 1649, "s": 1611, "text": "The little endian will be like this −" }, { "code": null, "e": 2235, "s": 1649, "text": "In this section we will see how to convert little endian to big endian and vice versa. To do this we have to interchange the 1st and 4th bytes, and 2nd and 3rd bytes. We can interchange them using logical expressions. Make Copy of the number four times, then for the first copy, shift the 1st byte 24 times to the right, for the second copy, mask it with 00FF0000, then swap 8 bits to the right, for the 3rd copy mask it with 0000FF00, then shift left 8 bits, and for the last copy swap the elements to the left 24 times. Then Logically OR these four copies to get the reversed result." }, { "code": null, "e": 2799, "s": 2235, "text": "#include <iostream>\n#define SWAP_INT32(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | ((x) << 24)) using namespace std;\nvoid memory_represent(char *value, int n) {\n int i;\n for (i = 0; i < n; i++)\n printf(\" %.2x\", value[i]);\n}\nint main() {\n unsigned int x = 0x9876543210;\n int y;\n cout << \"The little endian value is: \";\n memory_represent((char*)&x, sizeof(x));\n cout << endl;\n y = SWAP_INT32(x);\n cout << \"The Big endian value after conversion is: \";\n memory_represent((char*)&y, sizeof(y));\n cout << endl;\n}" }, { "code": null, "e": 2893, "s": 2799, "text": "The little endian value is: 10 32 54 76\nThe Big endian value after conversion is: 76 54 32 10" } ]
How to override only few methods of interface in Java?
Once you implement an interface from a concrete class you need to provide implementation to all its methods. If you try to skip implementing methods of an interface at compile time an error would be generated. Live Demo interface MyInterface{ public void sample(); public void display(); } public class InterfaceExample implements MyInterface{ public void sample(){ System.out.println("Implementation of the sample method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.sample(); } } InterfaceExample.java:5: error: InterfaceExample is not abstract and does not override abstract method display() in MyInterface public class InterfaceExample implements MyInterface{ ^ 1 error But, If you still need to skip the implementation. You can either provide a dummy implementation to the unwanted methods by throwing an exception such as UnsupportedOperationException or, IllegalStateException from them. Live Demo interface MyInterface{ public void sample(); public void display(); } public class InterfaceExample implements MyInterface{ public void sample(){ System.out.println("Implementation of the sample method"); } public void display(){ throw new UnsupportedOperationException(); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.sample(); obj.display(); } } Implementation of the sample method Exception in thread "main" java.lang.UnsupportedOperationException at InterfaceExample.display(InterfaceExample.java:10) at InterfaceExample.main(InterfaceExample.java:15) You can make the methods default in the interface itself, Default methods are introduced in interfaces since Java8 and if you have default methods in an interface it is not mandatory to override them in the implementing class. Live Demo interface MyInterface{ public void sample(); default public void display(){ System.out.println("Default implementation of the display method"); } } public class InterfaceExample implements MyInterface{ public void sample(){ System.out.println("Implementation of the sample method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.sample(); obj.display(); } } Implementation of the sample method Default implementation of the display method
[ { "code": null, "e": 1272, "s": 1062, "text": "Once you implement an interface from a concrete class you need to provide implementation to all its methods. If you try to skip implementing methods of an interface at compile time an error would be generated." }, { "code": null, "e": 1283, "s": 1272, "text": " Live Demo" }, { "code": null, "e": 1632, "s": 1283, "text": "interface MyInterface{\n public void sample();\n public void display();\n}\npublic class InterfaceExample implements MyInterface{\n public void sample(){\n System.out.println(\"Implementation of the sample method\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.sample();\n }\n}" }, { "code": null, "e": 1831, "s": 1632, "text": "InterfaceExample.java:5: error: InterfaceExample is not abstract and does not override abstract method display() in MyInterface\npublic class InterfaceExample implements MyInterface{\n ^\n1 error" }, { "code": null, "e": 1882, "s": 1831, "text": "But, If you still need to skip the implementation." }, { "code": null, "e": 2052, "s": 1882, "text": "You can either provide a dummy implementation to the unwanted methods by throwing an exception such as UnsupportedOperationException or, IllegalStateException from them." }, { "code": null, "e": 2063, "s": 2052, "text": " Live Demo" }, { "code": null, "e": 2513, "s": 2063, "text": "interface MyInterface{\n public void sample();\n public void display();\n}\npublic class InterfaceExample implements MyInterface{\n public void sample(){\n System.out.println(\"Implementation of the sample method\");\n }\n public void display(){\n throw new UnsupportedOperationException();\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.sample();\n obj.display();\n }\n}" }, { "code": null, "e": 2721, "s": 2513, "text": "Implementation of the sample method\nException in thread \"main\" java.lang.UnsupportedOperationException\nat InterfaceExample.display(InterfaceExample.java:10)\nat InterfaceExample.main(InterfaceExample.java:15)" }, { "code": null, "e": 2948, "s": 2721, "text": "You can make the methods default in the interface itself, Default methods are introduced in interfaces since Java8 and if you have default methods in an interface it is not mandatory to override them in the implementing class." }, { "code": null, "e": 2959, "s": 2948, "text": " Live Demo" }, { "code": null, "e": 3416, "s": 2959, "text": "interface MyInterface{\n public void sample();\n default public void display(){\n System.out.println(\"Default implementation of the display method\");\n }\n}\npublic class InterfaceExample implements MyInterface{\n public void sample(){\n System.out.println(\"Implementation of the sample method\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.sample();\n obj.display();\n }\n}" }, { "code": null, "e": 3497, "s": 3416, "text": "Implementation of the sample method\nDefault implementation of the display method" } ]
Ansible - Ad hoc Commands
Ad hoc commands are commands which can be run individually to perform quick functions. These commands need not be performed later. For example, you have to reboot all your company servers. For this, you will run the Adhoc commands from ‘/usr/bin/ansible’. These ad-hoc commands are not used for configuration management and deployment, because these commands are of one time usage. ansible-playbook is used for configuration management and deployment. Reboot your company server in 12 parallel forks at time. For this, we need to set up SSHagent for connection. $ ssh-agent bash $ ssh-add ~/.ssh/id_rsa To run reboot for all your company servers in a group, 'abc', in 12 parallel forks − $ Ansible abc -a "/sbin/reboot" -f 12 By default, Ansible will run the above Ad-hoc commands form current user account. If you want to change this behavior, you will have to pass the username in Ad-hoc commands as follows − $ Ansible abc -a "/sbin/reboot" -f 12 -u username You can use the Ad-hoc commands for doing SCP (Secure Copy Protocol) lots of files in parallel on multiple machines. $ Ansible abc -m copy -a "src = /etc/yum.conf dest = /tmp/yum.conf" $ Ansible abc -m file -a "dest = /path/user1/new mode = 777 owner = user1 group = user1 state = directory" $ Ansible abc -m file -a "dest = /path/user1/new state = absent" The Ad-hoc commands are available for yum and apt. Following are some Ad-hoc commands using yum. The following command checks if yum package is installed or not, but does not update it. $ Ansible abc -m yum -a "name = demo-tomcat-1 state = present" The following command check the package is not installed. $ Ansible abc -m yum -a "name = demo-tomcat-1 state = absent" The following command checks the latest version of package is installed. $ Ansible abc -m yum -a "name = demo-tomcat-1 state = latest" Facts can be used for implementing conditional statements in playbook. You can find adhoc information of all your facts through the following Ad-hoc command − $ Ansible all -m setup 41 Lectures 5 hours AR Shankar 11 Lectures 58 mins Musab Zayadneh 59 Lectures 15.5 hours Narendra P 11 Lectures 1 hours Sagar Mehta 39 Lectures 4 hours Vikas Yadav 4 Lectures 3.5 hours GreyCampus Inc. Print Add Notes Bookmark this page
[ { "code": null, "e": 1922, "s": 1791, "text": "Ad hoc commands are commands which can be run individually to perform quick functions. These commands need not be performed later." }, { "code": null, "e": 2047, "s": 1922, "text": "For example, you have to reboot all your company servers. For this, you will run the Adhoc commands from ‘/usr/bin/ansible’." }, { "code": null, "e": 2173, "s": 2047, "text": "These ad-hoc commands are not used for configuration management and deployment, because these commands are of one time usage." }, { "code": null, "e": 2243, "s": 2173, "text": "ansible-playbook is used for configuration management and deployment." }, { "code": null, "e": 2353, "s": 2243, "text": "Reboot your company server in 12 parallel forks at time. For this, we need to set up SSHagent for connection." }, { "code": null, "e": 2397, "s": 2353, "text": "$ ssh-agent bash \n$ ssh-add ~/.ssh/id_rsa \n" }, { "code": null, "e": 2482, "s": 2397, "text": "To run reboot for all your company servers in a group, 'abc', in 12 parallel forks −" }, { "code": null, "e": 2521, "s": 2482, "text": "$ Ansible abc -a \"/sbin/reboot\" -f 12\n" }, { "code": null, "e": 2707, "s": 2521, "text": "By default, Ansible will run the above Ad-hoc commands form current user account. If you want to change this behavior, you will have to pass the username in Ad-hoc commands as follows −" }, { "code": null, "e": 2758, "s": 2707, "text": "$ Ansible abc -a \"/sbin/reboot\" -f 12 -u username\n" }, { "code": null, "e": 2875, "s": 2758, "text": "You can use the Ad-hoc commands for doing SCP (Secure Copy Protocol) lots of files in parallel on multiple machines." }, { "code": null, "e": 2944, "s": 2875, "text": "$ Ansible abc -m copy -a \"src = /etc/yum.conf dest = /tmp/yum.conf\"\n" }, { "code": null, "e": 3053, "s": 2944, "text": "$ Ansible abc -m file -a \"dest = /path/user1/new mode = 777 owner = user1 group = user1 state = directory\" \n" }, { "code": null, "e": 3119, "s": 3053, "text": "$ Ansible abc -m file -a \"dest = /path/user1/new state = absent\"\n" }, { "code": null, "e": 3216, "s": 3119, "text": "The Ad-hoc commands are available for yum and apt. Following are some Ad-hoc commands using yum." }, { "code": null, "e": 3305, "s": 3216, "text": "The following command checks if yum package is installed or not, but does not update it." }, { "code": null, "e": 3369, "s": 3305, "text": "$ Ansible abc -m yum -a \"name = demo-tomcat-1 state = present\"\n" }, { "code": null, "e": 3427, "s": 3369, "text": "The following command check the package is not installed." }, { "code": null, "e": 3491, "s": 3427, "text": "$ Ansible abc -m yum -a \"name = demo-tomcat-1 state = absent\" \n" }, { "code": null, "e": 3564, "s": 3491, "text": "The following command checks the latest version of package is installed." }, { "code": null, "e": 3628, "s": 3564, "text": "$ Ansible abc -m yum -a \"name = demo-tomcat-1 state = latest\" \n" }, { "code": null, "e": 3787, "s": 3628, "text": "Facts can be used for implementing conditional statements in playbook. You can find adhoc information of all your facts through the following Ad-hoc command −" }, { "code": null, "e": 3812, "s": 3787, "text": "$ Ansible all -m setup \n" }, { "code": null, "e": 3845, "s": 3812, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 3857, "s": 3845, "text": " AR Shankar" }, { "code": null, "e": 3889, "s": 3857, "text": "\n 11 Lectures \n 58 mins\n" }, { "code": null, "e": 3905, "s": 3889, "text": " Musab Zayadneh" }, { "code": null, "e": 3941, "s": 3905, "text": "\n 59 Lectures \n 15.5 hours \n" }, { "code": null, "e": 3953, "s": 3941, "text": " Narendra P" }, { "code": null, "e": 3986, "s": 3953, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 3999, "s": 3986, "text": " Sagar Mehta" }, { "code": null, "e": 4032, "s": 3999, "text": "\n 39 Lectures \n 4 hours \n" }, { "code": null, "e": 4045, "s": 4032, "text": " Vikas Yadav" }, { "code": null, "e": 4079, "s": 4045, "text": "\n 4 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4096, "s": 4079, "text": " GreyCampus Inc." }, { "code": null, "e": 4103, "s": 4096, "text": " Print" }, { "code": null, "e": 4114, "s": 4103, "text": " Add Notes" } ]
Count of elements of an array present in every row of NxM matrix - GeeksforGeeks
26 May, 2021 Given N rows with M elements each and an array arr[] of L numbers, the task is to print the count of elements of that array present in every row of the matrix. Examples: Input: {8 27 39 589 23 23 34 589 12 45 939 32 27 12 78 23 349 48 21 32}, arr[] = {589, 39, 27} Output: 1st row - 3 2nd row - 1 3rd row - 1 4th row - 0 In 1st row, all three elements in array z[] are present In 2nd row, only 589 in array z[] are present In 3rd row, only 27 in array z[] are present In 4th row, none of the elements are present. Input: {1, 2, 3 4, 5, 6}, arr[] = {2, 3, 4} Output: 1st row - 2 2nd row - 1 A naive approach is to iterate for every element in the array arr[] and for ith row do a linear search for every element in the array arr[]. Count the number of elements and print the result for every row. Time Complexity: O(N*M*L)An efficient approach is to iterate for all the elements in the ith row of the matrix. Mark all elements using a hash table. Iterate in the array of numbers in the Z array, check if the number is present in the hash-table. Increase the count for every element present. Once all the elements are checked, print the count. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print the count of// elements present in the NxM matrix#include <bits/stdc++.h>using namespace std; // Function to print the count of// elements present in the NxM matrixvoid printCount(int a[][5], int n, int m, int z[], int l){ // iterate in the n rows for (int i = 0; i < n; i++) { // map to mark elements in N-th row unordered_map<int, int> mp; // mark all elements in the n-th row for (int j = 0; j < m; j++) mp[a[i][j]] = 1; int count = 0; // check for occurrence of all elements for (int j = 0; j < l; j++) { if (mp[z[j]]) count += 1; } // print the occurrence of all elements cout << "row" << i + 1 << " = " << count << endl; }} // Driver Codeint main(){ // NxM matrix int a[][5] = { { 8, 27, 39, 589, 23 }, { 23, 34, 589, 12, 45 }, { 939, 32, 27, 12, 78 }, { 23, 349, 48, 21, 32 } }; // elements array int arr[] = { 589, 39, 27 }; int n = sizeof(a) / sizeof(a[0]); int m = 5; int l = sizeof(arr) / sizeof(arr[0]); printCount(a, n, m, arr, l); return 0;} // Java program to print the count of// elements present in the NxM matriximport java.util.*; class GFG{ // Function to print the count of// elements present in the NxM matrixstatic void printCount(int a[][], int n, int m, int z[], int l){ // iterate in the n rows for (int i = 0; i < n; i++) { // map to mark elements in N-th row Map<Integer,Integer> mp = new HashMap<>(); // mark all elements in the n-th row for (int j = 0; j < m; j++) mp.put(a[i][j], 1); int count = 0; // check for occurrence of all elements for (int j = 0; j < l; j++) { if (mp.containsKey(z[j])) count += 1; } // print the occurrence of all elements System.out.println("row" +(i + 1) + " = " + count); }} // Driver Codepublic static void main(String[] args){ // NxM matrix int a[][] = { { 8, 27, 39, 589, 23 }, { 23, 34, 589, 12, 45 }, { 939, 32, 27, 12, 78 }, { 23, 349, 48, 21, 32 } }; // elements array int arr[] = { 589, 39, 27 }; int n = a.length; int m = 5; int l = arr.length; printCount(a, n, m, arr, l); }} // This code is contributed by 29AjayKumar # Python3 program to print the count of# elements present in the NxM matrix # Function to print the count of# elements present in the NxM matrixdef printCount(a, n, m, z, l): # iterate in the n rows for i in range(n): # map to mark elements in N-th row mp = dict() # mark all elements in the n-th row for j in range(m): mp[a[i][j]] = 1 count = 0 # check for occurrence of all elements for j in range(l): if z[j] in mp.keys(): count += 1 # print the occurrence of all elements print("row", i + 1, " = ", count ) # Driver Code # NxM matrixa = [[ 8, 27, 39, 589, 23 ], [ 23, 34, 589, 12, 45 ], [ 939, 32, 27, 12, 78 ], [ 23, 349, 48, 21, 32 ]] # elements arrayarr = [ 589, 39, 27 ] n = len(a) m = 5 l = len(arr) printCount(a, n, m, arr, l) # This code is contributed by mohit kumar 29 // C# program to print the count of// elements present in the NxM matrixusing System;using System.Collections.Generic; class GFG{ // Function to print the count of// elements present in the NxM matrixstatic void printCount(int [,]a, int n, int m, int []z, int l){ // iterate in the n rows for (int i = 0; i < n; i++) { // map to mark elements in N-th row Dictionary<int,int> mp = new Dictionary<int,int>(); // mark all elements in the n-th row for (int j = 0; j < m; j++) mp.Add(a[i,j], 1); int count = 0; // check for occurrence of all elements for (int j = 0; j < l; j++) { if (mp.ContainsKey(z[j])) count += 1; } // print the occurrence of all elements Console.WriteLine("row" +(i + 1) + " = " + count); }} // Driver Codepublic static void Main(String[] args){ // NxM matrix int [,]a = { { 8, 27, 39, 589, 23 }, { 23, 34, 589, 12, 45 }, { 939, 32, 27, 12, 78 }, { 23, 349, 48, 21, 32 } }; // elements array int []arr = { 589, 39, 27 }; int n = a.GetLength(0); int m = 5; int l = arr.Length; printCount(a, n, m, arr, l);}} /* This code is contributed by PrinciRaj1992 */ <script> // JavaScript program to print the count of// elements present in the NxM matrix // Function to print the count of// elements present in the NxM matrix function printCount(a,n,m,z,l) { // iterate in the n rows for (let i = 0; i < n; i++) { // map to mark elements in N-th row let mp = new Map(); // mark all elements in the n-th row for (let j = 0; j < m; j++) mp.set(a[i][j], 1); let count = 0; // check for occurrence of all elements for (let j = 0; j < l; j++) { if (mp.has(z[j])) count += 1; } // print the occurrence of all elements document.write("row" +(i + 1) + " = " + count+"<br>"); } } // Driver Code // NxM matrix let a = [[ 8, 27, 39, 589, 23 ], [ 23, 34, 589, 12, 45 ], [ 939, 32, 27, 12, 78 ], [ 23, 349, 48, 21, 32 ]]; // elements array let arr=[ 589, 39, 27]; let n = a.length; let m = 5; let l = arr.length; printCount(a, n, m, arr, l); // This code is contributed by patel2127 </script> row1 = 3 row2 = 1 row3 = 1 row4 = 0 Time Complexity: O(N*M) mohit kumar 29 29AjayKumar princiraj1992 Akanksha_Rai patel2127 Algorithms-Searching Arrays cpp-unordered_map Hash Matrix Arrays Hash Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Sudoku | Backtracking-7 Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 Min Cost Path | DP-6 The Celebrity Problem Count all possible paths from top left to bottom right of a mXn matrix Python program to multiply two matrices Rotate a matrix by 90 degree in clockwise direction without using any extra space Printing all solutions in N-Queen Problem
[ { "code": null, "e": 25420, "s": 25392, "text": "\n26 May, 2021" }, { "code": null, "e": 25592, "s": 25420, "text": "Given N rows with M elements each and an array arr[] of L numbers, the task is to print the count of elements of that array present in every row of the matrix. Examples: " }, { "code": null, "e": 26115, "s": 25592, "text": "Input: {8 27 39 589 23\n 23 34 589 12 45\n 939 32 27 12 78\n 23 349 48 21 32}, \n \n arr[] = {589, 39, 27}\n\nOutput: 1st row - 3\n 2nd row - 1\n 3rd row - 1 \n 4th row - 0\nIn 1st row, all three elements in array z[] are present\nIn 2nd row, only 589 in array z[] are present\nIn 3rd row, only 27 in array z[] are present \nIn 4th row, none of the elements are present. \n\nInput: {1, 2, 3\n 4, 5, 6}, \n \n arr[] = {2, 3, 4}\n\nOutput: 1st row - 2\n 2nd row - 1" }, { "code": null, "e": 26722, "s": 26117, "text": "A naive approach is to iterate for every element in the array arr[] and for ith row do a linear search for every element in the array arr[]. Count the number of elements and print the result for every row. Time Complexity: O(N*M*L)An efficient approach is to iterate for all the elements in the ith row of the matrix. Mark all elements using a hash table. Iterate in the array of numbers in the Z array, check if the number is present in the hash-table. Increase the count for every element present. Once all the elements are checked, print the count. Below is the implementation of the above approach: " }, { "code": null, "e": 26726, "s": 26722, "text": "C++" }, { "code": null, "e": 26731, "s": 26726, "text": "Java" }, { "code": null, "e": 26739, "s": 26731, "text": "Python3" }, { "code": null, "e": 26742, "s": 26739, "text": "C#" }, { "code": null, "e": 26753, "s": 26742, "text": "Javascript" }, { "code": "// C++ program to print the count of// elements present in the NxM matrix#include <bits/stdc++.h>using namespace std; // Function to print the count of// elements present in the NxM matrixvoid printCount(int a[][5], int n, int m, int z[], int l){ // iterate in the n rows for (int i = 0; i < n; i++) { // map to mark elements in N-th row unordered_map<int, int> mp; // mark all elements in the n-th row for (int j = 0; j < m; j++) mp[a[i][j]] = 1; int count = 0; // check for occurrence of all elements for (int j = 0; j < l; j++) { if (mp[z[j]]) count += 1; } // print the occurrence of all elements cout << \"row\" << i + 1 << \" = \" << count << endl; }} // Driver Codeint main(){ // NxM matrix int a[][5] = { { 8, 27, 39, 589, 23 }, { 23, 34, 589, 12, 45 }, { 939, 32, 27, 12, 78 }, { 23, 349, 48, 21, 32 } }; // elements array int arr[] = { 589, 39, 27 }; int n = sizeof(a) / sizeof(a[0]); int m = 5; int l = sizeof(arr) / sizeof(arr[0]); printCount(a, n, m, arr, l); return 0;}", "e": 27932, "s": 26753, "text": null }, { "code": "// Java program to print the count of// elements present in the NxM matriximport java.util.*; class GFG{ // Function to print the count of// elements present in the NxM matrixstatic void printCount(int a[][], int n, int m, int z[], int l){ // iterate in the n rows for (int i = 0; i < n; i++) { // map to mark elements in N-th row Map<Integer,Integer> mp = new HashMap<>(); // mark all elements in the n-th row for (int j = 0; j < m; j++) mp.put(a[i][j], 1); int count = 0; // check for occurrence of all elements for (int j = 0; j < l; j++) { if (mp.containsKey(z[j])) count += 1; } // print the occurrence of all elements System.out.println(\"row\" +(i + 1) + \" = \" + count); }} // Driver Codepublic static void main(String[] args){ // NxM matrix int a[][] = { { 8, 27, 39, 589, 23 }, { 23, 34, 589, 12, 45 }, { 939, 32, 27, 12, 78 }, { 23, 349, 48, 21, 32 } }; // elements array int arr[] = { 589, 39, 27 }; int n = a.length; int m = 5; int l = arr.length; printCount(a, n, m, arr, l); }} // This code is contributed by 29AjayKumar", "e": 29211, "s": 27932, "text": null }, { "code": "# Python3 program to print the count of# elements present in the NxM matrix # Function to print the count of# elements present in the NxM matrixdef printCount(a, n, m, z, l): # iterate in the n rows for i in range(n): # map to mark elements in N-th row mp = dict() # mark all elements in the n-th row for j in range(m): mp[a[i][j]] = 1 count = 0 # check for occurrence of all elements for j in range(l): if z[j] in mp.keys(): count += 1 # print the occurrence of all elements print(\"row\", i + 1, \" = \", count ) # Driver Code # NxM matrixa = [[ 8, 27, 39, 589, 23 ], [ 23, 34, 589, 12, 45 ], [ 939, 32, 27, 12, 78 ], [ 23, 349, 48, 21, 32 ]] # elements arrayarr = [ 589, 39, 27 ] n = len(a) m = 5 l = len(arr) printCount(a, n, m, arr, l) # This code is contributed by mohit kumar 29", "e": 30163, "s": 29211, "text": null }, { "code": "// C# program to print the count of// elements present in the NxM matrixusing System;using System.Collections.Generic; class GFG{ // Function to print the count of// elements present in the NxM matrixstatic void printCount(int [,]a, int n, int m, int []z, int l){ // iterate in the n rows for (int i = 0; i < n; i++) { // map to mark elements in N-th row Dictionary<int,int> mp = new Dictionary<int,int>(); // mark all elements in the n-th row for (int j = 0; j < m; j++) mp.Add(a[i,j], 1); int count = 0; // check for occurrence of all elements for (int j = 0; j < l; j++) { if (mp.ContainsKey(z[j])) count += 1; } // print the occurrence of all elements Console.WriteLine(\"row\" +(i + 1) + \" = \" + count); }} // Driver Codepublic static void Main(String[] args){ // NxM matrix int [,]a = { { 8, 27, 39, 589, 23 }, { 23, 34, 589, 12, 45 }, { 939, 32, 27, 12, 78 }, { 23, 349, 48, 21, 32 } }; // elements array int []arr = { 589, 39, 27 }; int n = a.GetLength(0); int m = 5; int l = arr.Length; printCount(a, n, m, arr, l);}} /* This code is contributed by PrinciRaj1992 */", "e": 31471, "s": 30163, "text": null }, { "code": "<script> // JavaScript program to print the count of// elements present in the NxM matrix // Function to print the count of// elements present in the NxM matrix function printCount(a,n,m,z,l) { // iterate in the n rows for (let i = 0; i < n; i++) { // map to mark elements in N-th row let mp = new Map(); // mark all elements in the n-th row for (let j = 0; j < m; j++) mp.set(a[i][j], 1); let count = 0; // check for occurrence of all elements for (let j = 0; j < l; j++) { if (mp.has(z[j])) count += 1; } // print the occurrence of all elements document.write(\"row\" +(i + 1) + \" = \" + count+\"<br>\"); } } // Driver Code // NxM matrix let a = [[ 8, 27, 39, 589, 23 ], [ 23, 34, 589, 12, 45 ], [ 939, 32, 27, 12, 78 ], [ 23, 349, 48, 21, 32 ]]; // elements array let arr=[ 589, 39, 27]; let n = a.length; let m = 5; let l = arr.length; printCount(a, n, m, arr, l); // This code is contributed by patel2127 </script>", "e": 32629, "s": 31471, "text": null }, { "code": null, "e": 32665, "s": 32629, "text": "row1 = 3\nrow2 = 1\nrow3 = 1\nrow4 = 0" }, { "code": null, "e": 32692, "s": 32667, "text": "Time Complexity: O(N*M) " }, { "code": null, "e": 32707, "s": 32692, "text": "mohit kumar 29" }, { "code": null, "e": 32719, "s": 32707, "text": "29AjayKumar" }, { "code": null, "e": 32733, "s": 32719, "text": "princiraj1992" }, { "code": null, "e": 32746, "s": 32733, "text": "Akanksha_Rai" }, { "code": null, "e": 32756, "s": 32746, "text": "patel2127" }, { "code": null, "e": 32777, "s": 32756, "text": "Algorithms-Searching" }, { "code": null, "e": 32784, "s": 32777, "text": "Arrays" }, { "code": null, "e": 32802, "s": 32784, "text": "cpp-unordered_map" }, { "code": null, "e": 32807, "s": 32802, "text": "Hash" }, { "code": null, "e": 32814, "s": 32807, "text": "Matrix" }, { "code": null, "e": 32821, "s": 32814, "text": "Arrays" }, { "code": null, "e": 32826, "s": 32821, "text": "Hash" }, { "code": null, "e": 32833, "s": 32826, "text": "Matrix" }, { "code": null, "e": 32931, "s": 32833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32940, "s": 32931, "text": "Comments" }, { "code": null, "e": 32953, "s": 32940, "text": "Old Comments" }, { "code": null, "e": 33015, "s": 32953, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 33039, "s": 33015, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 33072, "s": 33039, "text": "Program to multiply two matrices" }, { "code": null, "e": 33123, "s": 33072, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 33144, "s": 33123, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 33166, "s": 33144, "text": "The Celebrity Problem" }, { "code": null, "e": 33237, "s": 33166, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 33277, "s": 33237, "text": "Python program to multiply two matrices" }, { "code": null, "e": 33359, "s": 33277, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" } ]
MySQL query to extract first word from a field?
To extract first word from a field, use in-built SUBSTRING_INDEX() function. The syntax is as follows − SELECT SUBSTRING_INDEX(yourColumnName,’ ‘,1) as anyVariableName from yourTableName; In the above query, if you use -1 in place of 1 then you will get the last word. To understand the above concept, let us create a table. The following is the query to create a table. mysql> create table FirstWordDemo −> ( −> AllWords longtext −> ); Query OK, 0 rows affected (0.83 sec) Now insert some words in the table using insert command. The query is as follows − mysql> insert into FirstWordDemo values('This is the first MySQL Query'); Query OK, 1 row affected (0.11 sec) mysql> insert into FirstWordDemo values('MySQL is a Relational Database'); Query OK, 1 row affected (0.17 sec) mysql> insert into FirstWordDemo values('FirstWord is not correct'); Query OK, 1 row affected (0.21 sec) Now display all records from the table using select statement. The query is as follows − mysql> select *from FirstWordDemo; The following is the output − +--------------------------------+ | AllWords | +--------------------------------+ | This is the first MySQL Query | | MySQL is a Relational Database | | FirstWord is not correct | +--------------------------------+ 3 rows in set (0.00 sec) Here is the query to get first word from a field. We discussed the same syntax in the beginning. The following is the query − mysql> select SUBSTRING_INDEX(AllWords, ' ', 1) as MyFirstWordResult from FirstWordDemo; The following is the output − +-------------------+ | MyFirstWordResult | +-------------------+ | This | | MySQL | | FirstWord | +-------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1166, "s": 1062, "text": "To extract first word from a field, use in-built SUBSTRING_INDEX() function. The syntax is as follows −" }, { "code": null, "e": 1250, "s": 1166, "text": "SELECT SUBSTRING_INDEX(yourColumnName,’ ‘,1) as anyVariableName from yourTableName;" }, { "code": null, "e": 1433, "s": 1250, "text": "In the above query, if you use -1 in place of 1 then you will get the last word. To understand the above concept, let us create a table. The following is the query to create a table." }, { "code": null, "e": 1545, "s": 1433, "text": "mysql> create table FirstWordDemo\n −> (\n −> AllWords longtext\n −> );\nQuery OK, 0 rows affected (0.83 sec)" }, { "code": null, "e": 1628, "s": 1545, "text": "Now insert some words in the table using insert command. The query is as follows −" }, { "code": null, "e": 1956, "s": 1628, "text": "mysql> insert into FirstWordDemo values('This is the first MySQL Query');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into FirstWordDemo values('MySQL is a Relational Database');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into FirstWordDemo values('FirstWord is not correct');\nQuery OK, 1 row affected (0.21 sec)" }, { "code": null, "e": 2045, "s": 1956, "text": "Now display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2080, "s": 2045, "text": "mysql> select *from FirstWordDemo;" }, { "code": null, "e": 2110, "s": 2080, "text": "The following is the output −" }, { "code": null, "e": 2380, "s": 2110, "text": "+--------------------------------+\n| AllWords |\n+--------------------------------+\n| This is the first MySQL Query |\n| MySQL is a Relational Database |\n| FirstWord is not correct |\n+--------------------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2477, "s": 2380, "text": "Here is the query to get first word from a field. We discussed the same syntax in the beginning." }, { "code": null, "e": 2506, "s": 2477, "text": "The following is the query −" }, { "code": null, "e": 2595, "s": 2506, "text": "mysql> select SUBSTRING_INDEX(AllWords, ' ', 1) as MyFirstWordResult from FirstWordDemo;" }, { "code": null, "e": 2625, "s": 2595, "text": "The following is the output −" }, { "code": null, "e": 2804, "s": 2625, "text": "+-------------------+\n| MyFirstWordResult |\n+-------------------+\n| This |\n| MySQL |\n| FirstWord |\n+-------------------+\n3 rows in set (0.00 sec)" } ]
How to Launch Jupyter Notebook Quickly | by Benjamin Dornel | Towards Data Science
Jupyter Notebook is a great tool for data science but can be pretty slow if you constantly need to navigate through multiple directories before launching a notebook file, or if you’re using a clunky GUI like Anaconda Navigator to get to your files. Today, I’ll be covering how to use Windows File Explorer, Command Prompt and PowerShell via Windows Terminal to quickly navigate to your directory of choice and launch Jupyter Notebook. (If you’re using MacOS, you can look into setting up an automator script or bash alias). Here are two ways that you can drastically cut down on time wasted navigating through folders and files. Whenever you open a Windows Explorer folder, you’ll see an address bar similar to that in a web browser. By default, it shows the path of the current folder. In this address bar, you can enter in text and navigate to other directories manually. Once you’ve entered your specific folder with Windows Explorer, you can simply press ALT + D, type in cmd and press Enter. You can then type jupyter notebook to launch Jupyter Notebook within that specific folder. NOTE: If you’re using Anaconda, you may have to type activate conda to switch to Anaconda Prompt within Command Prompt. Additionally, if you receive an error involving zqm.h, you’ll need to add the following folders to your PATH environment variable: C:\Users\***\Anaconda3\Lib\site-packages\zmq C:\Users\***\Anaconda3\Library\bin This method is slightly more complicated but is much faster and much more versatile. In this section, I’ll explain how to use Windows Terminal to access PowerShell and set up custom aliases. Let me unpack that last sentence a bit: Windows Terminal is basically a modern terminal application that allows us to use command-line tools and shells like Command Prompt. Some key features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering engine, and the ability to customize text, colors, backgrounds, and shortcuts. A guide to set this up with Anaconda Prompt can be found here. PowerShell is a command-line tool like Command Prompt, except that it gives us the ability to do in-depth system management among several other handy abilities. An alias is basically a console command shortcut. For example, instead of typing out Set-Location in PowerShell, you can type cd or chdir to change directories quickly. PowerShell allows you to create custom aliases, which is what we’ll do here. With a custom alias, you can launch Jupyter Notebook by simply typing jn instead of jupyter notebook. You can also navigate to directories with this. For example, I can type cdp3 instead of something like cd C:\Users\***\OneDrive\Desktop\General Assembly\Project3. To set this up, you’ll first need to install Windows Terminal. This step is optional, but I prefer using Windows Terminal over stand-alone PowerShell due to the functionality that it offers (Windows Terminal is also much better looking). A guide to set this up with Anaconda Prompt can be found here. Next, you’ll want to create a PowerShell profile. This is where we’ll be storing our shortcut commands, which are more formally known as ‘aliases’. To create a profile, launch PowerShell and enter the following command: New-Item -Type File -Force $PROFILE. This will create a profile within your UserProfile\Documents folder. You can check the path of your profile by typing $PROFILE in PowerShell. You can then open this file with PowerShell by typing ise $PROFILE or by manually opening this file with your preferred code editor. You’ll first want to create a shortcut to your most frequently used directory such as: function Get-GeneralAssemblyProjects{ & cd ‘~\OneDrive\Desktop\General Assembly\Project3’ }New-Alias -Name cdp3 -Value Get-GeneralAssemblyProjects From there, you’ll want to add something like the following to your PowerShell profile: function Start-JupyterNotebook { & $ENV:UserProfile\Anaconda3\python.exe $ENV:UserProfile\Anaconda3\cwp.py $ENV:UserProfile\Anaconda3 $ENV:UserProfile\Anaconda3\python.exe $ENV:UserProfile\Anaconda3\Scripts\jupyter-notebook-script.py $pwd}New-Alias -Name jn -Value Start-JupyterNotebook This will allow you to start Jupyter Notebook by typing jn. You can change this alias to anything else, like >j and so on. To launch Windows Terminal, you can use Win + R and type wt. There are tons more you can do with aliases, such as setting custom Git commands like the following: function Get-GitStatus { & git status $args }New-Alias -Name gs -Value Get-GitStatus The possibilities are pretty endless with aliases. Hope this helps you out!
[ { "code": null, "e": 420, "s": 171, "text": "Jupyter Notebook is a great tool for data science but can be pretty slow if you constantly need to navigate through multiple directories before launching a notebook file, or if you’re using a clunky GUI like Anaconda Navigator to get to your files." }, { "code": null, "e": 695, "s": 420, "text": "Today, I’ll be covering how to use Windows File Explorer, Command Prompt and PowerShell via Windows Terminal to quickly navigate to your directory of choice and launch Jupyter Notebook. (If you’re using MacOS, you can look into setting up an automator script or bash alias)." }, { "code": null, "e": 800, "s": 695, "text": "Here are two ways that you can drastically cut down on time wasted navigating through folders and files." }, { "code": null, "e": 1045, "s": 800, "text": "Whenever you open a Windows Explorer folder, you’ll see an address bar similar to that in a web browser. By default, it shows the path of the current folder. In this address bar, you can enter in text and navigate to other directories manually." }, { "code": null, "e": 1259, "s": 1045, "text": "Once you’ve entered your specific folder with Windows Explorer, you can simply press ALT + D, type in cmd and press Enter. You can then type jupyter notebook to launch Jupyter Notebook within that specific folder." }, { "code": null, "e": 1510, "s": 1259, "text": "NOTE: If you’re using Anaconda, you may have to type activate conda to switch to Anaconda Prompt within Command Prompt. Additionally, if you receive an error involving zqm.h, you’ll need to add the following folders to your PATH environment variable:" }, { "code": null, "e": 1555, "s": 1510, "text": "C:\\Users\\***\\Anaconda3\\Lib\\site-packages\\zmq" }, { "code": null, "e": 1590, "s": 1555, "text": "C:\\Users\\***\\Anaconda3\\Library\\bin" }, { "code": null, "e": 1781, "s": 1590, "text": "This method is slightly more complicated but is much faster and much more versatile. In this section, I’ll explain how to use Windows Terminal to access PowerShell and set up custom aliases." }, { "code": null, "e": 1821, "s": 1781, "text": "Let me unpack that last sentence a bit:" }, { "code": null, "e": 2214, "s": 1821, "text": "Windows Terminal is basically a modern terminal application that allows us to use command-line tools and shells like Command Prompt. Some key features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering engine, and the ability to customize text, colors, backgrounds, and shortcuts. A guide to set this up with Anaconda Prompt can be found here." }, { "code": null, "e": 2375, "s": 2214, "text": "PowerShell is a command-line tool like Command Prompt, except that it gives us the ability to do in-depth system management among several other handy abilities." }, { "code": null, "e": 2544, "s": 2375, "text": "An alias is basically a console command shortcut. For example, instead of typing out Set-Location in PowerShell, you can type cd or chdir to change directories quickly." }, { "code": null, "e": 2886, "s": 2544, "text": "PowerShell allows you to create custom aliases, which is what we’ll do here. With a custom alias, you can launch Jupyter Notebook by simply typing jn instead of jupyter notebook. You can also navigate to directories with this. For example, I can type cdp3 instead of something like cd C:\\Users\\***\\OneDrive\\Desktop\\General Assembly\\Project3." }, { "code": null, "e": 3187, "s": 2886, "text": "To set this up, you’ll first need to install Windows Terminal. This step is optional, but I prefer using Windows Terminal over stand-alone PowerShell due to the functionality that it offers (Windows Terminal is also much better looking). A guide to set this up with Anaconda Prompt can be found here." }, { "code": null, "e": 3586, "s": 3187, "text": "Next, you’ll want to create a PowerShell profile. This is where we’ll be storing our shortcut commands, which are more formally known as ‘aliases’. To create a profile, launch PowerShell and enter the following command: New-Item -Type File -Force $PROFILE. This will create a profile within your UserProfile\\Documents folder. You can check the path of your profile by typing $PROFILE in PowerShell." }, { "code": null, "e": 3719, "s": 3586, "text": "You can then open this file with PowerShell by typing ise $PROFILE or by manually opening this file with your preferred code editor." }, { "code": null, "e": 3806, "s": 3719, "text": "You’ll first want to create a shortcut to your most frequently used directory such as:" }, { "code": null, "e": 3953, "s": 3806, "text": "function Get-GeneralAssemblyProjects{ & cd ‘~\\OneDrive\\Desktop\\General Assembly\\Project3’ }New-Alias -Name cdp3 -Value Get-GeneralAssemblyProjects" }, { "code": null, "e": 4041, "s": 3953, "text": "From there, you’ll want to add something like the following to your PowerShell profile:" }, { "code": null, "e": 4328, "s": 4041, "text": "function Start-JupyterNotebook { & $ENV:UserProfile\\Anaconda3\\python.exe $ENV:UserProfile\\Anaconda3\\cwp.py $ENV:UserProfile\\Anaconda3 $ENV:UserProfile\\Anaconda3\\python.exe $ENV:UserProfile\\Anaconda3\\Scripts\\jupyter-notebook-script.py $pwd}New-Alias -Name jn -Value Start-JupyterNotebook" }, { "code": null, "e": 4451, "s": 4328, "text": "This will allow you to start Jupyter Notebook by typing jn. You can change this alias to anything else, like >j and so on." }, { "code": null, "e": 4512, "s": 4451, "text": "To launch Windows Terminal, you can use Win + R and type wt." }, { "code": null, "e": 4613, "s": 4512, "text": "There are tons more you can do with aliases, such as setting custom Git commands like the following:" }, { "code": null, "e": 4698, "s": 4613, "text": "function Get-GitStatus { & git status $args }New-Alias -Name gs -Value Get-GitStatus" }, { "code": null, "e": 4749, "s": 4698, "text": "The possibilities are pretty endless with aliases." } ]
Convert a 1D array to a 2D Numpy array
13 Jan, 2021 Numpy is a Python package that consists of multidimensional array objects and a collection of operations or routines to perform various operations on the array and processing of the array. This package consists of a function called numpy.reshape which is used to convert a 1-D array into a 2-D array of required dimensions (n x m). This function gives a new required shape without changing the data of the 1-D array. Syntax: numpy.reshape(array, new_shape, order) Parameters: array: is the given 1-D array that will be given a new shape or converted into 2-D array new_shape: is the required shape or 2-D array having int or tuple of int order: ‘C’ for C style, ‘F’ for Fortran style, ‘A’ if data is in Fortran style then Fortran like order else C style. Examples 1: Python3 import numpy as np# 1-D array having elements [1 2 3 4 5 6 7 8]arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # Print the 1-D arrayprint ('Before reshaping:')print (arr)print ('\n') # Now we can convert this 1-D array into 2-D in two ways # 1. having dimension 4 x 2arr1 = arr.reshape(4, 2)print ('After reshaping having dimension 4x2:')print (arr1)print ('\n') # 2. having dimension 2 x 4arr2 = arr.reshape(2, 4)print ('After reshaping having dimension 2x4:')print (arr2)print ('\n') Output: Before reshaping: [1 2 3 4 5 6 7 8] After reshaping having dimension 4x2: [[1 2] [3 4] [5 6] [7 8]] After reshaping having dimension 2x4: [[1 2 3 4] [5 6 7 8]] Example 2: Let us see an important observation that whether we can reshape a 1-D array into any 2-D array. Python3 import numpy as np# 1-D array having elements [1 2 3 4 5 6 7 8]arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # Print the 1-D arrayprint('Before reshaping:')print(arr)print('\n') # let us try to convert into 2-D array having dimension 3x3arr1 = arr.reshape(3, 3)print('After reshaping having dimension 3x3:')print(arr1)print('\n') Output: This concludes that the number of elements should be equal to the product of dimension i.e. 3×3=9 but total elements = 8; Example 3: Another example is that we can use the reshape method without specifying the exact number for one of the dimensions. Just pass -1 as the value and NumPy will calculate the number. Python3 import numpy as np# 1-D array having elements [1 2 3 4 5 6 7 8]arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # Print the 1-D arrayprint('Before reshaping:')print(arr)print('\n') arr1 = arr.reshape(2, 2, -1)print('After reshaping:')print(arr1)print('\n') Output: Before reshaping: [1 2 3 4 5 6 7 8] After reshaping: [[[1 2] [3 4]] [[5 6] [7 8]]] Picked Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jan, 2021" }, { "code": null, "e": 470, "s": 52, "text": "Numpy is a Python package that consists of multidimensional array objects and a collection of operations or routines to perform various operations on the array and processing of the array. This package consists of a function called numpy.reshape which is used to convert a 1-D array into a 2-D array of required dimensions (n x m). This function gives a new required shape without changing the data of the 1-D array." }, { "code": null, "e": 518, "s": 470, "text": "Syntax: numpy.reshape(array, new_shape, order) " }, { "code": null, "e": 530, "s": 518, "text": "Parameters:" }, { "code": null, "e": 620, "s": 530, "text": " array: is the given 1-D array that will be given a new shape or converted into 2-D array" }, { "code": null, "e": 693, "s": 620, "text": "new_shape: is the required shape or 2-D array having int or tuple of int" }, { "code": null, "e": 810, "s": 693, "text": "order: ‘C’ for C style, ‘F’ for Fortran style, ‘A’ if data is in Fortran style then Fortran like order else C style." }, { "code": null, "e": 822, "s": 810, "text": "Examples 1:" }, { "code": null, "e": 830, "s": 822, "text": "Python3" }, { "code": "import numpy as np# 1-D array having elements [1 2 3 4 5 6 7 8]arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # Print the 1-D arrayprint ('Before reshaping:')print (arr)print ('\\n') # Now we can convert this 1-D array into 2-D in two ways # 1. having dimension 4 x 2arr1 = arr.reshape(4, 2)print ('After reshaping having dimension 4x2:')print (arr1)print ('\\n') # 2. having dimension 2 x 4arr2 = arr.reshape(2, 4)print ('After reshaping having dimension 2x4:')print (arr2)print ('\\n')", "e": 1313, "s": 830, "text": null }, { "code": null, "e": 1321, "s": 1313, "text": "Output:" }, { "code": null, "e": 1485, "s": 1321, "text": "Before reshaping:\n[1 2 3 4 5 6 7 8]\nAfter reshaping having dimension 4x2:\n[[1 2]\n [3 4]\n [5 6]\n [7 8]]\nAfter reshaping having dimension 2x4:\n[[1 2 3 4]\n [5 6 7 8]]" }, { "code": null, "e": 1592, "s": 1485, "text": "Example 2: Let us see an important observation that whether we can reshape a 1-D array into any 2-D array." }, { "code": null, "e": 1600, "s": 1592, "text": "Python3" }, { "code": "import numpy as np# 1-D array having elements [1 2 3 4 5 6 7 8]arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # Print the 1-D arrayprint('Before reshaping:')print(arr)print('\\n') # let us try to convert into 2-D array having dimension 3x3arr1 = arr.reshape(3, 3)print('After reshaping having dimension 3x3:')print(arr1)print('\\n')", "e": 1927, "s": 1600, "text": null }, { "code": null, "e": 1935, "s": 1927, "text": "Output:" }, { "code": null, "e": 2057, "s": 1935, "text": "This concludes that the number of elements should be equal to the product of dimension i.e. 3×3=9 but total elements = 8;" }, { "code": null, "e": 2248, "s": 2057, "text": "Example 3: Another example is that we can use the reshape method without specifying the exact number for one of the dimensions. Just pass -1 as the value and NumPy will calculate the number." }, { "code": null, "e": 2256, "s": 2248, "text": "Python3" }, { "code": "import numpy as np# 1-D array having elements [1 2 3 4 5 6 7 8]arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # Print the 1-D arrayprint('Before reshaping:')print(arr)print('\\n') arr1 = arr.reshape(2, 2, -1)print('After reshaping:')print(arr1)print('\\n')", "e": 2509, "s": 2256, "text": null }, { "code": null, "e": 2517, "s": 2509, "text": "Output:" }, { "code": null, "e": 2602, "s": 2517, "text": "Before reshaping:\n[1 2 3 4 5 6 7 8]\nAfter reshaping:\n[[[1 2]\n [3 4]]\n[[5 6]\n [7 8]]]" }, { "code": null, "e": 2609, "s": 2602, "text": "Picked" }, { "code": null, "e": 2640, "s": 2609, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 2653, "s": 2640, "text": "Python-numpy" }, { "code": null, "e": 2660, "s": 2653, "text": "Python" } ]
Lightweight Directory Access Protocol (LDAP)
21 Jun, 2019 Lightweight Directory Access Protocol (LDAP) is an internet protocol works on TCP/IP, used to access information from directories. LDAP protocol is basically used to access an active directory. Features of LDAP: Functional model of LDAP is simpler due to this it omits duplicate, rarely used and esoteric feature.It is easier to understand and implement.It uses strings to represent data Functional model of LDAP is simpler due to this it omits duplicate, rarely used and esoteric feature. It is easier to understand and implement. It uses strings to represent data Directories:Directories are set of object with similar attributes, organised in a logical and hierarchical manner. For example, Telephonic Directories. It is a distributed database application used to manage attributes in a directory. LDAP defines operations for accessing and modifying directory entries such as: Searching for user specified criteria Adding an entry Deleting an entry Modifying an entry Modifying the distinguished name or relative distinguished name of an entry Comparing an entry LDAP Models:LDAP can be explained by using four models upon which it based: Information Model:This model describes structure of information stored in an LDAP Directory.In this basic information is stored in directory is called an entity. Entries here represents object of interest in real world such as people, server, organization, etc. Entries contain collection of attributes that contain information about object.Every attribute has a type and one or more values. Here types of attribute is associated with syntax and syntax specifies what kind of values can be storedNaming Model:This model describes how information in an LDAP Directory is organized and identified. In this entries are organized in a Tree-Like structure called Directory Information Tree (DIT). Entries are arranged within DIT based on their distinguished name DN. DN is a unique name that unambiguously identifies a single entry.Functional Model:LDAP defines operations for accessing and modifying directory entries . In this we discuss about LDAP operations in a programming language independent manner LDAP operations can be divided into following categories:• Query • Update • Authentication Security Model:This model describes how information in LDAP directory can be protected from unauthorized access. It is based on BIND operation. There are several bind operation can be performed. Information Model:This model describes structure of information stored in an LDAP Directory.In this basic information is stored in directory is called an entity. Entries here represents object of interest in real world such as people, server, organization, etc. Entries contain collection of attributes that contain information about object.Every attribute has a type and one or more values. Here types of attribute is associated with syntax and syntax specifies what kind of values can be stored Naming Model:This model describes how information in an LDAP Directory is organized and identified. In this entries are organized in a Tree-Like structure called Directory Information Tree (DIT). Entries are arranged within DIT based on their distinguished name DN. DN is a unique name that unambiguously identifies a single entry. Functional Model:LDAP defines operations for accessing and modifying directory entries . In this we discuss about LDAP operations in a programming language independent manner LDAP operations can be divided into following categories:• Query • Update • Authentication • Query • Update • Authentication Security Model:This model describes how information in LDAP directory can be protected from unauthorized access. It is based on BIND operation. There are several bind operation can be performed. LDAP Client and Server Interaction:It is quite similar to any other client-server interaction. In this client performs protocol functions against server.The interaction takes place as follows:- A protocol request is send to server by client.Server perform operations on directory such as search, update, delete, etc.The response is sent back to the client. A protocol request is send to server by client. Server perform operations on directory such as search, update, delete, etc. The response is sent back to the client. Microsoft, Open LDAP, Sun, etc can easily be made an LDAP server. if the user don’t want to install directory service but want to use LDAP instruction for available LDAP server then user can use four11, bigfoot etc. Making an LDAP client is quite simple as there are SDK’s in many programming languages such as C, C++, Perl, Java, etc. User has to perform certain task to be LDAP client: (i) Go get SDK for your language (ii) Use function of SDK to connect to LDAP (iii) Operate on LDAP LDAP functions / operations: (a) For Authentication:It includes bind, unbind and abandon operations used to connect and disconnect to and from an LDAP server, establish access rights and protect information. In authentication, client session is established and ended using the functions-> BIND/UNBIND -> Abandon -> BIND/UNBIND -> Abandon (b) For Query:It includes search and compare operations used to retrieve information from a directory. In query, server performs action using function-> Search -> Compare Entry -> Search -> Compare Entry (c) For Update:It includes add, delete, modify and modify RDN operations used to update stored information in a directory. In update, we can make changes in directories by using function-> Add an entry -> Delete an entry -> Modify an entry -> Add an entry -> Delete an entry -> Modify an entry Client establishes session with server (BIND) using Hostname/IP/and Port Number. For security purposes, user set USER-ID and Password based authentication. Server perform operations such as read, update, search, etc. Client end session using UNBIND or Abandon function. Advantages of LDAP: Data present in LDAP is available to many clients and libraries. LDAP support many types of application. LDAP is very general and has basic security. Disadvantages in LDAP:It does not handle well relational database. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol Differences between TCP and UDP Mobile Internet Protocol (or Mobile IP) GSM in Wireless Communication Types of Network Topology Differences between IPv4 and IPv6 RSA Algorithm in Cryptography TCP Server-Client implementation in C Secure Socket Layer (SSL) Socket Programming in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2019" }, { "code": null, "e": 222, "s": 28, "text": "Lightweight Directory Access Protocol (LDAP) is an internet protocol works on TCP/IP, used to access information from directories. LDAP protocol is basically used to access an active directory." }, { "code": null, "e": 240, "s": 222, "text": "Features of LDAP:" }, { "code": null, "e": 416, "s": 240, "text": "Functional model of LDAP is simpler due to this it omits duplicate, rarely used and esoteric feature.It is easier to understand and implement.It uses strings to represent data" }, { "code": null, "e": 518, "s": 416, "text": "Functional model of LDAP is simpler due to this it omits duplicate, rarely used and esoteric feature." }, { "code": null, "e": 560, "s": 518, "text": "It is easier to understand and implement." }, { "code": null, "e": 594, "s": 560, "text": "It uses strings to represent data" }, { "code": null, "e": 829, "s": 594, "text": "Directories:Directories are set of object with similar attributes, organised in a logical and hierarchical manner. For example, Telephonic Directories. It is a distributed database application used to manage attributes in a directory." }, { "code": null, "e": 908, "s": 829, "text": "LDAP defines operations for accessing and modifying directory entries such as:" }, { "code": null, "e": 946, "s": 908, "text": "Searching for user specified criteria" }, { "code": null, "e": 962, "s": 946, "text": "Adding an entry" }, { "code": null, "e": 980, "s": 962, "text": "Deleting an entry" }, { "code": null, "e": 999, "s": 980, "text": "Modifying an entry" }, { "code": null, "e": 1075, "s": 999, "text": "Modifying the distinguished name or relative distinguished name of an entry" }, { "code": null, "e": 1094, "s": 1075, "text": "Comparing an entry" }, { "code": null, "e": 1170, "s": 1094, "text": "LDAP Models:LDAP can be explained by using four models upon which it based:" }, { "code": null, "e": 2459, "s": 1170, "text": "Information Model:This model describes structure of information stored in an LDAP Directory.In this basic information is stored in directory is called an entity. Entries here represents object of interest in real world such as people, server, organization, etc. Entries contain collection of attributes that contain information about object.Every attribute has a type and one or more values. Here types of attribute is associated with syntax and syntax specifies what kind of values can be storedNaming Model:This model describes how information in an LDAP Directory is organized and identified. In this entries are organized in a Tree-Like structure called Directory Information Tree (DIT). Entries are arranged within DIT based on their distinguished name DN. DN is a unique name that unambiguously identifies a single entry.Functional Model:LDAP defines operations for accessing and modifying directory entries . In this we discuss about LDAP operations in a programming language independent manner LDAP operations can be divided into following categories:• Query\n• Update \n• Authentication Security Model:This model describes how information in LDAP directory can be protected from unauthorized access. It is based on BIND operation. There are several bind operation can be performed." }, { "code": null, "e": 2956, "s": 2459, "text": "Information Model:This model describes structure of information stored in an LDAP Directory.In this basic information is stored in directory is called an entity. Entries here represents object of interest in real world such as people, server, organization, etc. Entries contain collection of attributes that contain information about object.Every attribute has a type and one or more values. Here types of attribute is associated with syntax and syntax specifies what kind of values can be stored" }, { "code": null, "e": 3288, "s": 2956, "text": "Naming Model:This model describes how information in an LDAP Directory is organized and identified. In this entries are organized in a Tree-Like structure called Directory Information Tree (DIT). Entries are arranged within DIT based on their distinguished name DN. DN is a unique name that unambiguously identifies a single entry." }, { "code": null, "e": 3556, "s": 3288, "text": "Functional Model:LDAP defines operations for accessing and modifying directory entries . In this we discuss about LDAP operations in a programming language independent manner LDAP operations can be divided into following categories:• Query\n• Update \n• Authentication " }, { "code": null, "e": 3592, "s": 3556, "text": "• Query\n• Update \n• Authentication " }, { "code": null, "e": 3787, "s": 3592, "text": "Security Model:This model describes how information in LDAP directory can be protected from unauthorized access. It is based on BIND operation. There are several bind operation can be performed." }, { "code": null, "e": 3981, "s": 3787, "text": "LDAP Client and Server Interaction:It is quite similar to any other client-server interaction. In this client performs protocol functions against server.The interaction takes place as follows:-" }, { "code": null, "e": 4144, "s": 3981, "text": "A protocol request is send to server by client.Server perform operations on directory such as search, update, delete, etc.The response is sent back to the client." }, { "code": null, "e": 4192, "s": 4144, "text": "A protocol request is send to server by client." }, { "code": null, "e": 4268, "s": 4192, "text": "Server perform operations on directory such as search, update, delete, etc." }, { "code": null, "e": 4309, "s": 4268, "text": "The response is sent back to the client." }, { "code": null, "e": 4645, "s": 4309, "text": "Microsoft, Open LDAP, Sun, etc can easily be made an LDAP server. if the user don’t want to install directory service but want to use LDAP instruction for available LDAP server then user can use four11, bigfoot etc. Making an LDAP client is quite simple as there are SDK’s in many programming languages such as C, C++, Perl, Java, etc." }, { "code": null, "e": 4697, "s": 4645, "text": "User has to perform certain task to be LDAP client:" }, { "code": null, "e": 4798, "s": 4697, "text": "(i) Go get SDK for your language\n(ii) Use function of SDK to connect to LDAP \n(iii) Operate on LDAP " }, { "code": null, "e": 4827, "s": 4798, "text": "LDAP functions / operations:" }, { "code": null, "e": 5111, "s": 4827, "text": "(a) For Authentication:It includes bind, unbind and abandon operations used to connect and disconnect to and from an LDAP server, establish access rights and protect information. In authentication, client session is established and ended using the functions-> BIND/UNBIND\n-> Abandon " }, { "code": null, "e": 5138, "s": 5111, "text": "-> BIND/UNBIND\n-> Abandon " }, { "code": null, "e": 5316, "s": 5138, "text": "(b) For Query:It includes search and compare operations used to retrieve information from a directory. In query, server performs action using function-> Search\n-> Compare Entry " }, { "code": null, "e": 5344, "s": 5316, "text": "-> Search\n-> Compare Entry " }, { "code": null, "e": 5585, "s": 5344, "text": "(c) For Update:It includes add, delete, modify and modify RDN operations used to update stored information in a directory. In update, we can make changes in directories by using function-> Add an entry\n-> Delete an entry\n-> Modify an entry " }, { "code": null, "e": 5640, "s": 5585, "text": "-> Add an entry\n-> Delete an entry\n-> Modify an entry " }, { "code": null, "e": 5796, "s": 5640, "text": "Client establishes session with server (BIND) using Hostname/IP/and Port Number. For security purposes, user set USER-ID and Password based authentication." }, { "code": null, "e": 5857, "s": 5796, "text": "Server perform operations such as read, update, search, etc." }, { "code": null, "e": 5910, "s": 5857, "text": "Client end session using UNBIND or Abandon function." }, { "code": null, "e": 5930, "s": 5910, "text": "Advantages of LDAP:" }, { "code": null, "e": 5995, "s": 5930, "text": "Data present in LDAP is available to many clients and libraries." }, { "code": null, "e": 6035, "s": 5995, "text": "LDAP support many types of application." }, { "code": null, "e": 6080, "s": 6035, "text": "LDAP is very general and has basic security." }, { "code": null, "e": 6147, "s": 6080, "text": "Disadvantages in LDAP:It does not handle well relational database." }, { "code": null, "e": 6165, "s": 6147, "text": "Computer Networks" }, { "code": null, "e": 6183, "s": 6165, "text": "Computer Networks" }, { "code": null, "e": 6281, "s": 6183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6311, "s": 6281, "text": "Wireless Application Protocol" }, { "code": null, "e": 6343, "s": 6311, "text": "Differences between TCP and UDP" }, { "code": null, "e": 6383, "s": 6343, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 6413, "s": 6383, "text": "GSM in Wireless Communication" }, { "code": null, "e": 6439, "s": 6413, "text": "Types of Network Topology" }, { "code": null, "e": 6473, "s": 6439, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 6503, "s": 6473, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 6541, "s": 6503, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 6567, "s": 6541, "text": "Secure Socket Layer (SSL)" } ]
How do we create multiline comments in Python?
23 Sep, 2021 Comments are pieces of information present in the middle of code that allows a developer to explain his work to other developers. They make the code more readable and hence easier to debug. An inline comment is a single line comment and is on the same line as a statement. They are created by putting a ‘#’ symbol before the text. Syntax: # This is a single line comment Example: Python3 def my_fun(): # prints Geeksforgeeks on the console print("GeeksforGeeks") # function callmy_fun() Output: GeeksforGeeks Note: Although not necessary, according to Python there should be a single space between # symbol and comment text and at least 2 spaces between comment and the statement. Block comments in Python usually refer to the code following them and are intended to the same level as that code. Each line of block comment starts with a ‘#’ symbol. Syntax: # This is a block comment # Each line of a block comment is intended to the same level Example: Python3 def my_fun(i): # prints GFG on the console until i # is greater than zero dercrements i # by one on each iteration while i > 0: print("GFG") i = i-1 # calling my_fun# it will print GFG 5 times on the consolemy_fun(5) Output: GFG GFG GFG GFG GFG The documentation string is string literal that occurs as the first statement in a module, function, class, or method definition. They explain what can be achieved by the piece of code but should not contain information about the logic behind the code. Docstrings become __doc__ special attribute of that object which makes them accessible as a runtime object attribute. They can be written in two ways: 1. One-line docstring: Syntax: """This is a one-line docstring.""" or '''This is one-line docstring.''' Example: Python3 def my_fun(): """Greets the user.""" print("Hello Geek!") # function callmy_fun() # help function on my_funhelp(my_fun) Output: Hello Geek! Help on function my_fun in module __main__: my_fun() Greets the user. Note that for one-line docstring closing quotes are on the same line as opening quotes. 2. Multi-line docstring: Syntax: """This is a multi-line docstring. The first line of a multi-line doscstring consist of a summary. It is followed by one or more elaborate description. """ Example: Python3 def my_fun(user): """Greets the user Keyword arguments: user -- name of user """ print("Hello", user+"!") # function callmy_fun("Geek") # help function on my_funhelp(my_fun) Output: Hello Geek! Help on function my_fun in module __main__: my_fun(user) Greets the user Keyword arguments: user -- name of user The closing quotes must be on a line by themselves whereas opening quotes can be on the same line as the summary line. Some best practices for writing docstrings: Use triple double-quotes for the sake of consistency. No extra spaces before or after docstring. Unlike comments, it should end with a period. surindertarika1234 python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 219, "s": 28, "text": "Comments are pieces of information present in the middle of code that allows a developer to explain his work to other developers. They make the code more readable and hence easier to debug. " }, { "code": null, "e": 360, "s": 219, "text": "An inline comment is a single line comment and is on the same line as a statement. They are created by putting a ‘#’ symbol before the text." }, { "code": null, "e": 368, "s": 360, "text": "Syntax:" }, { "code": null, "e": 400, "s": 368, "text": "# This is a single line comment" }, { "code": null, "e": 409, "s": 400, "text": "Example:" }, { "code": null, "e": 417, "s": 409, "text": "Python3" }, { "code": "def my_fun(): # prints Geeksforgeeks on the console print(\"GeeksforGeeks\") # function callmy_fun()", "e": 525, "s": 417, "text": null }, { "code": null, "e": 533, "s": 525, "text": "Output:" }, { "code": null, "e": 547, "s": 533, "text": "GeeksforGeeks" }, { "code": null, "e": 719, "s": 547, "text": "Note: Although not necessary, according to Python there should be a single space between # symbol and comment text and at least 2 spaces between comment and the statement." }, { "code": null, "e": 887, "s": 719, "text": "Block comments in Python usually refer to the code following them and are intended to the same level as that code. Each line of block comment starts with a ‘#’ symbol." }, { "code": null, "e": 895, "s": 887, "text": "Syntax:" }, { "code": null, "e": 983, "s": 895, "text": "# This is a block comment \n# Each line of a block comment is intended to the same level" }, { "code": null, "e": 992, "s": 983, "text": "Example:" }, { "code": null, "e": 1000, "s": 992, "text": "Python3" }, { "code": "def my_fun(i): # prints GFG on the console until i # is greater than zero dercrements i # by one on each iteration while i > 0: print(\"GFG\") i = i-1 # calling my_fun# it will print GFG 5 times on the consolemy_fun(5)", "e": 1247, "s": 1000, "text": null }, { "code": null, "e": 1255, "s": 1247, "text": "Output:" }, { "code": null, "e": 1275, "s": 1255, "text": "GFG\nGFG\nGFG\nGFG\nGFG" }, { "code": null, "e": 1679, "s": 1275, "text": "The documentation string is string literal that occurs as the first statement in a module, function, class, or method definition. They explain what can be achieved by the piece of code but should not contain information about the logic behind the code. Docstrings become __doc__ special attribute of that object which makes them accessible as a runtime object attribute. They can be written in two ways:" }, { "code": null, "e": 1703, "s": 1679, "text": "1. One-line docstring: " }, { "code": null, "e": 1712, "s": 1703, "text": "Syntax: " }, { "code": null, "e": 1748, "s": 1712, "text": "\"\"\"This is a one-line docstring.\"\"\"" }, { "code": null, "e": 1751, "s": 1748, "text": "or" }, { "code": null, "e": 1785, "s": 1751, "text": "'''This is one-line docstring.'''" }, { "code": null, "e": 1794, "s": 1785, "text": "Example:" }, { "code": null, "e": 1802, "s": 1794, "text": "Python3" }, { "code": "def my_fun(): \"\"\"Greets the user.\"\"\" print(\"Hello Geek!\") # function callmy_fun() # help function on my_funhelp(my_fun)", "e": 1933, "s": 1802, "text": null }, { "code": null, "e": 1942, "s": 1933, "text": "Output: " }, { "code": null, "e": 2029, "s": 1942, "text": "Hello Geek!\nHelp on function my_fun in module __main__:\n\nmy_fun()\n Greets the user." }, { "code": null, "e": 2117, "s": 2029, "text": "Note that for one-line docstring closing quotes are on the same line as opening quotes." }, { "code": null, "e": 2142, "s": 2117, "text": "2. Multi-line docstring:" }, { "code": null, "e": 2150, "s": 2142, "text": "Syntax:" }, { "code": null, "e": 2307, "s": 2150, "text": "\"\"\"This is a multi-line docstring.\n\nThe first line of a multi-line doscstring consist of a summary.\nIt is followed by one or more elaborate description.\n\"\"\"" }, { "code": null, "e": 2316, "s": 2307, "text": "Example:" }, { "code": null, "e": 2324, "s": 2316, "text": "Python3" }, { "code": "def my_fun(user): \"\"\"Greets the user Keyword arguments: user -- name of user \"\"\" print(\"Hello\", user+\"!\") # function callmy_fun(\"Geek\") # help function on my_funhelp(my_fun)", "e": 2514, "s": 2324, "text": null }, { "code": null, "e": 2522, "s": 2514, "text": "Output:" }, { "code": null, "e": 2665, "s": 2522, "text": "Hello Geek!\nHelp on function my_fun in module __main__:\n\nmy_fun(user)\n Greets the user\n \n Keyword arguments:\n user -- name of user" }, { "code": null, "e": 2785, "s": 2665, "text": "The closing quotes must be on a line by themselves whereas opening quotes can be on the same line as the summary line. " }, { "code": null, "e": 2829, "s": 2785, "text": "Some best practices for writing docstrings:" }, { "code": null, "e": 2883, "s": 2829, "text": "Use triple double-quotes for the sake of consistency." }, { "code": null, "e": 2926, "s": 2883, "text": "No extra spaces before or after docstring." }, { "code": null, "e": 2972, "s": 2926, "text": "Unlike comments, it should end with a period." }, { "code": null, "e": 2991, "s": 2972, "text": "surindertarika1234" }, { "code": null, "e": 3005, "s": 2991, "text": "python-basics" }, { "code": null, "e": 3012, "s": 3005, "text": "Python" }, { "code": null, "e": 3110, "s": 3012, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3128, "s": 3110, "text": "Python Dictionary" }, { "code": null, "e": 3170, "s": 3128, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3205, "s": 3170, "text": "Read a file line by line in Python" }, { "code": null, "e": 3237, "s": 3205, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3263, "s": 3237, "text": "Python String | replace()" }, { "code": null, "e": 3292, "s": 3263, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3319, "s": 3292, "text": "Python Classes and Objects" }, { "code": null, "e": 3340, "s": 3319, "text": "Python OOPs Concepts" }, { "code": null, "e": 3363, "s": 3340, "text": "Introduction To PYTHON" } ]
How to select and upload multiple files with HTML and PHP, using HTTP POST?
07 Aug, 2021 In this article, we will look at how to upload multiple files with HTML and PHP. Multiple image upload allows the user to select multiple files at once and upload all files to the server. index.html Create a simple HTML page to select multiple files and submit it to upload files on the server. Here, the HTML file contains a form to select and upload files using the POST method. HTML <!DOCTYPE html><html> <head> <title> Select and upload multiple files to the server </title></head> <body> <!-- multipart/form-data ensures that form data is going to be encoded as MIME data --> <form action="file_upload.php" method="POST" enctype="multipart/form-data"> <h2>Upload Files</h2> <p> Select files to upload: <!-- name of the input fields are going to be used in our php script--> <input type="file" name="files[]" multiple> <br><br> <input type="submit" name="submit" value="Upload" > </p> </form></body> </html> file_upload.php The file_upload.php script will handle the file uploading and show the upload status. PHP <?php // Check if form was submittedif(isset($_POST['submit'])) { // Configure upload directory and allowed file types $upload_dir = 'uploads'.DIRECTORY_SEPARATOR; $allowed_types = array('jpg', 'png', 'jpeg', 'gif'); // Define maxsize for files i.e 2MB $maxsize = 2 * 1024 * 1024; // Checks if user sent an empty form if(!empty(array_filter($_FILES['files']['name']))) { // Loop through each file in files[] array foreach ($_FILES['files']['tmp_name'] as $key => $value) { $file_tmpname = $_FILES['files']['tmp_name'][$key]; $file_name = $_FILES['files']['name'][$key]; $file_size = $_FILES['files']['size'][$key]; $file_ext = pathinfo($file_name, PATHINFO_EXTENSION); // Set upload file path $filepath = $upload_dir.$file_name; // Check file type is allowed or not if(in_array(strtolower($file_ext), $allowed_types)) { // Verify file size - 2MB max if ($file_size > $maxsize) echo "Error: File size is larger than the allowed limit."; // If file with name already exist then append time in // front of name of the file to avoid overwriting of file if(file_exists($filepath)) { $filepath = $upload_dir.time().$file_name; if( move_uploaded_file($file_tmpname, $filepath)) { echo "{$file_name} successfully uploaded <br />"; } else { echo "Error uploading {$file_name} <br />"; } } else { if( move_uploaded_file($file_tmpname, $filepath)) { echo "{$file_name} successfully uploaded <br />"; } else { echo "Error uploading {$file_name} <br />"; } } } else { // If file extension not valid echo "Error uploading {$file_name} "; echo "({$file_ext} file type is not allowed)<br / >"; } } } else { // If no files selected echo "No files selected."; }} ?> Output: Before Uploading the file: After Uploading the file: PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. arorakashish0911 Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Aug, 2021" }, { "code": null, "e": 240, "s": 52, "text": "In this article, we will look at how to upload multiple files with HTML and PHP. Multiple image upload allows the user to select multiple files at once and upload all files to the server." }, { "code": null, "e": 433, "s": 240, "text": "index.html Create a simple HTML page to select multiple files and submit it to upload files on the server. Here, the HTML file contains a form to select and upload files using the POST method." }, { "code": null, "e": 438, "s": 433, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> Select and upload multiple files to the server </title></head> <body> <!-- multipart/form-data ensures that form data is going to be encoded as MIME data --> <form action=\"file_upload.php\" method=\"POST\" enctype=\"multipart/form-data\"> <h2>Upload Files</h2> <p> Select files to upload: <!-- name of the input fields are going to be used in our php script--> <input type=\"file\" name=\"files[]\" multiple> <br><br> <input type=\"submit\" name=\"submit\" value=\"Upload\" > </p> </form></body> </html> ", "e": 1169, "s": 438, "text": null }, { "code": null, "e": 1271, "s": 1169, "text": "file_upload.php The file_upload.php script will handle the file uploading and show the upload status." }, { "code": null, "e": 1275, "s": 1271, "text": "PHP" }, { "code": "<?php // Check if form was submittedif(isset($_POST['submit'])) { // Configure upload directory and allowed file types $upload_dir = 'uploads'.DIRECTORY_SEPARATOR; $allowed_types = array('jpg', 'png', 'jpeg', 'gif'); // Define maxsize for files i.e 2MB $maxsize = 2 * 1024 * 1024; // Checks if user sent an empty form if(!empty(array_filter($_FILES['files']['name']))) { // Loop through each file in files[] array foreach ($_FILES['files']['tmp_name'] as $key => $value) { $file_tmpname = $_FILES['files']['tmp_name'][$key]; $file_name = $_FILES['files']['name'][$key]; $file_size = $_FILES['files']['size'][$key]; $file_ext = pathinfo($file_name, PATHINFO_EXTENSION); // Set upload file path $filepath = $upload_dir.$file_name; // Check file type is allowed or not if(in_array(strtolower($file_ext), $allowed_types)) { // Verify file size - 2MB max if ($file_size > $maxsize) echo \"Error: File size is larger than the allowed limit.\"; // If file with name already exist then append time in // front of name of the file to avoid overwriting of file if(file_exists($filepath)) { $filepath = $upload_dir.time().$file_name; if( move_uploaded_file($file_tmpname, $filepath)) { echo \"{$file_name} successfully uploaded <br />\"; } else { echo \"Error uploading {$file_name} <br />\"; } } else { if( move_uploaded_file($file_tmpname, $filepath)) { echo \"{$file_name} successfully uploaded <br />\"; } else { echo \"Error uploading {$file_name} <br />\"; } } } else { // If file extension not valid echo \"Error uploading {$file_name} \"; echo \"({$file_ext} file type is not allowed)<br / >\"; } } } else { // If no files selected echo \"No files selected.\"; }} ?>", "e": 3693, "s": 1275, "text": null }, { "code": null, "e": 3702, "s": 3693, "text": "Output: " }, { "code": null, "e": 3730, "s": 3702, "text": "Before Uploading the file: " }, { "code": null, "e": 3757, "s": 3730, "text": "After Uploading the file: " }, { "code": null, "e": 3926, "s": 3757, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 3945, "s": 3928, "text": "arorakashish0911" }, { "code": null, "e": 3952, "s": 3945, "text": "Picked" }, { "code": null, "e": 3956, "s": 3952, "text": "PHP" }, { "code": null, "e": 3969, "s": 3956, "text": "PHP Programs" }, { "code": null, "e": 3986, "s": 3969, "text": "Web Technologies" }, { "code": null, "e": 4013, "s": 3986, "text": "Web technologies Questions" }, { "code": null, "e": 4017, "s": 4013, "text": "PHP" } ]
Python | Carousel Widget In Kivy
06 Feb, 2020 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Kivy Tutorial – Learn Kivy with Examples. The Carousel widget provides the classic mobile-friendly carousel view where you can swipe between slides. You can add any content to the carousel and have it move horizontally or vertically. The carousel can display pages in a sequence or a loop. Some Important Points to notice: 1) It provides ease to traverse set of slides.2) It can hold image, videos or any other content3) The movement can be vertical or horizontal swipes4) Kivy provides several customizations to a Carousel that include: Animation effect while a transition is made from one slide to another slide, duration of the transition period Specifying the direction of the swipe Disabling vertical swipes Whether the carousel should loop infinitely or not Specification of minimum distance to be considered while accepting a swipe Specification of minimum duration to be considered while accepting a swipe Specifying current, previous and next slides To work with this widget you must have to import: from kivy.uix.carousel import Carousel Basic Approach: 1) import kivy 2) import kivy App 3) import Gridlayout 4) import widget 5) set minimum version(optional) 6) Create as much as widget class as needed 7) create the App class 8) return the widget/layout etc class 9) Run an instance of the class Implementation of the Approach: # Program to explain how to add carousel in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Image widget is used to display an image # this module contain all features of images from kivy.uix.image import AsyncImage # The Carousel widget provides the# classic mobile-friendly carousel# view where you can swipe between slidesfrom kivy.uix.carousel import Carousel # Create the App classclass CarouselApp(App): def build(self): # Add carousel # And add the direction of swipe carousel = Carousel(direction ='right') # Adding 10 slides for i in range(10): src = "http://placehold.it / 480x270.png&text = slide-%d&.png" %i # using Asynchronous image image = AsyncImage(source = src, allow_stretch = True) carousel.add_widget(image) return carousel # Run the AppCarouselApp().run() Output: Python-gui Python-kivy 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 Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Feb, 2020" }, { "code": null, "e": 264, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications." }, { "code": null, "e": 307, "s": 264, "text": " Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 555, "s": 307, "text": "The Carousel widget provides the classic mobile-friendly carousel view where you can swipe between slides. You can add any content to the carousel and have it move horizontally or vertically. The carousel can display pages in a sequence or a loop." }, { "code": null, "e": 588, "s": 555, "text": "Some Important Points to notice:" }, { "code": null, "e": 803, "s": 588, "text": "1) It provides ease to traverse set of slides.2) It can hold image, videos or any other content3) The movement can be vertical or horizontal swipes4) Kivy provides several customizations to a Carousel that include:" }, { "code": null, "e": 914, "s": 803, "text": "Animation effect while a transition is made from one slide to another slide, duration of the transition period" }, { "code": null, "e": 952, "s": 914, "text": "Specifying the direction of the swipe" }, { "code": null, "e": 978, "s": 952, "text": "Disabling vertical swipes" }, { "code": null, "e": 1029, "s": 978, "text": "Whether the carousel should loop infinitely or not" }, { "code": null, "e": 1104, "s": 1029, "text": "Specification of minimum distance to be considered while accepting a swipe" }, { "code": null, "e": 1179, "s": 1104, "text": "Specification of minimum duration to be considered while accepting a swipe" }, { "code": null, "e": 1224, "s": 1179, "text": "Specifying current, previous and next slides" }, { "code": null, "e": 1274, "s": 1224, "text": "To work with this widget you must have to import:" }, { "code": null, "e": 1313, "s": 1274, "text": "from kivy.uix.carousel import Carousel" }, { "code": null, "e": 1572, "s": 1313, "text": "Basic Approach:\n1) import kivy\n2) import kivy App\n3) import Gridlayout\n4) import widget\n5) set minimum version(optional)\n6) Create as much as widget class as needed\n7) create the App class\n8) return the widget/layout etc class\n9) Run an instance of the class" }, { "code": null, "e": 1604, "s": 1572, "text": "Implementation of the Approach:" }, { "code": "# Program to explain how to add carousel in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Image widget is used to display an image # this module contain all features of images from kivy.uix.image import AsyncImage # The Carousel widget provides the# classic mobile-friendly carousel# view where you can swipe between slidesfrom kivy.uix.carousel import Carousel # Create the App classclass CarouselApp(App): def build(self): # Add carousel # And add the direction of swipe carousel = Carousel(direction ='right') # Adding 10 slides for i in range(10): src = \"http://placehold.it / 480x270.png&text = slide-%d&.png\" %i # using Asynchronous image image = AsyncImage(source = src, allow_stretch = True) carousel.add_widget(image) return carousel # Run the AppCarouselApp().run()", "e": 2777, "s": 1604, "text": null }, { "code": null, "e": 2785, "s": 2777, "text": "Output:" }, { "code": null, "e": 2796, "s": 2785, "text": "Python-gui" }, { "code": null, "e": 2808, "s": 2796, "text": "Python-kivy" }, { "code": null, "e": 2815, "s": 2808, "text": "Python" }, { "code": null, "e": 2913, "s": 2815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2941, "s": 2913, "text": "Read JSON file using Python" }, { "code": null, "e": 2991, "s": 2941, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3013, "s": 2991, "text": "Python map() function" }, { "code": null, "e": 3057, "s": 3013, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3099, "s": 3057, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3121, "s": 3099, "text": "Enumerate() in Python" }, { "code": null, "e": 3156, "s": 3121, "text": "Read a file line by line in Python" }, { "code": null, "e": 3182, "s": 3156, "text": "Python String | replace()" }, { "code": null, "e": 3214, "s": 3182, "text": "How to Install PIP on Windows ?" } ]
How to remove portion of a string after a certain character in PHP?
21 Feb, 2019 The substr() and strpos() function is used to remove portion of string after certain character.strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string. Function treats upper-case and lower-case characters differently. Syntax: strpos( original_string, search_string, start_pos ) Return Value: This function returns an integer value which represents the index of original_str where the string search_str first occurs. substr() function: The substr() function is an inbuilt function in PHP is used to extract a specific part of string. Syntax: substr( string_name, start_position, string_length_to_cut ) Return Value: Returns the extracted part of the string if successful otherwise FALSE or an empty string on failure.Here are few examples. Below examples use substr() and strpos() function to remove portion of string after certain character. Example 1: <?php // Declare a variable and initialize it$variable = "GeeksForGeeks is the best platform."; // Display value of variableecho $variable;echo "\n"; // Use substr() and strpos() function to remove// portion of string after certain character$variable = substr($variable, 0, strpos($variable, "is")); // Display value of variableecho $variable; ?> GeeksForGeeks is the best platform. GeeksForGeeks Example 2: <?php // Declare a variable and initialize it$variable = "computer science portal for geeks"; // Display value of variableecho $variable;echo "\n"; // Use substr() and strpos() function to remove// portion of string after certain character// and display itecho substr($variable, 0, strpos($variable, "for")); ?> computer science portal for geeks computer science portal Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2019" }, { "code": null, "e": 380, "s": 28, "text": "The substr() and strpos() function is used to remove portion of string after certain character.strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string. Function treats upper-case and lower-case characters differently." }, { "code": null, "e": 388, "s": 380, "text": "Syntax:" }, { "code": null, "e": 440, "s": 388, "text": "strpos( original_string, search_string, start_pos )" }, { "code": null, "e": 578, "s": 440, "text": "Return Value: This function returns an integer value which represents the index of original_str where the string search_str first occurs." }, { "code": null, "e": 695, "s": 578, "text": "substr() function: The substr() function is an inbuilt function in PHP is used to extract a specific part of string." }, { "code": null, "e": 703, "s": 695, "text": "Syntax:" }, { "code": null, "e": 763, "s": 703, "text": "substr( string_name, start_position, string_length_to_cut )" }, { "code": null, "e": 901, "s": 763, "text": "Return Value: Returns the extracted part of the string if successful otherwise FALSE or an empty string on failure.Here are few examples." }, { "code": null, "e": 1004, "s": 901, "text": "Below examples use substr() and strpos() function to remove portion of string after certain character." }, { "code": null, "e": 1015, "s": 1004, "text": "Example 1:" }, { "code": "<?php // Declare a variable and initialize it$variable = \"GeeksForGeeks is the best platform.\"; // Display value of variableecho $variable;echo \"\\n\"; // Use substr() and strpos() function to remove// portion of string after certain character$variable = substr($variable, 0, strpos($variable, \"is\")); // Display value of variableecho $variable; ?>", "e": 1367, "s": 1015, "text": null }, { "code": null, "e": 1418, "s": 1367, "text": "GeeksForGeeks is the best platform.\nGeeksForGeeks\n" }, { "code": null, "e": 1429, "s": 1418, "text": "Example 2:" }, { "code": "<?php // Declare a variable and initialize it$variable = \"computer science portal for geeks\"; // Display value of variableecho $variable;echo \"\\n\"; // Use substr() and strpos() function to remove// portion of string after certain character// and display itecho substr($variable, 0, strpos($variable, \"for\")); ?>", "e": 1745, "s": 1429, "text": null }, { "code": null, "e": 1804, "s": 1745, "text": "computer science portal for geeks\ncomputer science portal\n" }, { "code": null, "e": 1811, "s": 1804, "text": "Picked" }, { "code": null, "e": 1815, "s": 1811, "text": "PHP" }, { "code": null, "e": 1828, "s": 1815, "text": "PHP Programs" }, { "code": null, "e": 1845, "s": 1828, "text": "Web Technologies" }, { "code": null, "e": 1849, "s": 1845, "text": "PHP" } ]
GATE | GATE CS 2011 | Question 7
28 Jun, 2021 A company needs to develop digital signal processing software for one of its newest inventions. The software is expected to have 40000 lines of code. The company needs to determine the effort in person-months needed to develop this software using the basic COCOMO model. The multiplicative factor for this model is given as 2.8 for the software development on embedded systems, while the exponentiation factor is given as 1.20. What is the estimated effort in person-months?(A) 234.25(B) 932.50(C) 287.80(D) 122.40Answer: (A)Explanation: In the Constructive Cost Model (COCOMO), following is formula for effort applied Effort Applied (E) = ab(KLOC)bb [ person-months ] = 2.8 x(40)1.20 = 2.8 x 83.65 = 234.25 Quiz of this Question GATE-CS-2011 GATE-GATE CS 2011 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 1996 | Question 63 GATE | Gate IT 2005 | Question 52 GATE | GATE-CS-2001 | Question 50 GATE | GATE CS 2008 | Question 40 GATE | GATE-CS-2016 (Set 2) | Question 48
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 647, "s": 28, "text": "A company needs to develop digital signal processing software for one of its newest inventions. The software is expected to have 40000 lines of code. The company needs to determine the effort in person-months needed to develop this software using the basic COCOMO model. The multiplicative factor for this model is given as 2.8 for the software development on embedded systems, while the exponentiation factor is given as 1.20. What is the estimated effort in person-months?(A) 234.25(B) 932.50(C) 287.80(D) 122.40Answer: (A)Explanation: In the Constructive Cost Model (COCOMO), following is formula for effort applied" }, { "code": null, "e": 796, "s": 647, "text": "Effort Applied (E) = ab(KLOC)bb [ person-months ]\n = 2.8 x(40)1.20 \n = 2.8 x 83.65 \n = 234.25 " }, { "code": null, "e": 818, "s": 796, "text": "Quiz of this Question" }, { "code": null, "e": 831, "s": 818, "text": "GATE-CS-2011" }, { "code": null, "e": 849, "s": 831, "text": "GATE-GATE CS 2011" }, { "code": null, "e": 854, "s": 849, "text": "GATE" }, { "code": null, "e": 952, "s": 854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 994, "s": 952, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1056, "s": 994, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1098, "s": 1056, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 1140, "s": 1098, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1182, "s": 1140, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1216, "s": 1182, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 1250, "s": 1216, "text": "GATE | Gate IT 2005 | Question 52" }, { "code": null, "e": 1284, "s": 1250, "text": "GATE | GATE-CS-2001 | Question 50" }, { "code": null, "e": 1318, "s": 1284, "text": "GATE | GATE CS 2008 | Question 40" } ]
STRCMP() Function in MySQL
11 Jan, 2021 STRCMP() function in MySQL is used to compare two strings. If both of the strings are same then it returns 0, if the first argument is smaller than the second according to the defined order it returns -1 and it returns 1 when the second one is smaller the first one. Syntax : STRCMP(Str1, Str2) Parameter : This method accepts two-parameter as described below : str1 : It is the first string used for comparison. str2 : It is the second string used for comparison. Returns : It can give four kinds of value – If string1 = string2, this function returns 0 If string1 < string2, this function returns -1 If string1 > string2, this function returns 1 If any one or both string is NULL, this function returns NULL . Example-1 : STRCMP() function to compare two equal string. As both given strings are equal it will return 0. Select STRCMP('Geeks', 'Geeks') As 'Cmp_Value' Output : Example-2 : STRCMP() function to compare two string when second string is smaller than the first string. Here, the return value will be 1. Select STRCMP('Geeks', 'Geek') As 'Cmp_Value' Output : Example-3 : STRCMP() function to compare two string when second string is bigger than the first string. As the second string is greater than the first one the result will be -1. Select STRCMP('Geek', 'Geeks') As 'Cmp_Value' Output : Example-4 : STRCMP() function to compare two string when at least one string is NULL. Select STRCMP('Geek', NULL) As 'Cmp_Value' Output : Example-5 : STRCMP() function can also be used on column data. To demonstrate create a table named StudentDetails. CREATE TABLE StudentDetails( Student_id INT AUTO_INCREMENT, First_name VARCHAR(100) NOT NULL, Last_name VARCHAR(100) NOT NULL, Student_Class VARCHAR(20) NOT NULL, TotalExamGiven INT NOT NULL, PRIMARY KEY(Student_id ) Inserting data into the Table : INSERT INTO StudentDetails(First_name, Last_name, Class, TotalExamGiven ) VALUES ('Sayan', 'Jana', 'IX', 8 ), ('Nitin', 'Sharma', 'X', 5 ), ('Aniket', 'Srivastava', 'XI', 6 ), ('Abdur', 'Ali', 'X', 7 ), ('Riya', 'Malakar', 'IX', 4 ), ('Jony', 'Patel', 'X', 10 ), ('Deepak', 'Saini', 'X', 7 ), ('Ankana', 'Biswas', 'XII', 5 ), ('Shreya', 'Majhi', 'X', 8 ) ; To verify used the following command as follows. SELECT * FROM StudentDetails; Output : Now, we are going to compare between First_Name and Last_Name column using STRCMP Function. SELECT First_Name, Last_Name, STRCMP(First_Name, Last_Name) AS Cmp_Value FROM StudentDetails; Output : mysql DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jan, 2021" }, { "code": null, "e": 295, "s": 28, "text": "STRCMP() function in MySQL is used to compare two strings. If both of the strings are same then it returns 0, if the first argument is smaller than the second according to the defined order it returns -1 and it returns 1 when the second one is smaller the first one." }, { "code": null, "e": 323, "s": 295, "text": "Syntax : STRCMP(Str1, Str2)" }, { "code": null, "e": 390, "s": 323, "text": "Parameter : This method accepts two-parameter as described below :" }, { "code": null, "e": 441, "s": 390, "text": "str1 : It is the first string used for comparison." }, { "code": null, "e": 493, "s": 441, "text": "str2 : It is the second string used for comparison." }, { "code": null, "e": 537, "s": 493, "text": "Returns : It can give four kinds of value –" }, { "code": null, "e": 583, "s": 537, "text": "If string1 = string2, this function returns 0" }, { "code": null, "e": 630, "s": 583, "text": "If string1 < string2, this function returns -1" }, { "code": null, "e": 676, "s": 630, "text": "If string1 > string2, this function returns 1" }, { "code": null, "e": 740, "s": 676, "text": "If any one or both string is NULL, this function returns NULL ." }, { "code": null, "e": 849, "s": 740, "text": "Example-1 : STRCMP() function to compare two equal string. As both given strings are equal it will return 0." }, { "code": null, "e": 896, "s": 849, "text": "Select STRCMP('Geeks', 'Geeks') As 'Cmp_Value'" }, { "code": null, "e": 905, "s": 896, "text": "Output :" }, { "code": null, "e": 1044, "s": 905, "text": "Example-2 : STRCMP() function to compare two string when second string is smaller than the first string. Here, the return value will be 1." }, { "code": null, "e": 1090, "s": 1044, "text": "Select STRCMP('Geeks', 'Geek') As 'Cmp_Value'" }, { "code": null, "e": 1099, "s": 1090, "text": "Output :" }, { "code": null, "e": 1277, "s": 1099, "text": "Example-3 : STRCMP() function to compare two string when second string is bigger than the first string. As the second string is greater than the first one the result will be -1." }, { "code": null, "e": 1323, "s": 1277, "text": "Select STRCMP('Geek', 'Geeks') As 'Cmp_Value'" }, { "code": null, "e": 1332, "s": 1323, "text": "Output :" }, { "code": null, "e": 1418, "s": 1332, "text": "Example-4 : STRCMP() function to compare two string when at least one string is NULL." }, { "code": null, "e": 1461, "s": 1418, "text": "Select STRCMP('Geek', NULL) As 'Cmp_Value'" }, { "code": null, "e": 1470, "s": 1461, "text": "Output :" }, { "code": null, "e": 1585, "s": 1470, "text": "Example-5 : STRCMP() function can also be used on column data. To demonstrate create a table named StudentDetails." }, { "code": null, "e": 1831, "s": 1585, "text": "CREATE TABLE StudentDetails(\n\n Student_id INT AUTO_INCREMENT, \n First_name VARCHAR(100) NOT NULL,\n Last_name VARCHAR(100) NOT NULL,\n Student_Class VARCHAR(20) NOT NULL,\n TotalExamGiven INT NOT NULL,\n PRIMARY KEY(Student_id )" }, { "code": null, "e": 1863, "s": 1831, "text": "Inserting data into the Table :" }, { "code": null, "e": 2269, "s": 1863, "text": "INSERT INTO \n StudentDetails(First_name, Last_name, Class, TotalExamGiven )\n\nVALUES\n ('Sayan', 'Jana', 'IX', 8 ),\n ('Nitin', 'Sharma', 'X', 5 ),\n ('Aniket', 'Srivastava', 'XI', 6 ),\n ('Abdur', 'Ali', 'X', 7 ),\n ('Riya', 'Malakar', 'IX', 4 ),\n ('Jony', 'Patel', 'X', 10 ),\n ('Deepak', 'Saini', 'X', 7 ),\n ('Ankana', 'Biswas', 'XII', 5 ),\n ('Shreya', 'Majhi', 'X', 8 ) ;" }, { "code": null, "e": 2318, "s": 2269, "text": "To verify used the following command as follows." }, { "code": null, "e": 2348, "s": 2318, "text": "SELECT * FROM StudentDetails;" }, { "code": null, "e": 2357, "s": 2348, "text": "Output :" }, { "code": null, "e": 2449, "s": 2357, "text": "Now, we are going to compare between First_Name and Last_Name column using STRCMP Function." }, { "code": null, "e": 2544, "s": 2449, "text": "SELECT First_Name, Last_Name,\nSTRCMP(First_Name, Last_Name) AS Cmp_Value \nFROM StudentDetails;" }, { "code": null, "e": 2553, "s": 2544, "text": "Output :" }, { "code": null, "e": 2559, "s": 2553, "text": "mysql" }, { "code": null, "e": 2564, "s": 2559, "text": "DBMS" }, { "code": null, "e": 2568, "s": 2564, "text": "SQL" }, { "code": null, "e": 2573, "s": 2568, "text": "DBMS" }, { "code": null, "e": 2577, "s": 2573, "text": "SQL" } ]
tellg() function in C++ with example
05 Jun, 2018 The tellg() function is used with input streams, and returns the current “get” position of the pointer in the stream. It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the get stream pointer. Syntax:- pos_type tellg(); Returns: The current position of the get pointer on success, pos_type(-1) on failure. Example 1 // C++ program to demonstrate // example of tellg() function.#include <bits/stdc++.h>using namespace std; int main(){ string str = "geeksforgeeks"; istringstream in(str); string word; in >> word; cout << "After reading the word \"" << word << "\" tellg() returns " << in.tellg() << '\n';} After reading the word "geeksforgeeks" tellg() returns -1 Example 2 : // C++ program to demonstrate // example of tellg() function.#include <bits/stdc++.h>using namespace std; int main(){ string str = "Hello, GFG"; istringstream in(str); string word; in >> word; cout << "After reading the word \"" << word << "\" tellg() returns " << in.tellg() << '\n';} After reading the word "Hello," tellg() returns 6 Properties:-tellg() does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It’s not even guaranteed that you can convert the type to an integral type) cpp-stringstream C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2018" }, { "code": null, "e": 307, "s": 28, "text": "The tellg() function is used with input streams, and returns the current “get” position of the pointer in the stream. It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the get stream pointer." }, { "code": null, "e": 316, "s": 307, "text": "Syntax:-" }, { "code": null, "e": 336, "s": 316, "text": "pos_type tellg(); \n" }, { "code": null, "e": 422, "s": 336, "text": "Returns: The current position of the get pointer on success, pos_type(-1) on failure." }, { "code": null, "e": 432, "s": 422, "text": "Example 1" }, { "code": "// C++ program to demonstrate // example of tellg() function.#include <bits/stdc++.h>using namespace std; int main(){ string str = \"geeksforgeeks\"; istringstream in(str); string word; in >> word; cout << \"After reading the word \\\"\" << word << \"\\\" tellg() returns \" << in.tellg() << '\\n';}", "e": 746, "s": 432, "text": null }, { "code": null, "e": 805, "s": 746, "text": "After reading the word \"geeksforgeeks\" tellg() returns -1\n" }, { "code": null, "e": 817, "s": 805, "text": "Example 2 :" }, { "code": "// C++ program to demonstrate // example of tellg() function.#include <bits/stdc++.h>using namespace std; int main(){ string str = \"Hello, GFG\"; istringstream in(str); string word; in >> word; cout << \"After reading the word \\\"\" << word << \"\\\" tellg() returns \" << in.tellg() << '\\n';}", "e": 1138, "s": 817, "text": null }, { "code": null, "e": 1189, "s": 1138, "text": "After reading the word \"Hello,\" tellg() returns 6\n" }, { "code": null, "e": 1462, "s": 1189, "text": "Properties:-tellg() does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It’s not even guaranteed that you can convert the type to an integral type)" }, { "code": null, "e": 1479, "s": 1462, "text": "cpp-stringstream" }, { "code": null, "e": 1483, "s": 1479, "text": "C++" }, { "code": null, "e": 1496, "s": 1483, "text": "C++ Programs" }, { "code": null, "e": 1500, "s": 1496, "text": "CPP" } ]
Generating RGBA portable graphic images through C++ - GeeksforGeeks
23 May, 2020 PNG images are capable of supporting multiple image properties such as multiple colors, degree of transparency, Gamma correction, Lossless compression, etc. PNG images are widely used and preferred for numerous types of images. For working with PNG files we will be using the PNGwriter platform-independent, wrapper open-source C++ library for libpng(PNG reference library) one of the most feature-rich library, written in C. PNGwriter library works on Linux, Unix, macOS, and Windows. Its supported features include opening existing PNG images, plotting and reading pixels in the RGB, HSV, and CMYK color spaces, basic shapes, scaling, bilinear interpolation, full TrueType antialiased and rotated text support, and Bezier curves. It requires the FreeType2 library for text support.For more documentation and libraries visit SourceForge, PNGwriter-github. How images are generated:Pixels are the smallest unit that collectively generates an image. Each pixel has some numeric value which represents a color. Below are the steps: We choose the desired height and width of the image.In the desired, we iterate and apply colors pixel by pixel.This collection of pixels is then stored with proper extension and properties, hence generating an image. We choose the desired height and width of the image. In the desired, we iterate and apply colors pixel by pixel. This collection of pixels is then stored with proper extension and properties, hence generating an image. Generating Image by applying colors: Below is the program which generates the RGBA portal graphic images in C++: // C++ program to generate PNG images #include <iostream>#include <pngwriter.h>#include <string> // Function to generate PNG imagevoid generate_PNG(int const width, int const height, std::string filepath){ // Print the filepath cout << endl << "Filepath: " << filepath.c_str(); // Generate the flag pngwriter flag{ width, height, 0, filepath.data() }; // Calculate sizes int const size = width / 3; // Fill the squares flag.filledsquare(0, 0, size, 2 * size, 0, 0, 65535); flag.filledsquare(size, 0, 2 * size, 2 * size, 0, 65535, 65535); flag.filledsquare(2 * size, 0, 3 * size, 2 * size, 65535, 0, 65535); // Close the flag flag.close();} // Driver codeint main(){ // Given width and height int width = 300, height = 200; // Filepath std::string filepath; // Function call to generate PNG image generate_PNG(width, height, filepath); return 0;} Output: Explanation:The above program takes width, height, and file address with a file name. The pngwriter class represents a PNG image. The constructor of the PNG image allows us to set the width and height in pixels, a background colour, and the path to the file where the image should be saved. As illustrated in the above code, we just arranged three solid colors side-by-side and for that, we used filledsquare() function which has taken the x-y coordinates value from start to end positions and a colour values (R, G, B). When the image is saved in memory, then call the close() method to save it to a disk file. computer-graphics C++ C++ Programs Write From Home CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Map in C++ Standard Template Library (STL) Inheritance in C++ C++ Classes and Objects Constructors in C++ Bitwise Operators in C/C++ Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? Program to print ASCII Value of a character C++ program for hashing with chaining
[ { "code": null, "e": 24201, "s": 24173, "text": "\n23 May, 2020" }, { "code": null, "e": 24429, "s": 24201, "text": "PNG images are capable of supporting multiple image properties such as multiple colors, degree of transparency, Gamma correction, Lossless compression, etc. PNG images are widely used and preferred for numerous types of images." }, { "code": null, "e": 25058, "s": 24429, "text": "For working with PNG files we will be using the PNGwriter platform-independent, wrapper open-source C++ library for libpng(PNG reference library) one of the most feature-rich library, written in C. PNGwriter library works on Linux, Unix, macOS, and Windows. Its supported features include opening existing PNG images, plotting and reading pixels in the RGB, HSV, and CMYK color spaces, basic shapes, scaling, bilinear interpolation, full TrueType antialiased and rotated text support, and Bezier curves. It requires the FreeType2 library for text support.For more documentation and libraries visit SourceForge, PNGwriter-github." }, { "code": null, "e": 25231, "s": 25058, "text": "How images are generated:Pixels are the smallest unit that collectively generates an image. Each pixel has some numeric value which represents a color. Below are the steps:" }, { "code": null, "e": 25448, "s": 25231, "text": "We choose the desired height and width of the image.In the desired, we iterate and apply colors pixel by pixel.This collection of pixels is then stored with proper extension and properties, hence generating an image." }, { "code": null, "e": 25501, "s": 25448, "text": "We choose the desired height and width of the image." }, { "code": null, "e": 25561, "s": 25501, "text": "In the desired, we iterate and apply colors pixel by pixel." }, { "code": null, "e": 25667, "s": 25561, "text": "This collection of pixels is then stored with proper extension and properties, hence generating an image." }, { "code": null, "e": 25704, "s": 25667, "text": "Generating Image by applying colors:" }, { "code": null, "e": 25780, "s": 25704, "text": "Below is the program which generates the RGBA portal graphic images in C++:" }, { "code": "// C++ program to generate PNG images #include <iostream>#include <pngwriter.h>#include <string> // Function to generate PNG imagevoid generate_PNG(int const width, int const height, std::string filepath){ // Print the filepath cout << endl << \"Filepath: \" << filepath.c_str(); // Generate the flag pngwriter flag{ width, height, 0, filepath.data() }; // Calculate sizes int const size = width / 3; // Fill the squares flag.filledsquare(0, 0, size, 2 * size, 0, 0, 65535); flag.filledsquare(size, 0, 2 * size, 2 * size, 0, 65535, 65535); flag.filledsquare(2 * size, 0, 3 * size, 2 * size, 65535, 0, 65535); // Close the flag flag.close();} // Driver codeint main(){ // Given width and height int width = 300, height = 200; // Filepath std::string filepath; // Function call to generate PNG image generate_PNG(width, height, filepath); return 0;}", "e": 26901, "s": 25780, "text": null }, { "code": null, "e": 26909, "s": 26901, "text": "Output:" }, { "code": null, "e": 27521, "s": 26909, "text": "Explanation:The above program takes width, height, and file address with a file name. The pngwriter class represents a PNG image. The constructor of the PNG image allows us to set the width and height in pixels, a background colour, and the path to the file where the image should be saved. As illustrated in the above code, we just arranged three solid colors side-by-side and for that, we used filledsquare() function which has taken the x-y coordinates value from start to end positions and a colour values (R, G, B). When the image is saved in memory, then call the close() method to save it to a disk file." }, { "code": null, "e": 27539, "s": 27521, "text": "computer-graphics" }, { "code": null, "e": 27543, "s": 27539, "text": "C++" }, { "code": null, "e": 27556, "s": 27543, "text": "C++ Programs" }, { "code": null, "e": 27572, "s": 27556, "text": "Write From Home" }, { "code": null, "e": 27576, "s": 27572, "text": "CPP" }, { "code": null, "e": 27674, "s": 27576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27683, "s": 27674, "text": "Comments" }, { "code": null, "e": 27696, "s": 27683, "text": "Old Comments" }, { "code": null, "e": 27739, "s": 27696, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 27758, "s": 27739, "text": "Inheritance in C++" }, { "code": null, "e": 27782, "s": 27758, "text": "C++ Classes and Objects" }, { "code": null, "e": 27802, "s": 27782, "text": "Constructors in C++" }, { "code": null, "e": 27829, "s": 27802, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27864, "s": 27829, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27890, "s": 27864, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27949, "s": 27890, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27993, "s": 27949, "text": "Program to print ASCII Value of a character" } ]
How to create PySpark dataframe with schema ? - GeeksforGeeks
09 May, 2021 In this article, we will discuss how to create the dataframe with schema using PySpark. In simple words, the schema is the structure of a dataset or dataframe. For creating the dataframe with schema we are using: Syntax: spark.createDataframe(data,schema) Parameter: data – list of values on which dataframe is created. schema – It’s the structure of dataset or list of column names. where spark is the SparkSession object. Example 1: In the below code we are creating a new Spark Session object named ‘spark’. Then we have created the data values and stored them in the variable named ‘data’ for creating the dataframe. Then we have defined the schema for the dataframe and stored it in the variable named as ‘schm’. Then we have created the dataframe by using createDataframe() function in which we have passed the data and the schema for the dataframe. As dataframe is created for visualizing we used show() function. Python # importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Geek_examples.com") \ .getOrCreate() return spk # main functionif __name__ == "__main__": # calling function to create SparkSession spark = create_session() # creating data for creating dataframe data = [ ("Shivansh","M",50000,2), ("Vaishali","F",45000,3), ("Karan","M",47000,2), ("Satyam","M",40000,4), ("Anupma","F",35000,5) ] # giving schema schm=["Name of employee","Gender","Salary","Years of experience"] # creating dataframe using createDataFrame() # function in which pass data and schema df = spark.createDataFrame(data,schema=schm) # visualizing the dataframe using show() function df.show() Output: Example 2: In the below code we are creating the dataframe by passing data and schema in the createDataframe() function directly. Python # importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Geek_examples.com") \ .getOrCreate() return spk # main functionif __name__ == "__main__": # calling function to create SparkSession spark = create_session() # creating dataframe using createDataFrame() # function in which pass data and schema df = spark.createDataFrame([ ("Mazda RX4",21,4,4), ("Hornet 4 Drive",22,3,2), ("Merc 240D",25,4,2), ("Lotus Europa",31,5,2), ("Ferrari Dino",20,5,6), ("Volvo 142E",22,4,2) ],["Car Name","mgp","gear","carb"]) # visualizing the dataframe using show() function df.show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23925, "s": 23897, "text": "\n09 May, 2021" }, { "code": null, "e": 24085, "s": 23925, "text": "In this article, we will discuss how to create the dataframe with schema using PySpark. In simple words, the schema is the structure of a dataset or dataframe." }, { "code": null, "e": 24138, "s": 24085, "text": "For creating the dataframe with schema we are using:" }, { "code": null, "e": 24181, "s": 24138, "text": "Syntax: spark.createDataframe(data,schema)" }, { "code": null, "e": 24192, "s": 24181, "text": "Parameter:" }, { "code": null, "e": 24245, "s": 24192, "text": "data – list of values on which dataframe is created." }, { "code": null, "e": 24309, "s": 24245, "text": "schema – It’s the structure of dataset or list of column names." }, { "code": null, "e": 24349, "s": 24309, "text": "where spark is the SparkSession object." }, { "code": null, "e": 24360, "s": 24349, "text": "Example 1:" }, { "code": null, "e": 24436, "s": 24360, "text": "In the below code we are creating a new Spark Session object named ‘spark’." }, { "code": null, "e": 24546, "s": 24436, "text": "Then we have created the data values and stored them in the variable named ‘data’ for creating the dataframe." }, { "code": null, "e": 24644, "s": 24546, "text": "Then we have defined the schema for the dataframe and stored it in the variable named as ‘schm’. " }, { "code": null, "e": 24782, "s": 24644, "text": "Then we have created the dataframe by using createDataframe() function in which we have passed the data and the schema for the dataframe." }, { "code": null, "e": 24847, "s": 24782, "text": "As dataframe is created for visualizing we used show() function." }, { "code": null, "e": 24854, "s": 24847, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Geek_examples.com\") \\ .getOrCreate() return spk # main functionif __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() # creating data for creating dataframe data = [ (\"Shivansh\",\"M\",50000,2), (\"Vaishali\",\"F\",45000,3), (\"Karan\",\"M\",47000,2), (\"Satyam\",\"M\",40000,4), (\"Anupma\",\"F\",35000,5) ] # giving schema schm=[\"Name of employee\",\"Gender\",\"Salary\",\"Years of experience\"] # creating dataframe using createDataFrame() # function in which pass data and schema df = spark.createDataFrame(data,schema=schm) # visualizing the dataframe using show() function df.show()", "e": 25699, "s": 24854, "text": null }, { "code": null, "e": 25707, "s": 25699, "text": "Output:" }, { "code": null, "e": 25718, "s": 25707, "text": "Example 2:" }, { "code": null, "e": 25837, "s": 25718, "text": "In the below code we are creating the dataframe by passing data and schema in the createDataframe() function directly." }, { "code": null, "e": 25844, "s": 25837, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Geek_examples.com\") \\ .getOrCreate() return spk # main functionif __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() # creating dataframe using createDataFrame() # function in which pass data and schema df = spark.createDataFrame([ (\"Mazda RX4\",21,4,4), (\"Hornet 4 Drive\",22,3,2), (\"Merc 240D\",25,4,2), (\"Lotus Europa\",31,5,2), (\"Ferrari Dino\",20,5,6), (\"Volvo 142E\",22,4,2) ],[\"Car Name\",\"mgp\",\"gear\",\"carb\"]) # visualizing the dataframe using show() function df.show()", "e": 26592, "s": 25844, "text": null }, { "code": null, "e": 26600, "s": 26592, "text": "Output:" }, { "code": null, "e": 26607, "s": 26600, "text": "Picked" }, { "code": null, "e": 26622, "s": 26607, "text": "Python-Pyspark" }, { "code": null, "e": 26629, "s": 26622, "text": "Python" }, { "code": null, "e": 26727, "s": 26629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26736, "s": 26727, "text": "Comments" }, { "code": null, "e": 26749, "s": 26736, "text": "Old Comments" }, { "code": null, "e": 26781, "s": 26749, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26837, "s": 26781, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26879, "s": 26837, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26921, "s": 26879, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26957, "s": 26921, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26979, "s": 26957, "text": "Defaultdict in Python" }, { "code": null, "e": 27018, "s": 26979, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27045, "s": 27018, "text": "Python Classes and Objects" }, { "code": null, "e": 27076, "s": 27045, "text": "Python | os.path.join() method" } ]
Generating random number in a range in C
Here we will see how to generate random number in given range using C. To solve this problem, we will use the srand() function. The current time will be used to seed the srad() function. This function cannot generate random number in any range, it can generate number between 0 to some value. So for it, we have to follow one trick. We will generate random number in between 0 to (upper – lower + 1), then add the lower limit for offsetting. #include <stdio.h> #include <stdlib.h> #include <time.h> void generate_random(int l, int r, int count) { //this will generate random number in range l and r int i; for (i = 0; i < count; i++) { int rand_num = (rand() % (r - l + 1)) + l; printf("%d ", rand_num); } } main() { int lower = 10, upper = 15, count = 15; srand(time(0)); //current time as seed of random number generator generate_random(lower, upper, count); printf("\n"); } 15 11 13 10 13 10 15 11 14 12 12 13 12 13 14
[ { "code": null, "e": 1249, "s": 1062, "text": "Here we will see how to generate random number in given range using C. To solve this problem, we will use the srand() function. The current time will be used to seed the srad() function." }, { "code": null, "e": 1504, "s": 1249, "text": "This function cannot generate random number in any range, it can generate number between 0 to some value. So for it, we have to follow one trick. We will generate random number in between 0 to (upper – lower + 1), then add the lower limit for offsetting." }, { "code": null, "e": 1972, "s": 1504, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\nvoid generate_random(int l, int r, int count) { //this will generate random number in range l and r\n int i;\n for (i = 0; i < count; i++) {\n int rand_num = (rand() % (r - l + 1)) + l;\n printf(\"%d \", rand_num);\n }\n}\nmain() {\n int lower = 10, upper = 15, count = 15;\n srand(time(0)); //current time as seed of random number generator\n generate_random(lower, upper, count);\n printf(\"\\n\");\n}" }, { "code": null, "e": 2017, "s": 1972, "text": "15 11 13 10 13 10 15 11 14 12 12 13 12 13 14" } ]
Using Python in Power BI. Step by step guide on how to enable... | by Tommi Ranta | Towards Data Science
Since April 2019 Python integration has been generally available in Power BI. Just as with the R support you can now use Python for importing data, data transformation and data visualization. In this article we will step by step prepare a Python environment, enable Python in Power BI, import data and apply clustering to the data and create custom visuals in Power BI using Python. All material needed to replicate this example is available in GitHub. The article assumes that you have a working Python environment and Power BI installed. The dataset that we’ll be working with is the Boston Housing dataset, which is available in scikit-learn. The dataset is most often used for examples in regression but we’ll take a different approach and use it for clustering. We will use Principal Component Analysis to reduce the dimensions in order to visualize the data in a 2-dimensional space. After this we will apply k-means clustering to try to identify any homogeneous groups within the data. I will not go through the steps taken to create the import code as the main focus of this article is to showcase using Python in Power BI. The data preparation phase is available as an Jupyter Notebook for those who are interested to see how it was created. I recommend creating standalone scripts of the code that you are going to use in order to test and debug any problems prior to using it in Power BI. The error messages provided by Power BI are not always that informative. There are several ways to manage your Python (virtual) environments. In addition to virtualenv and pipenv you can also use the conda distribution. In this example I’m using pipenv to manage the Python environment that Power BI will use. In order to get started open a Command Prompt or Power Shell console and navigate to the folder that you want to use as a working directory for your Python code. Go to the location where you have cloned/downloaded the example code from my GitHub repository if you are using that. We will run the following command in order to create the Python environment and install the required libraries. pipenv install numpy pandas matplotlib seaborn scikit-learn In case you are using my code from GitHub it is enough to run pipenv install as it will automatically install the required libraries from the existing Pipfile. Lastly, we want to check the actual Python path for this virtual environment since we will need to refer to that from Power BI. pipenv --venv The location of my virtual environment was C:\Users\tomra\.virtualenvs\python_and_powerbi-0r4DNLn9 so I copy that path to the clipboard. NOTE: You can use conda to manage a virtual environment for Power BI. In case you've used similar conda installation/configuration as me, the conda environments are installed in a system folder in Windows %userprofile%\AppData. As default you cannot navigate to this folder from the Power BI to choose your Python home directory. A workaround for this is to show hidden files in Windows Explorer. Just be aware of the implications that you don't accidentally remove any system files in regular Windows usage. Another option is to place the conda environments in a non-system folder. Start Power BI and go to the Options where you should see the Python scripting section on the left. Click on that to open the Python script options. As default Power BI lists the Python environments is has been able to detect in the system. We will need to change these settings since we created a separate virtual environment for Power BI. From Detected Python home directories choose the Other option. Set the Python home directory to the Scripts folder in the path where your virtual environment exists. In my case it is C:\Users\tomra\.virtualenvs\python_and_powerbi-0r4DNLn9\Scripts. Now we are ready to utilize Python code in Power BI so get ready! We go to the Home tab in the ribbon and click Get data and choose the More option to start our data import. Go to the Other pane where you should find the Python script option. Select that and click Connect. A Python script dialog opens where you can add your own code. Copy and paste the below code to the Script text area and click OK. import pandas as pdimport numpy as npfrom sklearn.datasets import load_bostonfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom sklearn.cluster import KMeans# utilize the sklearn.datasets package to load the Boston Housing datasetboston = load_boston()# scale the data to same value range first since PCA# is sensitive to the scaling of datasc = StandardScaler()X = sc.fit_transform(boston.data)# create PCA with n_components=2 to allow visualization in 2 dimensionspca = PCA(n_components=2)X_pca = pca.fit_transform(X)# divide data into 5 clusters (refer to .ipynb for motivation)kmeans = KMeans(n_clusters=5, init='k-means++', max_iter=300, n_init=10)y_kmeans = kmeans.fit_predict(X_pca)# create pandas dataframe of the housing data for Power BIcolumns = np.append(boston.feature_names, ['MEDV', 'PC1', 'PC2', 'CLUSTER'])data = np.concatenate((boston.data, boston.target.reshape(-1, 1), X_pca, y_kmeans.reshape(-1, 1)), axis=1)df_housing = pd.DataFrame(data=data, columns=columns)# we need to convert all columns as string because of different# decimal separator in Python (.) and Finnish locale (,) that Power BI uses.# comment out below line if Power BI uses dot as a decimal separator.df_housing = df_housing.astype('str')# create pandas dataframe of the pca data for Power BIcolumns = np.append(boston.feature_names, ['VARRATIO'])data = np.concatenate((pca.components_, pca.explained_variance_ratio_.reshape(-1, 1)), axis=1)df_pca = pd.DataFrame(data=data, columns=columns, index=['PC1', 'PC2'])df_pca = df_pca.astype('str') In the next window we are able to choose which datasets to import. Select both the df_housing as well as the df_pca datasets and click Load. Next we will go and make the final adjustments to our import data. Click Edit Queries in the ribbon. Because of the possible difference in your locale settings in Python and Power BI I chose to save all columns as strings in the Python script. The correct data types needs to be set and depending on your locale/settings we might need to take different routes. The target is to convert every column to numbers. Power BI with decimal point Although I have not tested this, you should be able to remove the Changed Type step, choose all columns and let Power BI Detect Data Type from the Transform tab in the ribbon in order to get the correct data types. Repeat for both datasets. Another option is to modify the import script and remove/comment the rows where we set the data type as strings df_housing = df_housing.astype('str') and df_pca = df_pca.astype('str'). Power BI should identify the data types during import correctly. Power BI with decimal comma We need to replace the decimal separator from dot (.) to comma (,) in order to set the correct data type. Choose all columns and click Replace Values from the Transform tab in the ribbon. Replace dot with comma and click OK. After this let Power BI detect the correct data type by clicking Detect Data Type. Repeat these steps for both datasets. The final step is to add an Index Column to the df_housing dataset. This can be done from the Add Column tab in the ribbon. When that has been done go to the Home tab and click Close & Apply. We go back to the Reports view to start working on our visualizations. The plan is to visualize the clusters on a chart using the principal components as axes. A scatter plot is a good alternative for this visualization. Click on the Scatter chart to add it to the page. Drag the df_housing columns to the visualizations pane in the following way: Drag PC1 to the X Axis. Drag PC2 to the Y Axis. Drag CLUSTER to the Legend to visualize how the clusters are grouped. Drag Index to Details as this will remove the aggregation in the chart. The end result should look something similar to the picture below. You might have a different cluster order (coloring) due to the random selection of initial centroids in the k-means clustering. Next we will visualize how each feature affects each of the principal components. This information is available in the df_pca dataset. We will show this information through a heatmap. The Seaborn Python library provides an easy way to create a heatmap so we'll add a Python visual to the page. Power BI might warn you about script visuals, click Enable to continue. Each feature needs to be separately dragged to the Data fields area. Drag each column from the dataset except VARRATIO. Copy the following code snippet to the code area and click Run script. import matplotlib.pyplot as pltimport seaborn as snsdataset.index = ['PC1', 'PC2']plt.figure(figsize=(8, 2))plt.xticks(rotation=45)data = dataset.loc['PC1', :].to_frame().sort_values(by='PC1').transpose()sns.heatmap(data, cmap='plasma', square=True, annot=True, cbar=False, yticklabels='')plt.show() You should now see a heatmap similar to the figure below. Depending on your screen resolution you might have to hide the script pane to see the visual. Repeat the same step to create a heatmap for the second principal component but use below code snippet instead to use the data from the second principal component and make a vertical visualization that can be placed on the left side of the scatter plot. import matplotlib.pyplot as pltimport seaborn as snsdataset.index = ['PC1', 'PC2']plt.figure(figsize=(2, 8))data = dataset.loc['PC2', :].to_frame().sort_values(by='PC2', ascending=False)sns.heatmap(data, cmap='plasma', square=True, annot=True, cbar=False, xticklabels='')plt.show() I recommend testing your Python visuals in some other tool e.g. using Jupyter Notebook especially in cases where the visualization is complicated or you want to fine-tune all the small details of the visualization. It’s also worth considering to use the same fonts in your Python visualization as in the Power BI report to have a unified look & feel. This is quite easy to achieve with Matplotlib and its siblings. NOTE: Some python packages only generate HTML, to overcome this limitation, the plot is saved as an image and then displayed using matplotlib. To write to png you need to install chrome driver and e.g. place the exe in C:\chromedriver. Once you have done this you should this folder in the PATH environment variable. This step is not needed in our case. We have now visualized the identified clusters of data with regards to the two principal components that together explain the majority of the variance in the data. The heat maps display which features affects each principal component in a positive or negative manner with regards to the principal component value. Let’s make some final touches to make the report look a little nicer: Change one of the gray cluster colors to purple. Add a heading and reference to data. Add a visualization that shows the average median price per cluster. Add a text box explaining the features. Add a visualization stating the variance explained for each principal component. This is how my version ended up looking. To top it off we’ll just create one more report where we take a closer look at the relation between a chosen feature, median housing value (target) and the identified clusters. By looking at the visualization we can conclude that the first principal component alone explains almost half of the variance in the data. In addition, we can see from the charts that lower principal components values translate to a higher median house value on average. The Distance feature has the biggest impact for lowering the PC1 value by a small margin, so let's have a closer look at that to see how it behaves in the different clusters. We create a new page and do the following changes: Add a descriptive heading. Add a Scatter chart with X Axis value is DIS column, Y Axis value is MEDV and Legend and Details fields are set up like the previous scatter plot. Right click the DIS column and choose New group and create bins of size 1. Add a Stacked column chart showing the distribution of distance values by using the newly created binned column of DIS. Sort the chart in ascending order by the Axis instead of the count. This is how my version of the report turned out. In this article we have set-up a Python virtual environment and installed the required libraries for data transformation and visualization. You can install additional libraries to the environment if there is some Python library you want to utilize. Next we set-up Power BI to utilize Python scripts. This was a one-time setup, which means that you don’t have to repeat these same steps with your next report. Finally, we utilized Python scripts for importing data and creating custom visuals. There is also possibilities to use Python scripts for data cleaning & transformations for datasets that have already been imported to Power BI. It remains to be seen in what use cases it makes sense to utilize Python scripts within Power BI versus preparing the data outside Power BI and importing a dataset that is ready for visualization. Also the performance of the Python visuals could be better. But keeping in mind that this is still a preview feature it looks very promising! What use cases do you see for using Python in Power BI? Join the discussion and share your thoughts.
[ { "code": null, "e": 711, "s": 171, "text": "Since April 2019 Python integration has been generally available in Power BI. Just as with the R support you can now use Python for importing data, data transformation and data visualization. In this article we will step by step prepare a Python environment, enable Python in Power BI, import data and apply clustering to the data and create custom visuals in Power BI using Python. All material needed to replicate this example is available in GitHub. The article assumes that you have a working Python environment and Power BI installed." }, { "code": null, "e": 1164, "s": 711, "text": "The dataset that we’ll be working with is the Boston Housing dataset, which is available in scikit-learn. The dataset is most often used for examples in regression but we’ll take a different approach and use it for clustering. We will use Principal Component Analysis to reduce the dimensions in order to visualize the data in a 2-dimensional space. After this we will apply k-means clustering to try to identify any homogeneous groups within the data." }, { "code": null, "e": 1644, "s": 1164, "text": "I will not go through the steps taken to create the import code as the main focus of this article is to showcase using Python in Power BI. The data preparation phase is available as an Jupyter Notebook for those who are interested to see how it was created. I recommend creating standalone scripts of the code that you are going to use in order to test and debug any problems prior to using it in Power BI. The error messages provided by Power BI are not always that informative." }, { "code": null, "e": 1791, "s": 1644, "text": "There are several ways to manage your Python (virtual) environments. In addition to virtualenv and pipenv you can also use the conda distribution." }, { "code": null, "e": 2273, "s": 1791, "text": "In this example I’m using pipenv to manage the Python environment that Power BI will use. In order to get started open a Command Prompt or Power Shell console and navigate to the folder that you want to use as a working directory for your Python code. Go to the location where you have cloned/downloaded the example code from my GitHub repository if you are using that. We will run the following command in order to create the Python environment and install the required libraries." }, { "code": null, "e": 2333, "s": 2273, "text": "pipenv install numpy pandas matplotlib seaborn scikit-learn" }, { "code": null, "e": 2493, "s": 2333, "text": "In case you are using my code from GitHub it is enough to run pipenv install as it will automatically install the required libraries from the existing Pipfile." }, { "code": null, "e": 2621, "s": 2493, "text": "Lastly, we want to check the actual Python path for this virtual environment since we will need to refer to that from Power BI." }, { "code": null, "e": 2635, "s": 2621, "text": "pipenv --venv" }, { "code": null, "e": 2772, "s": 2635, "text": "The location of my virtual environment was C:\\Users\\tomra\\.virtualenvs\\python_and_powerbi-0r4DNLn9 so I copy that path to the clipboard." }, { "code": null, "e": 3355, "s": 2772, "text": "NOTE: You can use conda to manage a virtual environment for Power BI. In case you've used similar conda installation/configuration as me, the conda environments are installed in a system folder in Windows %userprofile%\\AppData. As default you cannot navigate to this folder from the Power BI to choose your Python home directory. A workaround for this is to show hidden files in Windows Explorer. Just be aware of the implications that you don't accidentally remove any system files in regular Windows usage. Another option is to place the conda environments in a non-system folder." }, { "code": null, "e": 3944, "s": 3355, "text": "Start Power BI and go to the Options where you should see the Python scripting section on the left. Click on that to open the Python script options. As default Power BI lists the Python environments is has been able to detect in the system. We will need to change these settings since we created a separate virtual environment for Power BI. From Detected Python home directories choose the Other option. Set the Python home directory to the Scripts folder in the path where your virtual environment exists. In my case it is C:\\Users\\tomra\\.virtualenvs\\python_and_powerbi-0r4DNLn9\\Scripts." }, { "code": null, "e": 4010, "s": 3944, "text": "Now we are ready to utilize Python code in Power BI so get ready!" }, { "code": null, "e": 4348, "s": 4010, "text": "We go to the Home tab in the ribbon and click Get data and choose the More option to start our data import. Go to the Other pane where you should find the Python script option. Select that and click Connect. A Python script dialog opens where you can add your own code. Copy and paste the below code to the Script text area and click OK." }, { "code": null, "e": 6048, "s": 4348, "text": "import pandas as pdimport numpy as npfrom sklearn.datasets import load_bostonfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom sklearn.cluster import KMeans# utilize the sklearn.datasets package to load the Boston Housing datasetboston = load_boston()# scale the data to same value range first since PCA# is sensitive to the scaling of datasc = StandardScaler()X = sc.fit_transform(boston.data)# create PCA with n_components=2 to allow visualization in 2 dimensionspca = PCA(n_components=2)X_pca = pca.fit_transform(X)# divide data into 5 clusters (refer to .ipynb for motivation)kmeans = KMeans(n_clusters=5, init='k-means++', max_iter=300, n_init=10)y_kmeans = kmeans.fit_predict(X_pca)# create pandas dataframe of the housing data for Power BIcolumns = np.append(boston.feature_names, ['MEDV', 'PC1', 'PC2', 'CLUSTER'])data = np.concatenate((boston.data, boston.target.reshape(-1, 1), X_pca, y_kmeans.reshape(-1, 1)), axis=1)df_housing = pd.DataFrame(data=data, columns=columns)# we need to convert all columns as string because of different# decimal separator in Python (.) and Finnish locale (,) that Power BI uses.# comment out below line if Power BI uses dot as a decimal separator.df_housing = df_housing.astype('str')# create pandas dataframe of the pca data for Power BIcolumns = np.append(boston.feature_names, ['VARRATIO'])data = np.concatenate((pca.components_, pca.explained_variance_ratio_.reshape(-1, 1)), axis=1)df_pca = pd.DataFrame(data=data, columns=columns, index=['PC1', 'PC2'])df_pca = df_pca.astype('str')" }, { "code": null, "e": 6290, "s": 6048, "text": "In the next window we are able to choose which datasets to import. Select both the df_housing as well as the df_pca datasets and click Load. Next we will go and make the final adjustments to our import data. Click Edit Queries in the ribbon." }, { "code": null, "e": 6600, "s": 6290, "text": "Because of the possible difference in your locale settings in Python and Power BI I chose to save all columns as strings in the Python script. The correct data types needs to be set and depending on your locale/settings we might need to take different routes. The target is to convert every column to numbers." }, { "code": null, "e": 6628, "s": 6600, "text": "Power BI with decimal point" }, { "code": null, "e": 6869, "s": 6628, "text": "Although I have not tested this, you should be able to remove the Changed Type step, choose all columns and let Power BI Detect Data Type from the Transform tab in the ribbon in order to get the correct data types. Repeat for both datasets." }, { "code": null, "e": 7119, "s": 6869, "text": "Another option is to modify the import script and remove/comment the rows where we set the data type as strings df_housing = df_housing.astype('str') and df_pca = df_pca.astype('str'). Power BI should identify the data types during import correctly." }, { "code": null, "e": 7147, "s": 7119, "text": "Power BI with decimal comma" }, { "code": null, "e": 7372, "s": 7147, "text": "We need to replace the decimal separator from dot (.) to comma (,) in order to set the correct data type. Choose all columns and click Replace Values from the Transform tab in the ribbon. Replace dot with comma and click OK." }, { "code": null, "e": 7493, "s": 7372, "text": "After this let Power BI detect the correct data type by clicking Detect Data Type. Repeat these steps for both datasets." }, { "code": null, "e": 7685, "s": 7493, "text": "The final step is to add an Index Column to the df_housing dataset. This can be done from the Add Column tab in the ribbon. When that has been done go to the Home tab and click Close & Apply." }, { "code": null, "e": 8033, "s": 7685, "text": "We go back to the Reports view to start working on our visualizations. The plan is to visualize the clusters on a chart using the principal components as axes. A scatter plot is a good alternative for this visualization. Click on the Scatter chart to add it to the page. Drag the df_housing columns to the visualizations pane in the following way:" }, { "code": null, "e": 8057, "s": 8033, "text": "Drag PC1 to the X Axis." }, { "code": null, "e": 8081, "s": 8057, "text": "Drag PC2 to the Y Axis." }, { "code": null, "e": 8151, "s": 8081, "text": "Drag CLUSTER to the Legend to visualize how the clusters are grouped." }, { "code": null, "e": 8223, "s": 8151, "text": "Drag Index to Details as this will remove the aggregation in the chart." }, { "code": null, "e": 8418, "s": 8223, "text": "The end result should look something similar to the picture below. You might have a different cluster order (coloring) due to the random selection of initial centroids in the k-means clustering." }, { "code": null, "e": 8975, "s": 8418, "text": "Next we will visualize how each feature affects each of the principal components. This information is available in the df_pca dataset. We will show this information through a heatmap. The Seaborn Python library provides an easy way to create a heatmap so we'll add a Python visual to the page. Power BI might warn you about script visuals, click Enable to continue. Each feature needs to be separately dragged to the Data fields area. Drag each column from the dataset except VARRATIO. Copy the following code snippet to the code area and click Run script." }, { "code": null, "e": 9330, "s": 8975, "text": "import matplotlib.pyplot as pltimport seaborn as snsdataset.index = ['PC1', 'PC2']plt.figure(figsize=(8, 2))plt.xticks(rotation=45)data = dataset.loc['PC1', :].to_frame().sort_values(by='PC1').transpose()sns.heatmap(data, cmap='plasma', square=True, annot=True, cbar=False, yticklabels='')plt.show()" }, { "code": null, "e": 9482, "s": 9330, "text": "You should now see a heatmap similar to the figure below. Depending on your screen resolution you might have to hide the script pane to see the visual." }, { "code": null, "e": 9736, "s": 9482, "text": "Repeat the same step to create a heatmap for the second principal component but use below code snippet instead to use the data from the second principal component and make a vertical visualization that can be placed on the left side of the scatter plot." }, { "code": null, "e": 10073, "s": 9736, "text": "import matplotlib.pyplot as pltimport seaborn as snsdataset.index = ['PC1', 'PC2']plt.figure(figsize=(2, 8))data = dataset.loc['PC2', :].to_frame().sort_values(by='PC2', ascending=False)sns.heatmap(data, cmap='plasma', square=True, annot=True, cbar=False, xticklabels='')plt.show()" }, { "code": null, "e": 10488, "s": 10073, "text": "I recommend testing your Python visuals in some other tool e.g. using Jupyter Notebook especially in cases where the visualization is complicated or you want to fine-tune all the small details of the visualization. It’s also worth considering to use the same fonts in your Python visualization as in the Power BI report to have a unified look & feel. This is quite easy to achieve with Matplotlib and its siblings." }, { "code": null, "e": 10842, "s": 10488, "text": "NOTE: Some python packages only generate HTML, to overcome this limitation, the plot is saved as an image and then displayed using matplotlib. To write to png you need to install chrome driver and e.g. place the exe in C:\\chromedriver. Once you have done this you should this folder in the PATH environment variable. This step is not needed in our case." }, { "code": null, "e": 11226, "s": 10842, "text": "We have now visualized the identified clusters of data with regards to the two principal components that together explain the majority of the variance in the data. The heat maps display which features affects each principal component in a positive or negative manner with regards to the principal component value. Let’s make some final touches to make the report look a little nicer:" }, { "code": null, "e": 11275, "s": 11226, "text": "Change one of the gray cluster colors to purple." }, { "code": null, "e": 11312, "s": 11275, "text": "Add a heading and reference to data." }, { "code": null, "e": 11381, "s": 11312, "text": "Add a visualization that shows the average median price per cluster." }, { "code": null, "e": 11421, "s": 11381, "text": "Add a text box explaining the features." }, { "code": null, "e": 11502, "s": 11421, "text": "Add a visualization stating the variance explained for each principal component." }, { "code": null, "e": 11543, "s": 11502, "text": "This is how my version ended up looking." }, { "code": null, "e": 12217, "s": 11543, "text": "To top it off we’ll just create one more report where we take a closer look at the relation between a chosen feature, median housing value (target) and the identified clusters. By looking at the visualization we can conclude that the first principal component alone explains almost half of the variance in the data. In addition, we can see from the charts that lower principal components values translate to a higher median house value on average. The Distance feature has the biggest impact for lowering the PC1 value by a small margin, so let's have a closer look at that to see how it behaves in the different clusters. We create a new page and do the following changes:" }, { "code": null, "e": 12244, "s": 12217, "text": "Add a descriptive heading." }, { "code": null, "e": 12391, "s": 12244, "text": "Add a Scatter chart with X Axis value is DIS column, Y Axis value is MEDV and Legend and Details fields are set up like the previous scatter plot." }, { "code": null, "e": 12466, "s": 12391, "text": "Right click the DIS column and choose New group and create bins of size 1." }, { "code": null, "e": 12654, "s": 12466, "text": "Add a Stacked column chart showing the distribution of distance values by using the newly created binned column of DIS. Sort the chart in ascending order by the Axis instead of the count." }, { "code": null, "e": 12703, "s": 12654, "text": "This is how my version of the report turned out." } ]
Getter and Setter in Python - GeeksforGeeks
04 Dec, 2019 In Python, getters and setters are not the same as those in other object-oriented programming languages. Basically, the main purpose of using getters and setters in object-oriented programs is to ensure data encapsulation. Private variables in python are not actually hidden fields like in other object oriented languages. Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user. Using normal function to achieve getters and setters behaviour To achieve getters & setters property, if we define normal get() and set() methods it will not reflect any special implementation. For Example # Python program showing a use# of get() and set() method in# normal function class Geek: def __init__(self, age = 0): self._age = age # getter method def get_age(self): return self._age # setter method def set_age(self, x): self._age = x raj = Geek() # setting the age using setterraj.set_age(21) # retrieving age using getterprint(raj.get_age()) print(raj._age) Output: 21 21 In above code functions get_age() and set_age() acts as normal functions and doesn’t play any impact as getters and setters, to achieve such functionality Python has a special function property(). Using property() function to achieve getters and setters behaviour In Python property()is a built-in function that creates and returns a property object. A property object has three methods, getter(), setter(), and delete(). property() function in Python has four arguments property(fget, fset, fdel, doc), fget is a function for retrieving an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. doc creates a docstring for attribute. A property object has three methods, getter(), setter(), and delete() to specify fget, fset and fdel individually. For Example # Python program showing a# use of property() function class Geeks: def __init__(self): self._age = 0 # function to get value of _age def get_age(self): print("getter method called") return self._age # function to set value of _age def set_age(self, a): print("setter method called") self._age = a # function to delete _age attribute def del_age(self): del self._age age = property(get_age, set_age, del_age) mark = Geeks() mark.age = 10 print(mark.age) setter method called getter method called 10 In above code there is only one print statement at line #25 but output consists of three lines due to setter method set_age() called in line #23 and getter method get_age() called in line #25. Hence age is a property object that helps to keep the access of private variable safe. Using @property decorators to achieve getters and setters behaviour In previous method we used property() function in order to achieve getters and setters behaviour. However as mentioned earlier in this post getters and setters are also used for validating the getting and setting of attributes value. There is one more way to implement property function i.e. by using decorator. Python @property is one of the built-in decorators. The main purpose of any decorator is to change your class methods or attributes in such a way so that the user of your class no need to make any change in their code. For Example # Python program showing the use of# @property class Geeks: def __init__(self): self._age = 0 # using property decorator # a getter function @property def age(self): print("getter method called") return self._age # a setter function @age.setter def age(self, a): if(a < 18): raise ValueError("Sorry you age is below eligibility criteria") print("setter method called") self._age = a mark = Geeks() mark.age = 19 print(mark.age) Output: setter method called getter method called 19 In above code it is clear that how to use @property decorator to create getters & setters in pythonic way. Line 15-16 acts as a validation code that raises a ValueError if we try to initialize age with value less than 18, In this way any kind of validation can be applied in getter or setter functions . Akanksha_Rai Picked Python-OOP Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 23761, "s": 23733, "text": "\n04 Dec, 2019" }, { "code": null, "e": 24135, "s": 23761, "text": "In Python, getters and setters are not the same as those in other object-oriented programming languages. Basically, the main purpose of using getters and setters in object-oriented programs is to ensure data encapsulation. Private variables in python are not actually hidden fields like in other object oriented languages. Getters and Setters in python are often used when:" }, { "code": null, "e": 24220, "s": 24135, "text": "We use getters & setters to add validation logic around getting and setting a value." }, { "code": null, "e": 24341, "s": 24220, "text": "To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user." }, { "code": null, "e": 24404, "s": 24341, "text": "Using normal function to achieve getters and setters behaviour" }, { "code": null, "e": 24547, "s": 24404, "text": "To achieve getters & setters property, if we define normal get() and set() methods it will not reflect any special implementation. For Example" }, { "code": "# Python program showing a use# of get() and set() method in# normal function class Geek: def __init__(self, age = 0): self._age = age # getter method def get_age(self): return self._age # setter method def set_age(self, x): self._age = x raj = Geek() # setting the age using setterraj.set_age(21) # retrieving age using getterprint(raj.get_age()) print(raj._age)", "e": 24965, "s": 24547, "text": null }, { "code": null, "e": 24973, "s": 24965, "text": "Output:" }, { "code": null, "e": 24980, "s": 24973, "text": "21\n21\n" }, { "code": null, "e": 25177, "s": 24980, "text": "In above code functions get_age() and set_age() acts as normal functions and doesn’t play any impact as getters and setters, to achieve such functionality Python has a special function property()." }, { "code": null, "e": 25244, "s": 25177, "text": "Using property() function to achieve getters and setters behaviour" }, { "code": null, "e": 25807, "s": 25244, "text": "In Python property()is a built-in function that creates and returns a property object. A property object has three methods, getter(), setter(), and delete(). property() function in Python has four arguments property(fget, fset, fdel, doc), fget is a function for retrieving an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. doc creates a docstring for attribute. A property object has three methods, getter(), setter(), and delete() to specify fget, fset and fdel individually. For Example" }, { "code": "# Python program showing a# use of property() function class Geeks: def __init__(self): self._age = 0 # function to get value of _age def get_age(self): print(\"getter method called\") return self._age # function to set value of _age def set_age(self, a): print(\"setter method called\") self._age = a # function to delete _age attribute def del_age(self): del self._age age = property(get_age, set_age, del_age) mark = Geeks() mark.age = 10 print(mark.age)", "e": 26368, "s": 25807, "text": null }, { "code": null, "e": 26414, "s": 26368, "text": "setter method called\ngetter method called\n10\n" }, { "code": null, "e": 26694, "s": 26414, "text": "In above code there is only one print statement at line #25 but output consists of three lines due to setter method set_age() called in line #23 and getter method get_age() called in line #25. Hence age is a property object that helps to keep the access of private variable safe." }, { "code": null, "e": 26762, "s": 26694, "text": "Using @property decorators to achieve getters and setters behaviour" }, { "code": null, "e": 27305, "s": 26762, "text": "In previous method we used property() function in order to achieve getters and setters behaviour. However as mentioned earlier in this post getters and setters are also used for validating the getting and setting of attributes value. There is one more way to implement property function i.e. by using decorator. Python @property is one of the built-in decorators. The main purpose of any decorator is to change your class methods or attributes in such a way so that the user of your class no need to make any change in their code. For Example" }, { "code": "# Python program showing the use of# @property class Geeks: def __init__(self): self._age = 0 # using property decorator # a getter function @property def age(self): print(\"getter method called\") return self._age # a setter function @age.setter def age(self, a): if(a < 18): raise ValueError(\"Sorry you age is below eligibility criteria\") print(\"setter method called\") self._age = a mark = Geeks() mark.age = 19 print(mark.age)", "e": 27843, "s": 27305, "text": null }, { "code": null, "e": 27851, "s": 27843, "text": "Output:" }, { "code": null, "e": 27897, "s": 27851, "text": "setter method called\ngetter method called\n19\n" }, { "code": null, "e": 28201, "s": 27897, "text": "In above code it is clear that how to use @property decorator to create getters & setters in pythonic way. Line 15-16 acts as a validation code that raises a ValueError if we try to initialize age with value less than 18, In this way any kind of validation can be applied in getter or setter functions ." }, { "code": null, "e": 28214, "s": 28201, "text": "Akanksha_Rai" }, { "code": null, "e": 28221, "s": 28214, "text": "Picked" }, { "code": null, "e": 28232, "s": 28221, "text": "Python-OOP" }, { "code": null, "e": 28256, "s": 28232, "text": "Technical Scripter 2018" }, { "code": null, "e": 28263, "s": 28256, "text": "Python" }, { "code": null, "e": 28282, "s": 28263, "text": "Technical Scripter" }, { "code": null, "e": 28380, "s": 28282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28389, "s": 28380, "text": "Comments" }, { "code": null, "e": 28402, "s": 28389, "text": "Old Comments" }, { "code": null, "e": 28437, "s": 28402, "text": "Read a file line by line in Python" }, { "code": null, "e": 28459, "s": 28437, "text": "Enumerate() in Python" }, { "code": null, "e": 28491, "s": 28459, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28521, "s": 28491, "text": "Iterate over a list in Python" }, { "code": null, "e": 28563, "s": 28521, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28589, "s": 28563, "text": "Python String | replace()" }, { "code": null, "e": 28632, "s": 28589, "text": "Python program to convert a list to string" }, { "code": null, "e": 28676, "s": 28632, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28701, "s": 28676, "text": "sum() function in Python" } ]
What is ComponentWillMount() method in ReactJS ? - GeeksforGeeks
31 Oct, 2021 React requires several components to represent a unit of logic for specific functionality. The componentWillMount lifecycle hook is an ideal choice when it comes to updating business logic, app configuration updates, and API calls. The componentWillMount() lifecycle hook is primarily used to implement server-side logic before the actual rendering happens, such as making an API call to the server. The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle. ComponentWillMount() is generally used to show a loader when the component is being loaded or when the data from the server is being fetched. It allows us to modify the contents before displaying them to the end-user, which creates a better impression to the end-user, otherwise, anything can be displayed to the end-user. Because it is a react system-defined method, if we want to achieve the same functionality with the help of writing any custom function then it will not be able to give us the same performance as it is part of the React lifecycle, and hence it is optimized. Before performing any activity the first thing they will call is the constructor and then call for the componentWillMount() function. Inside this function, we can perform some of the important activities like modification of HTML view for the end-users, etc. The next thing will be called to render, as we have already done some modification in the componentWillMount() section the changed value will be displayed at the user end. Javascript componentWillMount() { // Perform the required // activity inside it} // Call the render method to // display the HTML contents.render(){} Creating a react app: Step 1: Run the below command to create a new project npx create-react-app my-app Step 2: The above command will create the app and you can run it by using the below command and you can view your app in your browser. cd my-app npm start Project Structure: It will look like the following App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. ComponentWillMount to manipulate State(): The life-cycle hook componentWillMount() triggers before the initial render, and the function will only trigger once in the lifespan of a component. Once the component gets initiated, the current state value will be overridden with the updated value, but keep in mind this happens once in a lifetime of a component. And the last step is to print the message inside the render() function, as demonstrated below. Javascript import React, { Component } from "react"; class App extends Component{constructor() { super(); this.state = { message: "This is initial message" };} render() { return ( <div> <h2>Update the state</h2> <h3> {this.state.message} </h3> </div> );}}; export default App; Explanation: When we run the above example, the message variable’s value is updated once the component gets initiated; this is the standard way to manipulate the business logic. Output: ComponentWillMount() to Make API Calls: componentWillMount() is to make API calls once the component is initiated and configure the values into the state. To make an API call, use an HttpClient such as Axios, or we can use fetch() to trigger the AJAX call. The function with the fetch() API call is shown below. fetch() is used along with the dummy API URL, which hits the server and fetches the data; in the end, the response is updated into the state variable todo, which contains the object. After getting the response from the API, we can consume the data as per requirements. Below is a complete example of this dummy API URL: https://jsonplaceholder.typicode.com/todos/3 Javascript import React, { Component } from "react"; class ApiCall extends Component { constructor() { super(); this.state = { todo: {} }; } componentWillMount() { fetch("https://jsonplaceholder.typicode.com/todos/3") .then(response => response.json()) .then(json => { this.setState({ todo: json }); }); } render() { const { todo } = this.state; console.log(todo) return ( <div> <p>API call :</p> Todo title : <p>{todo.title}</p> Todo completed : <p>{todo.completed === true ? "true" : "false"}</p> </div> ); }} export default ApiCall; Output: Note: Changing the state value inside componentWillMount will not re-run the component again and again, unlike other life-cycle methods. Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? How to create a multi-page website using React.js ? ReactJS useNavigate() Hook Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24423, "s": 24395, "text": "\n31 Oct, 2021" }, { "code": null, "e": 24656, "s": 24423, "text": "React requires several components to represent a unit of logic for specific functionality. The componentWillMount lifecycle hook is an ideal choice when it comes to updating business logic, app configuration updates, and API calls. " }, { "code": null, "e": 25057, "s": 24656, "text": "The componentWillMount() lifecycle hook is primarily used to implement server-side logic before the actual rendering happens, such as making an API call to the server. The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle." }, { "code": null, "e": 25199, "s": 25057, "text": "ComponentWillMount() is generally used to show a loader when the component is being loaded or when the data from the server is being fetched." }, { "code": null, "e": 25380, "s": 25199, "text": "It allows us to modify the contents before displaying them to the end-user, which creates a better impression to the end-user, otherwise, anything can be displayed to the end-user." }, { "code": null, "e": 25637, "s": 25380, "text": "Because it is a react system-defined method, if we want to achieve the same functionality with the help of writing any custom function then it will not be able to give us the same performance as it is part of the React lifecycle, and hence it is optimized." }, { "code": null, "e": 25771, "s": 25637, "text": "Before performing any activity the first thing they will call is the constructor and then call for the componentWillMount() function." }, { "code": null, "e": 25896, "s": 25771, "text": "Inside this function, we can perform some of the important activities like modification of HTML view for the end-users, etc." }, { "code": null, "e": 26068, "s": 25896, "text": "The next thing will be called to render, as we have already done some modification in the componentWillMount() section the changed value will be displayed at the user end." }, { "code": null, "e": 26079, "s": 26068, "text": "Javascript" }, { "code": "componentWillMount() { // Perform the required // activity inside it} // Call the render method to // display the HTML contents.render(){}", "e": 26226, "s": 26079, "text": null }, { "code": null, "e": 26250, "s": 26228, "text": "Creating a react app:" }, { "code": null, "e": 26304, "s": 26250, "text": "Step 1: Run the below command to create a new project" }, { "code": null, "e": 26332, "s": 26304, "text": "npx create-react-app my-app" }, { "code": null, "e": 26467, "s": 26332, "text": "Step 2: The above command will create the app and you can run it by using the below command and you can view your app in your browser." }, { "code": null, "e": 26487, "s": 26467, "text": "cd my-app\nnpm start" }, { "code": null, "e": 26538, "s": 26487, "text": "Project Structure: It will look like the following" }, { "code": null, "e": 26667, "s": 26538, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 27120, "s": 26667, "text": "ComponentWillMount to manipulate State(): The life-cycle hook componentWillMount() triggers before the initial render, and the function will only trigger once in the lifespan of a component. Once the component gets initiated, the current state value will be overridden with the updated value, but keep in mind this happens once in a lifetime of a component. And the last step is to print the message inside the render() function, as demonstrated below." }, { "code": null, "e": 27133, "s": 27122, "text": "Javascript" }, { "code": "import React, { Component } from \"react\"; class App extends Component{constructor() { super(); this.state = { message: \"This is initial message\" };} render() { return ( <div> <h2>Update the state</h2> <h3> {this.state.message} </h3> </div> );}}; export default App;", "e": 27458, "s": 27133, "text": null }, { "code": null, "e": 27636, "s": 27458, "text": "Explanation: When we run the above example, the message variable’s value is updated once the component gets initiated; this is the standard way to manipulate the business logic." }, { "code": null, "e": 27644, "s": 27636, "text": "Output:" }, { "code": null, "e": 28262, "s": 27644, "text": "ComponentWillMount() to Make API Calls: componentWillMount() is to make API calls once the component is initiated and configure the values into the state. To make an API call, use an HttpClient such as Axios, or we can use fetch() to trigger the AJAX call. The function with the fetch() API call is shown below. fetch() is used along with the dummy API URL, which hits the server and fetches the data; in the end, the response is updated into the state variable todo, which contains the object. After getting the response from the API, we can consume the data as per requirements. Below is a complete example of this" }, { "code": null, "e": 28322, "s": 28262, "text": "dummy API URL: https://jsonplaceholder.typicode.com/todos/3" }, { "code": null, "e": 28333, "s": 28322, "text": "Javascript" }, { "code": "import React, { Component } from \"react\"; class ApiCall extends Component { constructor() { super(); this.state = { todo: {} }; } componentWillMount() { fetch(\"https://jsonplaceholder.typicode.com/todos/3\") .then(response => response.json()) .then(json => { this.setState({ todo: json }); }); } render() { const { todo } = this.state; console.log(todo) return ( <div> <p>API call :</p> Todo title : <p>{todo.title}</p> Todo completed : <p>{todo.completed === true ? \"true\" : \"false\"}</p> </div> ); }} export default ApiCall;", "e": 28992, "s": 28333, "text": null }, { "code": null, "e": 29000, "s": 28992, "text": "Output:" }, { "code": null, "e": 29137, "s": 29000, "text": "Note: Changing the state value inside componentWillMount will not re-run the component again and again, unlike other life-cycle methods." }, { "code": null, "e": 29144, "s": 29137, "text": "Picked" }, { "code": null, "e": 29160, "s": 29144, "text": "React-Questions" }, { "code": null, "e": 29168, "s": 29160, "text": "ReactJS" }, { "code": null, "e": 29185, "s": 29168, "text": "Web Technologies" }, { "code": null, "e": 29283, "s": 29185, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29292, "s": 29283, "text": "Comments" }, { "code": null, "e": 29305, "s": 29292, "text": "Old Comments" }, { "code": null, "e": 29347, "s": 29305, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 29382, "s": 29347, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 29440, "s": 29382, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 29492, "s": 29440, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 29519, "s": 29492, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 29575, "s": 29519, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29608, "s": 29575, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29670, "s": 29608, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29720, "s": 29670, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Building Recommendation Engines using Pandas - GeeksforGeeks
04 Jan, 2022 In this article, we learn how to build a basic recommendation engine from scratch using Pandas. A Recommendation Engine or Recommender Systems or Recommender Systems is a system that predicts or filters preferences according to each user’s likings. Recommender systems supervise delivering an index of suggestions via collaborative filtering or content-based filtering. A Recommendation Engine is one of the most popular and widely used applications of machine learning. Almost all the big tech companies such as E-Commerce websites, Netflix, Amazon Prime and more uses Recommendation Engines to recommend suitable items or movies to the users. It is based on the instinct that similar types of users are more likely to have similar ratings on similar search items or entities. Now let’s start creating our very basic and simple Recommender Engine using pandas. Let’s concentrate on delivering a simple recommendation engine by presenting things that are most comparable to a certain object based on correlation and number of ratings, in this case, movies. It just tells what movies are considered equivalent to the user’s film choice. To download the files: .tsv file, Movie_Id_Titles.csv. Popularity-based filtering is one of the most basic and not so useful filtering techniques to build a recommender system. It basically filters out the item which is mostly in trend and hides the rest. For example, in our movies dataset if a movie is rated by most of the users that mean it is watched by so many users and is in trend now. So only those movies with a maximum number of ratings will be suggested to the users by the recommender system. There is a lack of personalization as it is not sensitive to some particular taste of a user. Example: At first, we will import the pandas library of python with the help of which we will create the Recommendation Engine. Then we loaded the datasets from the given path in the code below and added the column names to it. Python3 # import pandas libraryimport pandas as pd # Get the column namescol_names = ['user_id', 'item_id', 'rating', 'timestamp'] # Load the datasetpath = 'https://media.geeksforgeeks.org/wp-content/uploads/file.tsv' ratings = pd.read_csv(path, sep='\t', names=col_names) # Check the head of the dataprint(ratings.head()) # Check out all the movies and their respective IDsmovies = pd.read_csv( 'https://media.geeksforgeeks.org/wp-content/uploads/Movie_Id_Titles.csv')print(movies.head()) # We merge the datamovies_merge = pd.merge(ratings, movies, on='item_id')movies_merge.head() Output Now we will rank the movies based on the numbers of ratings on the movies. As we are doing popularity-based filtering, the movies that are watched by more users will have more ratings. Python3 pop_movies = movies_merge.groupby("title")pop_movies["user_id"].count().sort_values( ascending=False).reset_index().rename( columns={"user_id": "score"}) pop_movies['Rank'] = pop_movies['score'].rank( ascending=0, method='first')pop_movies Output Then we visualize the top 10 movies with the most rating count: Python3 import matplotlib.pyplot as plt plt.figure(figsize=(12, 4))plt.barh(pop_movies['title'].head(6), pop_movies['score'].head(6), align='center', color='RED') plt.xlabel("Popularity")plt.title("Popular Movies")plt.gca().invert_yaxis() Output These techniques suggest outcomes to a user that matching users have picked. We can either apply Pearson correlation or cosine similarity for estimating the resemblance between two users. In user-based collaborative filtering, we locate the likeness or similarity score among users. Collaborative filtering takes into count the strength of the mass. For example, if many people watch e-book A and B both and a new user reads only book B, then the recommendation engine will also suggest the user read book A. Instead of calculating the resemblance among various users, item-based collaborative filtering suggests items based on their likeness with the items that the target user ranked. Likewise, the resemblance can be calculated with Pearson Correlation or Cosine Similarity. For example, if user A likes movie P and a new user B is similar to A then the recommender will suggest movie P to user B. The below code demonstrates the user-item-based collaborative filtering. Example: At first, we will import the pandas library of python with the help of which we will create the Recommendation Engine. Then we loaded the datasets from the given path in the code below and added the column names to it. Python3 # import pandas libraryimport pandas as pd # Get the column namescol_names = ['user_id', 'item_id', 'rating', 'timestamp'] # Load the datasetpath = 'https://media.geeksforgeeks.org/\wp-content/uploads/file.tsv' ratings = pd.read_csv(path, sep='\t', names=col_names) # Check the head of the dataprint(ratings.head()) # Check out all the movies and their respective IDsmovies = pd.read_csv( 'https://media.geeksforgeeks.org/\ wp-content/uploads/Movie_Id_Titles.csv')print(movies.head()) Output Now we merge the two datasets on the basis of the item_id which is the common primary key for both. Python3 movies_merge = pd.merge(ratings, movies, on='item_id')movies_merge.head() Output Here we calculate the mean of the number of ratings given to each of the movies. Then we calculate the count of the number of ratings given to each of the movies. We sort them in ascending order as we can see in the output. Python3 print(movies_merge.groupby('title')[ 'rating'].mean().sort_values( ascending=False).head()) print(movies_merge.groupby('title')[ 'rating'].count().sort_values( ascending=False).head()) Output Now we create a new dataframe named ratings_mean_count_data and added the new columns of rating mean and rating count beside each movie title since these two parameters are required for filtering out the best suggestions to the user. Python3 ratings_mean_count_data = pd.DataFrame( movies_merge.groupby('title')['rating'].mean())ratings_mean_count_data['rating_counts'] = pd.DataFrame( movies_merge.groupby('title')['rating'].count())ratings_mean_count_data Output In the newly created dataframe, we can see the movies along with the mean value of ratings and the number of ratings. Now we want to create a matrix to see each user’s rating on each movie. To do so we will do the following code. Python3 user_rating = movies_merge.pivot_table( index='user_id', columns='title', values='rating')user_rating.head() Output Here each column contains all the ratings of all users of a particular movie making it easy for us to find ratings of our movie of choice. Here each column contains all the ratings of all users of a particular movie making it easy for us to find ratings of our movie of choice. So we will see the ratings of Star Wars(1977) as it has got the highest count of ratings. Since we want to find the correlation between movies with the most ratings this will be a good approach. We will see the first 25 ratings. Python3 Star_Wars_ratings = user_rating['Star Wars (1977)']Star_Wars_ratings.head(15) Output Now we will find the movies which correlate with Star Wars(1977) using the corrwith() function. Next, we store the correlation values under column Correlation in a new dataframe called corr_Star_Wars. We removed the NaN values from the new dataset. We displayed the first 10 movies which are highly correlated with Star Wars(1977) in ascending order using the parameter ‘ascending=False’. Python3 movies_like_Star_Wars = user_rating.corrwith(Star_Wars_ratings) corr_Star_Wars = pd.DataFrame(movies_like_Star_Wars, columns=['Correlation'])corr_Star_Wars.dropna(inplace=True)corr_Star_Wars.head(10)corr_Star_Wars.sort_values('Correlation', ascending=False).head(25) Output From the above output, we can see that the movies which are highly correlated with Star Wars(1977) are not all famous and well known. There can be cases where only one user watches a particular movie and give it a 5-star rating. In that case, it will not be a valid rating as no other user has watched it. So correlation only might not be a good metric for filtering out the best suggestion. So we added the column of rating_counts to the data frame to account for the number of ratings along with correlation. Python3 corr_Star_Wars_count = corr_Star_Wars.join( ratings_mean_count_data['rating_counts']) We assumed that the movies which are worth watching will at least have some ratings greater than 100. So the below code filters out the most correlated movies with ratings from more than 100 users. Python3 corr_Star_Wars_count[corr_Star_Wars_count[ 'rating_counts'] > 100].sort_values( 'Correlation', ascending=False).head()corr_Star_Wars_count = corr_Star_Wars_count.reset_index()corr_Star_Wars_count Output We can better visualize see the final set of recommended movies Python3 import matplotlib.pyplot as plt plt.figure(figsize=(12, 4))plt.barh(corr_Star_Wars_count['title'].head(10), abs(corr_Star_Wars_count['Correlation'].head(10)), align='center', color='red')plt.xlabel("Popularity")plt.title("Top 10 Popular Movies")plt.gca().invert_yaxis() Output Therefore the above movies will be recommended to users who have just finished watching or had watched Star Wars(1977). In this way, we can build a very basic recommender system with pandas. For real-time recommender engines definitely, pandas will not fulfill the needs. for that, we will have to implement complex machine learning algorithms and frameworks. Picked Python-pandas Python-projects Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Selecting rows in pandas DataFrame based on conditions Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n04 Jan, 2022" }, { "code": null, "e": 24388, "s": 24292, "text": "In this article, we learn how to build a basic recommendation engine from scratch using Pandas." }, { "code": null, "e": 24662, "s": 24388, "text": "A Recommendation Engine or Recommender Systems or Recommender Systems is a system that predicts or filters preferences according to each user’s likings. Recommender systems supervise delivering an index of suggestions via collaborative filtering or content-based filtering." }, { "code": null, "e": 25070, "s": 24662, "text": "A Recommendation Engine is one of the most popular and widely used applications of machine learning. Almost all the big tech companies such as E-Commerce websites, Netflix, Amazon Prime and more uses Recommendation Engines to recommend suitable items or movies to the users. It is based on the instinct that similar types of users are more likely to have similar ratings on similar search items or entities." }, { "code": null, "e": 25428, "s": 25070, "text": "Now let’s start creating our very basic and simple Recommender Engine using pandas. Let’s concentrate on delivering a simple recommendation engine by presenting things that are most comparable to a certain object based on correlation and number of ratings, in this case, movies. It just tells what movies are considered equivalent to the user’s film choice." }, { "code": null, "e": 25483, "s": 25428, "text": "To download the files: .tsv file, Movie_Id_Titles.csv." }, { "code": null, "e": 26028, "s": 25483, "text": "Popularity-based filtering is one of the most basic and not so useful filtering techniques to build a recommender system. It basically filters out the item which is mostly in trend and hides the rest. For example, in our movies dataset if a movie is rated by most of the users that mean it is watched by so many users and is in trend now. So only those movies with a maximum number of ratings will be suggested to the users by the recommender system. There is a lack of personalization as it is not sensitive to some particular taste of a user." }, { "code": null, "e": 26037, "s": 26028, "text": "Example:" }, { "code": null, "e": 26256, "s": 26037, "text": "At first, we will import the pandas library of python with the help of which we will create the Recommendation Engine. Then we loaded the datasets from the given path in the code below and added the column names to it." }, { "code": null, "e": 26264, "s": 26256, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # Get the column namescol_names = ['user_id', 'item_id', 'rating', 'timestamp'] # Load the datasetpath = 'https://media.geeksforgeeks.org/wp-content/uploads/file.tsv' ratings = pd.read_csv(path, sep='\\t', names=col_names) # Check the head of the dataprint(ratings.head()) # Check out all the movies and their respective IDsmovies = pd.read_csv( 'https://media.geeksforgeeks.org/wp-content/uploads/Movie_Id_Titles.csv')print(movies.head()) # We merge the datamovies_merge = pd.merge(ratings, movies, on='item_id')movies_merge.head()", "e": 26848, "s": 26264, "text": null }, { "code": null, "e": 26855, "s": 26848, "text": "Output" }, { "code": null, "e": 27041, "s": 26855, "text": "Now we will rank the movies based on the numbers of ratings on the movies. As we are doing popularity-based filtering, the movies that are watched by more users will have more ratings." }, { "code": null, "e": 27049, "s": 27041, "text": "Python3" }, { "code": "pop_movies = movies_merge.groupby(\"title\")pop_movies[\"user_id\"].count().sort_values( ascending=False).reset_index().rename( columns={\"user_id\": \"score\"}) pop_movies['Rank'] = pop_movies['score'].rank( ascending=0, method='first')pop_movies", "e": 27295, "s": 27049, "text": null }, { "code": null, "e": 27302, "s": 27295, "text": "Output" }, { "code": null, "e": 27366, "s": 27302, "text": "Then we visualize the top 10 movies with the most rating count:" }, { "code": null, "e": 27374, "s": 27366, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt plt.figure(figsize=(12, 4))plt.barh(pop_movies['title'].head(6), pop_movies['score'].head(6), align='center', color='RED') plt.xlabel(\"Popularity\")plt.title(\"Popular Movies\")plt.gca().invert_yaxis()", "e": 27633, "s": 27374, "text": null }, { "code": null, "e": 27640, "s": 27633, "text": "Output" }, { "code": null, "e": 28149, "s": 27640, "text": "These techniques suggest outcomes to a user that matching users have picked. We can either apply Pearson correlation or cosine similarity for estimating the resemblance between two users. In user-based collaborative filtering, we locate the likeness or similarity score among users. Collaborative filtering takes into count the strength of the mass. For example, if many people watch e-book A and B both and a new user reads only book B, then the recommendation engine will also suggest the user read book A." }, { "code": null, "e": 28541, "s": 28149, "text": "Instead of calculating the resemblance among various users, item-based collaborative filtering suggests items based on their likeness with the items that the target user ranked. Likewise, the resemblance can be calculated with Pearson Correlation or Cosine Similarity. For example, if user A likes movie P and a new user B is similar to A then the recommender will suggest movie P to user B." }, { "code": null, "e": 28614, "s": 28541, "text": "The below code demonstrates the user-item-based collaborative filtering." }, { "code": null, "e": 28623, "s": 28614, "text": "Example:" }, { "code": null, "e": 28842, "s": 28623, "text": "At first, we will import the pandas library of python with the help of which we will create the Recommendation Engine. Then we loaded the datasets from the given path in the code below and added the column names to it." }, { "code": null, "e": 28850, "s": 28842, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # Get the column namescol_names = ['user_id', 'item_id', 'rating', 'timestamp'] # Load the datasetpath = 'https://media.geeksforgeeks.org/\\wp-content/uploads/file.tsv' ratings = pd.read_csv(path, sep='\\t', names=col_names) # Check the head of the dataprint(ratings.head()) # Check out all the movies and their respective IDsmovies = pd.read_csv( 'https://media.geeksforgeeks.org/\\ wp-content/uploads/Movie_Id_Titles.csv')print(movies.head())", "e": 29381, "s": 28850, "text": null }, { "code": null, "e": 29388, "s": 29381, "text": "Output" }, { "code": null, "e": 29488, "s": 29388, "text": "Now we merge the two datasets on the basis of the item_id which is the common primary key for both." }, { "code": null, "e": 29496, "s": 29488, "text": "Python3" }, { "code": "movies_merge = pd.merge(ratings, movies, on='item_id')movies_merge.head()", "e": 29593, "s": 29496, "text": null }, { "code": null, "e": 29600, "s": 29593, "text": "Output" }, { "code": null, "e": 29824, "s": 29600, "text": "Here we calculate the mean of the number of ratings given to each of the movies. Then we calculate the count of the number of ratings given to each of the movies. We sort them in ascending order as we can see in the output." }, { "code": null, "e": 29832, "s": 29824, "text": "Python3" }, { "code": "print(movies_merge.groupby('title')[ 'rating'].mean().sort_values( ascending=False).head()) print(movies_merge.groupby('title')[ 'rating'].count().sort_values( ascending=False).head())", "e": 30030, "s": 29832, "text": null }, { "code": null, "e": 30037, "s": 30030, "text": "Output" }, { "code": null, "e": 30271, "s": 30037, "text": "Now we create a new dataframe named ratings_mean_count_data and added the new columns of rating mean and rating count beside each movie title since these two parameters are required for filtering out the best suggestions to the user." }, { "code": null, "e": 30279, "s": 30271, "text": "Python3" }, { "code": "ratings_mean_count_data = pd.DataFrame( movies_merge.groupby('title')['rating'].mean())ratings_mean_count_data['rating_counts'] = pd.DataFrame( movies_merge.groupby('title')['rating'].count())ratings_mean_count_data", "e": 30501, "s": 30279, "text": null }, { "code": null, "e": 30508, "s": 30501, "text": "Output" }, { "code": null, "e": 30738, "s": 30508, "text": "In the newly created dataframe, we can see the movies along with the mean value of ratings and the number of ratings. Now we want to create a matrix to see each user’s rating on each movie. To do so we will do the following code." }, { "code": null, "e": 30746, "s": 30738, "text": "Python3" }, { "code": "user_rating = movies_merge.pivot_table( index='user_id', columns='title', values='rating')user_rating.head()", "e": 30858, "s": 30746, "text": null }, { "code": null, "e": 30865, "s": 30858, "text": "Output" }, { "code": null, "e": 31004, "s": 30865, "text": "Here each column contains all the ratings of all users of a particular movie making it easy for us to find ratings of our movie of choice." }, { "code": null, "e": 31143, "s": 31004, "text": "Here each column contains all the ratings of all users of a particular movie making it easy for us to find ratings of our movie of choice." }, { "code": null, "e": 31372, "s": 31143, "text": "So we will see the ratings of Star Wars(1977) as it has got the highest count of ratings. Since we want to find the correlation between movies with the most ratings this will be a good approach. We will see the first 25 ratings." }, { "code": null, "e": 31380, "s": 31372, "text": "Python3" }, { "code": "Star_Wars_ratings = user_rating['Star Wars (1977)']Star_Wars_ratings.head(15)", "e": 31458, "s": 31380, "text": null }, { "code": null, "e": 31465, "s": 31458, "text": "Output" }, { "code": null, "e": 31714, "s": 31465, "text": "Now we will find the movies which correlate with Star Wars(1977) using the corrwith() function. Next, we store the correlation values under column Correlation in a new dataframe called corr_Star_Wars. We removed the NaN values from the new dataset." }, { "code": null, "e": 31854, "s": 31714, "text": "We displayed the first 10 movies which are highly correlated with Star Wars(1977) in ascending order using the parameter ‘ascending=False’." }, { "code": null, "e": 31862, "s": 31854, "text": "Python3" }, { "code": "movies_like_Star_Wars = user_rating.corrwith(Star_Wars_ratings) corr_Star_Wars = pd.DataFrame(movies_like_Star_Wars, columns=['Correlation'])corr_Star_Wars.dropna(inplace=True)corr_Star_Wars.head(10)corr_Star_Wars.sort_values('Correlation', ascending=False).head(25)", "e": 32186, "s": 31862, "text": null }, { "code": null, "e": 32193, "s": 32186, "text": "Output" }, { "code": null, "e": 32327, "s": 32193, "text": "From the above output, we can see that the movies which are highly correlated with Star Wars(1977) are not all famous and well known." }, { "code": null, "e": 32499, "s": 32327, "text": "There can be cases where only one user watches a particular movie and give it a 5-star rating. In that case, it will not be a valid rating as no other user has watched it." }, { "code": null, "e": 32704, "s": 32499, "text": "So correlation only might not be a good metric for filtering out the best suggestion. So we added the column of rating_counts to the data frame to account for the number of ratings along with correlation." }, { "code": null, "e": 32712, "s": 32704, "text": "Python3" }, { "code": "corr_Star_Wars_count = corr_Star_Wars.join( ratings_mean_count_data['rating_counts'])", "e": 32801, "s": 32712, "text": null }, { "code": null, "e": 32999, "s": 32801, "text": "We assumed that the movies which are worth watching will at least have some ratings greater than 100. So the below code filters out the most correlated movies with ratings from more than 100 users." }, { "code": null, "e": 33007, "s": 32999, "text": "Python3" }, { "code": "corr_Star_Wars_count[corr_Star_Wars_count[ 'rating_counts'] > 100].sort_values( 'Correlation', ascending=False).head()corr_Star_Wars_count = corr_Star_Wars_count.reset_index()corr_Star_Wars_count", "e": 33207, "s": 33007, "text": null }, { "code": null, "e": 33214, "s": 33207, "text": "Output" }, { "code": null, "e": 33278, "s": 33214, "text": "We can better visualize see the final set of recommended movies" }, { "code": null, "e": 33286, "s": 33278, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt plt.figure(figsize=(12, 4))plt.barh(corr_Star_Wars_count['title'].head(10), abs(corr_Star_Wars_count['Correlation'].head(10)), align='center', color='red')plt.xlabel(\"Popularity\")plt.title(\"Top 10 Popular Movies\")plt.gca().invert_yaxis()", "e": 33582, "s": 33286, "text": null }, { "code": null, "e": 33589, "s": 33582, "text": "Output" }, { "code": null, "e": 33949, "s": 33589, "text": "Therefore the above movies will be recommended to users who have just finished watching or had watched Star Wars(1977). In this way, we can build a very basic recommender system with pandas. For real-time recommender engines definitely, pandas will not fulfill the needs. for that, we will have to implement complex machine learning algorithms and frameworks." }, { "code": null, "e": 33956, "s": 33949, "text": "Picked" }, { "code": null, "e": 33970, "s": 33956, "text": "Python-pandas" }, { "code": null, "e": 33986, "s": 33970, "text": "Python-projects" }, { "code": null, "e": 33993, "s": 33986, "text": "Python" }, { "code": null, "e": 34091, "s": 33993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34123, "s": 34091, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34165, "s": 34123, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 34221, "s": 34165, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 34263, "s": 34221, "text": "Check if element exists in list in Python" }, { "code": null, "e": 34294, "s": 34263, "text": "Python | os.path.join() method" }, { "code": null, "e": 34316, "s": 34294, "text": "Defaultdict in Python" }, { "code": null, "e": 34371, "s": 34316, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 34410, "s": 34371, "text": "Python | Get unique values from a list" }, { "code": null, "e": 34439, "s": 34410, "text": "Create a directory in Python" } ]
ExpressJS - Form data
Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware. To install the body-parser and multer, go to your terminal and use − npm install --save body-parser multer Replace your index.js file contents with the following code − var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var app = express(); app.get('/', function(req, res){ res.render('form'); }); app.set('view engine', 'pug'); app.set('views', './views'); // for parsing application/json app.use(bodyParser.json()); // for parsing application/xwww- app.use(bodyParser.urlencoded({ extended: true })); //form-urlencoded // for parsing multipart/form-data app.use(upload.array()); app.use(express.static('public')); app.post('/', function(req, res){ console.log(req.body); res.send("recieved your request!"); }); app.listen(3000); After importing the body parser and multer, we will use the body-parser for parsing json and x-www-form-urlencoded header requests, while we will use multer for parsing multipart/form-data. Let us create an html form to test this out. Create a new view called form.pug with the following code − html html head title Form Tester body form(action = "/", method = "POST") div label(for = "say") Say: input(name = "say" value = "Hi") br div label(for = "to") To: input(name = "to" value = "Express forms") br button(type = "submit") Send my greetings Run your server using the following. nodemon index.js Now go to localhost:3000/ and fill the form as you like, and submit it. The following response will be displayed − Have a look at your console; it will show you the body of your request as a JavaScript object as in the following screenshot − The req.body object contains your parsed request body. To use fields from that object, just use them like normal JS objects. This is the most recommended way to send a request. There are many other ways, but those are irrelevant to cover here, because our Express app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page. 16 Lectures 1 hours Anadi Sharma Print Add Notes Bookmark this page
[ { "code": null, "e": 2352, "s": 2061, "text": "Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware." }, { "code": null, "e": 2421, "s": 2352, "text": "To install the body-parser and multer, go to your terminal and use −" }, { "code": null, "e": 2460, "s": 2421, "text": "npm install --save body-parser multer\n" }, { "code": null, "e": 2522, "s": 2460, "text": "Replace your index.js file contents with the following code −" }, { "code": null, "e": 3181, "s": 2522, "text": "var express = require('express');\nvar bodyParser = require('body-parser');\nvar multer = require('multer');\nvar upload = multer();\nvar app = express();\n\napp.get('/', function(req, res){\n res.render('form');\n});\n\napp.set('view engine', 'pug');\napp.set('views', './views');\n\n// for parsing application/json\napp.use(bodyParser.json()); \n\n// for parsing application/xwww-\napp.use(bodyParser.urlencoded({ extended: true })); \n//form-urlencoded\n\n// for parsing multipart/form-data\napp.use(upload.array()); \napp.use(express.static('public'));\n\napp.post('/', function(req, res){\n console.log(req.body);\n res.send(\"recieved your request!\");\n});\napp.listen(3000);" }, { "code": null, "e": 3371, "s": 3181, "text": "After importing the body parser and multer, we will use the body-parser for parsing json and x-www-form-urlencoded header requests, while we will use multer for parsing multipart/form-data." }, { "code": null, "e": 3476, "s": 3371, "text": "Let us create an html form to test this out. Create a new view called form.pug with the following code −" }, { "code": null, "e": 3840, "s": 3476, "text": "html\nhtml\n head\n title Form Tester\n body\n form(action = \"/\", method = \"POST\")\n div\n label(for = \"say\") Say:\n input(name = \"say\" value = \"Hi\")\n br\n div\n label(for = \"to\") To:\n input(name = \"to\" value = \"Express forms\")\n br\n button(type = \"submit\") Send my greetings\n" }, { "code": null, "e": 3877, "s": 3840, "text": "Run your server using the following." }, { "code": null, "e": 3895, "s": 3877, "text": "nodemon index.js\n" }, { "code": null, "e": 4010, "s": 3895, "text": "Now go to localhost:3000/ and fill the form as you like, and submit it. The following response will be displayed −" }, { "code": null, "e": 4137, "s": 4010, "text": "Have a look at your console; it will show you the body of your request as a JavaScript object as in the following screenshot −" }, { "code": null, "e": 4262, "s": 4137, "text": "The req.body object contains your parsed request body. To use fields from that object, just use them like normal JS objects." }, { "code": null, "e": 4532, "s": 4262, "text": "This is the most recommended way to send a request. There are many other ways, but those are irrelevant to cover here, because our Express app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page." }, { "code": null, "e": 4565, "s": 4532, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4579, "s": 4565, "text": " Anadi Sharma" }, { "code": null, "e": 4586, "s": 4579, "text": " Print" }, { "code": null, "e": 4597, "s": 4586, "text": " Add Notes" } ]
DOM - Element Object Method - setAttributeNS
The method setAttributeNS adds a new attribute. If an attribute with the same local name and namespace URI is already present on the element, its prefix is changed to be the prefix part of the qualifiedName, and its value is changed to be the value parameter. Following is the syntax for the usage of the setAttributeNS method. elementObj.setAttributeNS(namespace,name,value) namespace It is a string specifying the namespace of the attribute. name It is a string identifying the attribute to be set. value It is the desired string value of the new attribute. node_ns.xml contents are as below − <?xml version = "1.0"?> <Company> <Employee xmlns:e = "http://www.tutorials.com/technical/" category = "technical"> <e:FirstName e:lang = "en">Tanmay</e:FirstName> <e:LastName>Patil</e:LastName> <e:ContactNo>1234567890</e:ContactNo> <e:Email>tanmaypatil@xyz.com</e:Email> </Employee> <Employee xmlns:n = "http://www.tutorials.com/non-technical/" category = "non-technical"> <n:FirstName n:lang = "en">Taniya</n:FirstName> <n:LastName>Mishra</n:LastName> <n:ContactNo>1234667898</n:ContactNo> <n:Email>taniyamishra@xyz.com</n:Email> </Employee> </Company> Following example demonstrates the usage of the setAttributeNS method − <!DOCTYPE html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node_ns.xml"); x = xmlDoc.getElementsByTagName('FirstName')[0]; ns="http://www.tutorials.com/technical/"; document.write("<b>Before using setattributeNS method: </b> "); document.write(x.getAttributeNS(ns,"lang")); x.setAttributeNS(ns,"lang","DE"); document.write("<br><b>After using setattributeNS method: </b> "); document.write(x.getAttributeNS(ns,"lang")); </script> </body> </html> Save this file as elementattribute_setAttributeNS.htm on the server path (this file and node_ns.xml should be on the same path in your server). We will get the output as shown below − Before using setattributeNS method: en After using setattributeNS method: DE 41 Lectures 5 hours Abhishek And Pukhraj 33 Lectures 3.5 hours Abhishek And Pukhraj 15 Lectures 1 hours Zach Miller 15 Lectures 4 hours Prof. Paul Cline, Ed.D 13 Lectures 4 hours Prof. Paul Cline, Ed.D 17 Lectures 2 hours Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2548, "s": 2288, "text": "The method setAttributeNS adds a new attribute. If an attribute with the same local name and namespace URI is already present on the element, its prefix is changed to be the prefix part of the qualifiedName, and its value is changed to be the value parameter." }, { "code": null, "e": 2616, "s": 2548, "text": "Following is the syntax for the usage of the setAttributeNS method." }, { "code": null, "e": 2665, "s": 2616, "text": "elementObj.setAttributeNS(namespace,name,value)\n" }, { "code": null, "e": 2675, "s": 2665, "text": "namespace" }, { "code": null, "e": 2733, "s": 2675, "text": "It is a string specifying the namespace of the attribute." }, { "code": null, "e": 2738, "s": 2733, "text": "name" }, { "code": null, "e": 2790, "s": 2738, "text": "It is a string identifying the attribute to be set." }, { "code": null, "e": 2796, "s": 2790, "text": "value" }, { "code": null, "e": 2849, "s": 2796, "text": "It is the desired string value of the new attribute." }, { "code": null, "e": 2885, "s": 2849, "text": "node_ns.xml contents are as below −" }, { "code": null, "e": 3504, "s": 2885, "text": "<?xml version = \"1.0\"?>\n<Company>\n <Employee xmlns:e = \"http://www.tutorials.com/technical/\" category = \"technical\">\n <e:FirstName e:lang = \"en\">Tanmay</e:FirstName>\n <e:LastName>Patil</e:LastName>\n <e:ContactNo>1234567890</e:ContactNo>\n <e:Email>tanmaypatil@xyz.com</e:Email>\n </Employee>\n \n <Employee xmlns:n = \"http://www.tutorials.com/non-technical/\" category = \"non-technical\">\n <n:FirstName n:lang = \"en\">Taniya</n:FirstName>\n <n:LastName>Mishra</n:LastName>\n <n:ContactNo>1234667898</n:ContactNo>\n <n:Email>taniyamishra@xyz.com</n:Email>\n </Employee>\n</Company>" }, { "code": null, "e": 3576, "s": 3504, "text": "Following example demonstrates the usage of the setAttributeNS method −" }, { "code": null, "e": 4533, "s": 3576, "text": "<!DOCTYPE html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node_ns.xml\");\n x = xmlDoc.getElementsByTagName('FirstName')[0];\n ns=\"http://www.tutorials.com/technical/\";\n document.write(\"<b>Before using setattributeNS method: </b> \");\n document.write(x.getAttributeNS(ns,\"lang\"));\n x.setAttributeNS(ns,\"lang\",\"DE\");\n document.write(\"<br><b>After using setattributeNS method: </b> \");\n document.write(x.getAttributeNS(ns,\"lang\"));\n </script>\n </body>\n</html>" }, { "code": null, "e": 4717, "s": 4533, "text": "Save this file as elementattribute_setAttributeNS.htm on the server path (this file and node_ns.xml should be on the same path in your server). We will get the output as shown below −" }, { "code": null, "e": 4795, "s": 4717, "text": "Before using setattributeNS method: en\nAfter using setattributeNS method: DE\n" }, { "code": null, "e": 4828, "s": 4795, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 4850, "s": 4828, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4885, "s": 4850, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4907, "s": 4885, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4940, "s": 4907, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 4953, "s": 4940, "text": " Zach Miller" }, { "code": null, "e": 4986, "s": 4953, "text": "\n 15 Lectures \n 4 hours \n" }, { "code": null, "e": 5010, "s": 4986, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 5043, "s": 5010, "text": "\n 13 Lectures \n 4 hours \n" }, { "code": null, "e": 5067, "s": 5043, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 5100, "s": 5067, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 5117, "s": 5100, "text": " Laurence Svekis" }, { "code": null, "e": 5124, "s": 5117, "text": " Print" }, { "code": null, "e": 5135, "s": 5124, "text": " Add Notes" } ]
floor() and ceil() function Python - GeeksforGeeks
28 Oct, 2021 floor() method in Python returns the floor of x i.e., the largest integer not greater than x. Syntax: import math math.floor(x) Parameter: x-numeric expression. Returns: largest integer not greater than x. Below is the Python implementation of floor() method: Python # Python program to demonstrate the use of floor() method # This will import math moduleimport math # prints the ceil using floor() methodprint "math.floor(-23.11) : ", math.floor(-23.11)print "math.floor(300.16) : ", math.floor(300.16)print "math.floor(300.72) : ", math.floor(300.72) Output: math.floor(-23.11) : -24.0 math.floor(300.16) : 300.0 math.floor(300.72) : 300.0 The method ceil(x) in Python returns a ceiling value of x i.e., the smallest integer greater than or equal to x. Syntax: import math math.ceil(x) Parameter: x:This is a numeric expression. Returns: Smallest integer not less than x. Below is the Python implementation of ceil() method: Python # Python program to demonstrate the use of ceil() method # This will import math moduleimport math # prints the ceil using ceil() methodprint "math.ceil(-23.11) : ", math.ceil(-23.11)print "math.ceil(300.16) : ", math.ceil(300.16)print "math.ceil(300.72) : ", math.ceil(300.72) Output: math.ceil(-23.11) : -23.0 math.ceil(300.16) : 301.0 math.ceil(300.72) : 301.0 reachtoshasidhar07 atulyatib Python-Built-in-functions Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 23979, "s": 23951, "text": "\n28 Oct, 2021" }, { "code": null, "e": 24074, "s": 23979, "text": "floor() method in Python returns the floor of x i.e., the largest integer not greater than x. " }, { "code": null, "e": 24191, "s": 24074, "text": "Syntax:\nimport math\nmath.floor(x)\n\nParameter: \nx-numeric expression. \n\nReturns: \nlargest integer not greater than x." }, { "code": null, "e": 24246, "s": 24191, "text": "Below is the Python implementation of floor() method: " }, { "code": null, "e": 24253, "s": 24246, "text": "Python" }, { "code": "# Python program to demonstrate the use of floor() method # This will import math moduleimport math # prints the ceil using floor() methodprint \"math.floor(-23.11) : \", math.floor(-23.11)print \"math.floor(300.16) : \", math.floor(300.16)print \"math.floor(300.72) : \", math.floor(300.72)", "e": 24544, "s": 24253, "text": null }, { "code": null, "e": 24553, "s": 24544, "text": "Output: " }, { "code": null, "e": 24637, "s": 24553, "text": "math.floor(-23.11) : -24.0\nmath.floor(300.16) : 300.0\nmath.floor(300.72) : 300.0" }, { "code": null, "e": 24750, "s": 24637, "text": "The method ceil(x) in Python returns a ceiling value of x i.e., the smallest integer greater than or equal to x." }, { "code": null, "e": 24873, "s": 24750, "text": "Syntax: \nimport math\nmath.ceil(x)\n\nParameter:\nx:This is a numeric expression.\n\nReturns: \nSmallest integer not less than x." }, { "code": null, "e": 24927, "s": 24873, "text": "Below is the Python implementation of ceil() method: " }, { "code": null, "e": 24934, "s": 24927, "text": "Python" }, { "code": "# Python program to demonstrate the use of ceil() method # This will import math moduleimport math # prints the ceil using ceil() methodprint \"math.ceil(-23.11) : \", math.ceil(-23.11)print \"math.ceil(300.16) : \", math.ceil(300.16)print \"math.ceil(300.72) : \", math.ceil(300.72)", "e": 25217, "s": 24934, "text": null }, { "code": null, "e": 25226, "s": 25217, "text": "Output: " }, { "code": null, "e": 25307, "s": 25226, "text": "math.ceil(-23.11) : -23.0\nmath.ceil(300.16) : 301.0\nmath.ceil(300.72) : 301.0" }, { "code": null, "e": 25326, "s": 25307, "text": "reachtoshasidhar07" }, { "code": null, "e": 25336, "s": 25326, "text": "atulyatib" }, { "code": null, "e": 25362, "s": 25336, "text": "Python-Built-in-functions" }, { "code": null, "e": 25377, "s": 25362, "text": "Python-Library" }, { "code": null, "e": 25384, "s": 25377, "text": "Python" }, { "code": null, "e": 25482, "s": 25384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25491, "s": 25482, "text": "Comments" }, { "code": null, "e": 25504, "s": 25491, "text": "Old Comments" }, { "code": null, "e": 25522, "s": 25504, "text": "Python Dictionary" }, { "code": null, "e": 25557, "s": 25522, "text": "Read a file line by line in Python" }, { "code": null, "e": 25579, "s": 25557, "text": "Enumerate() in Python" }, { "code": null, "e": 25611, "s": 25579, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25641, "s": 25611, "text": "Iterate over a list in Python" }, { "code": null, "e": 25683, "s": 25641, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25709, "s": 25683, "text": "Python String | replace()" }, { "code": null, "e": 25746, "s": 25709, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25789, "s": 25746, "text": "Python program to convert a list to string" } ]
Progression - Solved Examples
Q 1 - Locate the ninth term and sixteenth term of the A.P. 5,8,11, 14, 17... A - 40 B - 50 C - 60 D - 70 Answer - B Explanation In the given A.P. we have a=5, d= (8-5) = 3 ∴ Tn= a+ (n-1) d= 5+ (n-1)3 = 3n+2 T16= (3*16+2) = 50 Q 2 - Which term of the A.P. 4,9,14, 19 ... is 109? A - 22nd B - 23rd C - 24th D - 25th Answer - A Explanation We have a =4 and d= (9-4) = 5 Let the nth term 109. At that point (a+ (n-1) d= 109 ⇒ 4+ (n-1)*5 =109 (n-1)*5= 105 ⇒ (n-1) = 21 ⇒ n= 22 ∴ 22nd term is 109. Q 3 - What numbers of term arrive in the A.P. 7, 13, 19, 25... 205? A - 34 B - 35 C - 36 D - 37 Answer - A Explanation Let the given A.P contain A.P. contain n terms. At that point, A=7, d = (13-7)= 6 and Tn = 205 ∴ a+ (n-1) d =205 ⇒ 7+ (n-1)*6 = 198 ⇒ (n-1) =33 ⇒ n = 34 Given A.P contains 34 terms. Q 4 - The sixth term of an A.P. is 12 and its eighth term is 22. Locate its first term, normal contrast and sixteenth term. A - 61 B - 62 C - 63 D - 64 Answer - B Explanation Let, first term = a and normal contrast =d. T6 = 12 ⇒ a+5d= 12 .... (i) T8= 22 ⇒ a+7d = 22 ... (ii) On subtracting (i) from (ii), we get 2d = 10 ⇒ d = 5 Putting d= 5 in (i), we get a+5*5 = 12 ⇒ a= (12-25) =-13 ∴ First term = - 13, normal distinction = 5. T16= a+ 15d = - 13+15*5 = (75-13) = 62 Q 5 - Discover the whole of initial 17 terms of the A.P. 5, 9, 13, 17... A - 627 B - 628 C - 629 D - 630 Answer - C Explanation Here a =5, d= (9-5) = 4 and n = 17 Sn = n/2[2a+ (n-1) d] S17 = 17/2 [2*5+ (17-1)*4] = (17/2*74) = 629 Q 6 - Discover the sum of the arrangement = 2+5+8+...+182. A - 5612 B - 5712 C - 5812 D - 5912 Answer - A Explanation Here a = 2, d = (5-2) = 3 and Tn = 182. Tn = 182 ⇒ a+ (n-1) d = 182 ⇒ 2+ (n-1)*3 = 182 ⇒ 3n = 183 ⇒ n= 61. Sn = n/2[2a+ (n-1) d] =61/2 {2*2+(61-1)*3} = (61/2* 184) = (61*92) = 5612. Q 7 - Discover three numbers in A.P. whose sum is 15 and item is 80. A - 1,4 and 9 or 9,4, and 1 B - 3,5 and 9 or 9,5, and 3 C - 3,6 and 9 or 9,6, and 3 D - 2,5 and 8 or 8,5, and 2 Answer - D Explanation Let the numbers be (a-d), an and (a+d). At that point, (a-d) +a+ (a+d) = 15 ⇒ 3a = 15 ⇒ a = 5 (a-d)*a*(a+d) = 80 ⇒ (5-d)*5 * (5+d) = 80 ⇒ (25-d2) = 16 = d2 =9 ⇒ d = 3 Numbers are 2, 5, 8 or 8, 5, 2. Q 8 - Locate the ninth term and the nth term of the G.P. 3,6,12, 24 ... A - 738, 4n-1 B - 748, 5n-1 C - 758, 6n-1 D - 768, 6n-1 Answer - D Explanation Given numbers are in G.P in which a= 3 and r =6/3 = 2. ∴ Tn = arn-1 ⇒ T9= 3*28 = (3*256) = 768 Tn = 3*2n-1 = 6n-1 Q 9 - On the off chance that the fourth and ninth terms of A G.P. are 54 and 13122 individually, locate the first term, regular proportion and its sixth term. A - 476 B - 486 C - 496 D - 506 Answer - B Explanation Let A be the first term and r be the basic proportion. At that point, T4 = 54 ⇒ ar3 =54 ... (i) T4 = 13122 ⇒ ar8 = 13122 ...(ii) On isolating (ii) by (i) , we get r5 = 13122/54 = 243 =(3)5 ⇒ r =3 Putting r =3 in (i), we get a*27 =54 ⇒ a = 2 ∴ First term =2 and common ratio =3. T6= ar5 = 2*35= 486. Hence, 6th term = 486. 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 3969, "s": 3892, "text": "Q 1 - Locate the ninth term and sixteenth term of the A.P. 5,8,11, 14, 17..." }, { "code": null, "e": 3976, "s": 3969, "text": "A - 40" }, { "code": null, "e": 3983, "s": 3976, "text": "B - 50" }, { "code": null, "e": 3990, "s": 3983, "text": "C - 60" }, { "code": null, "e": 3997, "s": 3990, "text": "D - 70" }, { "code": null, "e": 4008, "s": 3997, "text": "Answer - B" }, { "code": null, "e": 4020, "s": 4008, "text": "Explanation" }, { "code": null, "e": 4121, "s": 4020, "text": "In the given A.P. we have a=5, d= (8-5) = 3 \n∴ Tn= a+ (n-1) d= 5+ (n-1)3 = 3n+2 \nT16= (3*16+2) = 50\n" }, { "code": null, "e": 4173, "s": 4121, "text": "Q 2 - Which term of the A.P. 4,9,14, 19 ... is 109?" }, { "code": null, "e": 4183, "s": 4173, "text": "A - 22nd " }, { "code": null, "e": 4193, "s": 4183, "text": "B - 23rd " }, { "code": null, "e": 4203, "s": 4193, "text": "C - 24th " }, { "code": null, "e": 4213, "s": 4203, "text": "D - 25th " }, { "code": null, "e": 4224, "s": 4213, "text": "Answer - A" }, { "code": null, "e": 4236, "s": 4224, "text": "Explanation" }, { "code": null, "e": 4396, "s": 4236, "text": "We have a =4 and d= (9-4) = 5 \nLet the nth term 109. At that point \n(a+ (n-1) d= 109 ⇒ 4+ (n-1)*5 =109 \n(n-1)*5= 105 ⇒ (n-1) = 21 ⇒ n= 22 \n∴ 22nd term is 109.\n" }, { "code": null, "e": 4465, "s": 4396, "text": "Q 3 - What numbers of term arrive in the A.P. 7, 13, 19, 25... 205? " }, { "code": null, "e": 4472, "s": 4465, "text": "A - 34" }, { "code": null, "e": 4479, "s": 4472, "text": "B - 35" }, { "code": null, "e": 4486, "s": 4479, "text": "C - 36" }, { "code": null, "e": 4493, "s": 4486, "text": "D - 37" }, { "code": null, "e": 4504, "s": 4493, "text": "Answer - A" }, { "code": null, "e": 4516, "s": 4504, "text": "Explanation" }, { "code": null, "e": 4703, "s": 4516, "text": "Let the given A.P contain A.P. contain n terms. At that point, \nA=7, d = (13-7)= 6 and Tn = 205 \n∴ a+ (n-1) d =205 ⇒ 7+ (n-1)*6 = 198 ⇒ (n-1) =33 ⇒ n = 34 \nGiven A.P contains 34 terms. \n" }, { "code": null, "e": 4827, "s": 4703, "text": "Q 4 - The sixth term of an A.P. is 12 and its eighth term is 22. Locate its first term, normal contrast and sixteenth term." }, { "code": null, "e": 4834, "s": 4827, "text": "A - 61" }, { "code": null, "e": 4841, "s": 4834, "text": "B - 62" }, { "code": null, "e": 4848, "s": 4841, "text": "C - 63" }, { "code": null, "e": 4855, "s": 4848, "text": "D - 64" }, { "code": null, "e": 4866, "s": 4855, "text": "Answer - B" }, { "code": null, "e": 4878, "s": 4866, "text": "Explanation" }, { "code": null, "e": 5179, "s": 4878, "text": "Let, first term = a and normal contrast =d. \nT6 = 12 ⇒ a+5d= 12 .... (i) \nT8= 22 ⇒ a+7d = 22 ... (ii) \nOn subtracting (i) from (ii), we get 2d = 10 ⇒ d = 5 \nPutting d= 5 in (i), we get a+5*5 = 12 ⇒ a= (12-25) =-13 \n∴ First term = - 13, normal distinction = 5. \nT16= a+ 15d = - 13+15*5 = (75-13) = 62\n" }, { "code": null, "e": 5252, "s": 5179, "text": "Q 5 - Discover the whole of initial 17 terms of the A.P. 5, 9, 13, 17..." }, { "code": null, "e": 5260, "s": 5252, "text": "A - 627" }, { "code": null, "e": 5268, "s": 5260, "text": "B - 628" }, { "code": null, "e": 5276, "s": 5268, "text": "C - 629" }, { "code": null, "e": 5284, "s": 5276, "text": "D - 630" }, { "code": null, "e": 5295, "s": 5284, "text": "Answer - C" }, { "code": null, "e": 5307, "s": 5295, "text": "Explanation" }, { "code": null, "e": 5412, "s": 5307, "text": "Here a =5, d= (9-5) = 4 and n = 17 \nSn = n/2[2a+ (n-1) d] \nS17 = 17/2 [2*5+ (17-1)*4] = (17/2*74) = 629\n" }, { "code": null, "e": 5472, "s": 5412, "text": "Q 6 - Discover the sum of the arrangement = 2+5+8+...+182. " }, { "code": null, "e": 5481, "s": 5472, "text": "A - 5612" }, { "code": null, "e": 5490, "s": 5481, "text": "B - 5712" }, { "code": null, "e": 5499, "s": 5490, "text": "C - 5812" }, { "code": null, "e": 5508, "s": 5499, "text": "D - 5912" }, { "code": null, "e": 5519, "s": 5508, "text": "Answer - A" }, { "code": null, "e": 5531, "s": 5519, "text": "Explanation" }, { "code": null, "e": 5718, "s": 5531, "text": "Here a = 2, d = (5-2) = 3 and Tn = 182. \nTn = 182 ⇒ a+ (n-1) d = 182 ⇒ 2+ (n-1)*3 = 182 ⇒ 3n = 183 ⇒ n= 61. \nSn = n/2[2a+ (n-1) d] \n=61/2 {2*2+(61-1)*3} = (61/2* 184) = (61*92) = 5612. \n" }, { "code": null, "e": 5787, "s": 5718, "text": "Q 7 - Discover three numbers in A.P. whose sum is 15 and item is 80." }, { "code": null, "e": 5815, "s": 5787, "text": "A - 1,4 and 9 or 9,4, and 1" }, { "code": null, "e": 5843, "s": 5815, "text": "B - 3,5 and 9 or 9,5, and 3" }, { "code": null, "e": 5871, "s": 5843, "text": "C - 3,6 and 9 or 9,6, and 3" }, { "code": null, "e": 5899, "s": 5871, "text": "D - 2,5 and 8 or 8,5, and 2" }, { "code": null, "e": 5910, "s": 5899, "text": "Answer - D" }, { "code": null, "e": 5922, "s": 5910, "text": "Explanation" }, { "code": null, "e": 6127, "s": 5922, "text": "Let the numbers be (a-d), an and (a+d). At that point, \n(a-d) +a+ (a+d) = 15 ⇒ 3a = 15 ⇒ a = 5 \n(a-d)*a*(a+d) = 80 ⇒ (5-d)*5 * (5+d) = 80 \n⇒ (25-d2) = 16 = d2 =9 ⇒ d = 3 \nNumbers are 2, 5, 8 or 8, 5, 2. \n" }, { "code": null, "e": 6199, "s": 6127, "text": "Q 8 - Locate the ninth term and the nth term of the G.P. 3,6,12, 24 ..." }, { "code": null, "e": 6213, "s": 6199, "text": "A - 738, 4n-1" }, { "code": null, "e": 6227, "s": 6213, "text": "B - 748, 5n-1" }, { "code": null, "e": 6241, "s": 6227, "text": "C - 758, 6n-1" }, { "code": null, "e": 6255, "s": 6241, "text": "D - 768, 6n-1" }, { "code": null, "e": 6266, "s": 6255, "text": "Answer - D" }, { "code": null, "e": 6278, "s": 6266, "text": "Explanation" }, { "code": null, "e": 6395, "s": 6278, "text": "Given numbers are in G.P in which a= 3 and r =6/3 = 2. \n∴ Tn = arn-1 ⇒ T9= 3*28 = (3*256) = 768 \nTn = 3*2n-1 = 6n-1\n" }, { "code": null, "e": 6554, "s": 6395, "text": "Q 9 - On the off chance that the fourth and ninth terms of A G.P. are 54 and 13122 individually, locate the first term, regular proportion and its sixth term." }, { "code": null, "e": 6562, "s": 6554, "text": "A - 476" }, { "code": null, "e": 6570, "s": 6562, "text": "B - 486" }, { "code": null, "e": 6578, "s": 6570, "text": "C - 496" }, { "code": null, "e": 6586, "s": 6578, "text": "D - 506" }, { "code": null, "e": 6597, "s": 6586, "text": "Answer - B" }, { "code": null, "e": 6609, "s": 6597, "text": "Explanation" }, { "code": null, "e": 6937, "s": 6609, "text": "Let A be the first term and r be the basic proportion. At that point, \nT4 = 54 ⇒ ar3 =54 ... (i) \nT4 = 13122 ⇒ ar8 = 13122 ...(ii) \nOn isolating (ii) by (i) , we get r5 = 13122/54 = 243 =(3)5 ⇒ r =3 \nPutting r =3 in (i), we get a*27 =54 ⇒ a = 2 \n∴ First term =2 and common ratio =3.\nT6= ar5 = 2*35= 486. Hence, 6th term = 486.\n" }, { "code": null, "e": 6973, "s": 6937, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 6991, "s": 6973, "text": " Programming Line" }, { "code": null, "e": 6998, "s": 6991, "text": " Print" }, { "code": null, "e": 7009, "s": 6998, "text": " Add Notes" } ]
PHP - Facebook Login
We can use Facebook login to allow the users to get access into the websites. This page will explain you about login with facebook PHP SDK. Need to go https://developers.facebook.com/apps/ and click on add a new group button to make the app ID. Need to go https://developers.facebook.com/apps/ and click on add a new group button to make the app ID. Choose Website Choose Website Give an app name and click on Create New Facebook App ID Give an app name and click on Create New Facebook App ID Click on Create app ID Click on Create app ID Click on Skip Quick Test Click on Skip Quick Test On Final stage, it will show as below shown image. Now open fbconfig.php file and add you app ID and app Secrete Now open fbconfig.php file and add you app ID and app Secrete FacebookSession::setDefaultApplication( 'your app ID','App Secrete ' ); // login helper with redirect_uri $helper = new FacebookRedirectLoginHelper('You web address' ); Finally fbconfig.php file as shown below − <?php session_start(); // added in v4.0.0 require_once 'autoload.php'; use Facebook\FacebookSession; use Facebook\FacebookRedirectLoginHelper; use Facebook\FacebookRequest; use Facebook\FacebookResponse; use Facebook\FacebookSDKException; use Facebook\FacebookRequestException; use Facebook\FacebookAuthorizationException; use Facebook\GraphObject; use Facebook\Entities\AccessToken; use Facebook\HttpClients\FacebookCurlHttpClient; use Facebook\HttpClients\FacebookHttpable; // init app with app id and secret FacebookSession::setDefaultApplication( '496544657159182','e6d239655aeb3e496e52fabeaf1b1f93' ); // login helper with redirect_uri $helper = new FacebookRedirectLoginHelper('http://www.tutorialspoint.com/' ); try { $session = $helper->getSessionFromRedirect(); }catch( FacebookRequestException $ex ) { // When Facebook returns an error }catch( Exception $ex ) { // When validation fails or other local issues } // see if we have a session if ( isset( $session ) ) { // graph api request for user data $request = new FacebookRequest( $session, 'GET', '/me' ); $response = $request->execute(); // get response $graphObject = $response->getGraphObject(); $fbid = $graphObject->getProperty('id'); // To Get Facebook ID $fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name $femail = $graphObject->getProperty('email'); // To Get Facebook email ID /* ---- Session Variables -----*/ $_SESSION['FBID'] = $fbid; $_SESSION['FULLNAME'] = $fbfullname; $_SESSION['EMAIL'] = $femail; /* ---- header location after session ----*/ header("Location: index.php"); }else { $loginUrl = $helper->getLoginUrl(); header("Location: ".$loginUrl); } ?> Login page is used to login into FB <?php session_start(); session_unset(); $_SESSION['FBID'] = NULL; $_SESSION['FULLNAME'] = NULL; $_SESSION['EMAIL'] = NULL; header("Location: index.php"); ?> Index page is as shown below. <?php session_start(); ?> <html xmlns:fb = "http://www.facebook.com/2008/fbml"> <head> <title>Login with Facebook</title> <link href = "http://www.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel = "stylesheet"> </head> <body> <?php if ($_SESSION['FBID']): ?> <!-- After user login --> <div class = "container"> <div class = "hero-unit"> <h1>Hello <?php echo $_SESSION['USERNAME']; ?></h1> <p>Welcome to "facebook login" tutorial</p> </div> <div class = "span4"> <ul class = "nav nav-list"> <li class = "nav-header">Image</li> <li><img src = "https://graph.facebook.com/<?php echo $_SESSION['FBID']; ?>/picture"></li> <li class = "nav-header">Facebook ID</li> <li><?php echo $_SESSION['FBID']; ?></li> <li class = "nav-header">Facebook fullname</li> <li><?php echo $_SESSION['FULLNAME']; ?></li> <li class = "nav-header">Facebook Email</li> <li><?php echo $_SESSION['EMAIL']; ?></li> <div><a href="logout.php">Logout</a></div> </ul> </div> </div> <?php else: ?> <!-- Before login --> <div class = "container"> <h1>Login with Facebook</h1> Not Connected <div> <a href = "fbconfig.php">Login with Facebook</a> </div> <div> <a href = "http://www.tutorialspoint.com" title = "Login with facebook">More information about Tutorialspoint</a> </div> </div> <?php endif ?> </body> </html> It will produce the result. Before trying this example, please logout your face book account in your browser. Below code is used to logout facebook. <?php session_start();. session_unset(); $_SESSION['FBID'] = NULL; $_SESSION['FULLNAME'] = NULL; $_SESSION['EMAIL'] = NULL; header("Location: index.php"); ?> 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2897, "s": 2757, "text": "We can use Facebook login to allow the users to get access into the websites. This page will explain you about login with facebook PHP SDK." }, { "code": null, "e": 3002, "s": 2897, "text": "Need to go https://developers.facebook.com/apps/ and click on add a new group button to make the app ID." }, { "code": null, "e": 3107, "s": 3002, "text": "Need to go https://developers.facebook.com/apps/ and click on add a new group button to make the app ID." }, { "code": null, "e": 3122, "s": 3107, "text": "Choose Website" }, { "code": null, "e": 3137, "s": 3122, "text": "Choose Website" }, { "code": null, "e": 3194, "s": 3137, "text": "Give an app name and click on Create New Facebook App ID" }, { "code": null, "e": 3251, "s": 3194, "text": "Give an app name and click on Create New Facebook App ID" }, { "code": null, "e": 3274, "s": 3251, "text": "Click on Create app ID" }, { "code": null, "e": 3297, "s": 3274, "text": "Click on Create app ID" }, { "code": null, "e": 3322, "s": 3297, "text": "Click on Skip Quick Test" }, { "code": null, "e": 3347, "s": 3322, "text": "Click on Skip Quick Test" }, { "code": null, "e": 3398, "s": 3347, "text": "On Final stage, it will show as below shown image." }, { "code": null, "e": 3460, "s": 3398, "text": "Now open fbconfig.php file and add you app ID and app Secrete" }, { "code": null, "e": 3522, "s": 3460, "text": "Now open fbconfig.php file and add you app ID and app Secrete" }, { "code": null, "e": 3694, "s": 3522, "text": "FacebookSession::setDefaultApplication( 'your app ID','App Secrete ' );\n// login helper with redirect_uri\n $helper = new FacebookRedirectLoginHelper('You web address' );" }, { "code": null, "e": 3737, "s": 3694, "text": "Finally fbconfig.php file as shown below −" }, { "code": null, "e": 5654, "s": 3737, "text": "<?php\n \n session_start();\n \n // added in v4.0.0\n require_once 'autoload.php';\n use Facebook\\FacebookSession;\n use Facebook\\FacebookRedirectLoginHelper;\n use Facebook\\FacebookRequest;\n use Facebook\\FacebookResponse;\n use Facebook\\FacebookSDKException;\n use Facebook\\FacebookRequestException;\n use Facebook\\FacebookAuthorizationException;\n use Facebook\\GraphObject;\n use Facebook\\Entities\\AccessToken;\n use Facebook\\HttpClients\\FacebookCurlHttpClient;\n use Facebook\\HttpClients\\FacebookHttpable;\n \n // init app with app id and secret\n FacebookSession::setDefaultApplication( '496544657159182','e6d239655aeb3e496e52fabeaf1b1f93' );\n \n // login helper with redirect_uri\n $helper = new FacebookRedirectLoginHelper('http://www.tutorialspoint.com/' );\n \n try {\n $session = $helper->getSessionFromRedirect();\n }catch( FacebookRequestException $ex ) {\n // When Facebook returns an error\n }catch( Exception $ex ) {\n // When validation fails or other local issues\n }\n \n // see if we have a session\n if ( isset( $session ) ) {\n // graph api request for user data\n $request = new FacebookRequest( $session, 'GET', '/me' );\n $response = $request->execute();\n \n // get response\n $graphObject = $response->getGraphObject();\n $fbid = $graphObject->getProperty('id'); // To Get Facebook ID\n $fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name\n $femail = $graphObject->getProperty('email'); // To Get Facebook email ID\n \n /* ---- Session Variables -----*/\n $_SESSION['FBID'] = $fbid;\n $_SESSION['FULLNAME'] = $fbfullname;\n $_SESSION['EMAIL'] = $femail;\n \n /* ---- header location after session ----*/\n header(\"Location: index.php\");\n }else {\n $loginUrl = $helper->getLoginUrl();\n header(\"Location: \".$loginUrl);\n }\n?>" }, { "code": null, "e": 5690, "s": 5654, "text": "Login page is used to login into FB" }, { "code": null, "e": 5878, "s": 5690, "text": "<?php\n session_start();\n session_unset();\n \n $_SESSION['FBID'] = NULL;\n $_SESSION['FULLNAME'] = NULL;\n $_SESSION['EMAIL'] = NULL;\n header(\"Location: index.php\"); \n?>" }, { "code": null, "e": 5908, "s": 5878, "text": "Index page is as shown below." }, { "code": null, "e": 7961, "s": 5908, "text": "<?php\n session_start(); \n?>\n<html xmlns:fb = \"http://www.facebook.com/2008/fbml\">\n \n <head>\n <title>Login with Facebook</title>\n <link \n href = \"http://www.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css\" \n rel = \"stylesheet\">\n </head>\n \n <body>\n <?php if ($_SESSION['FBID']): ?> <!-- After user login -->\n \n <div class = \"container\">\n \n <div class = \"hero-unit\">\n <h1>Hello <?php echo $_SESSION['USERNAME']; ?></h1>\n <p>Welcome to \"facebook login\" tutorial</p>\n </div>\n \n <div class = \"span4\">\n\t\t\t\t\n <ul class = \"nav nav-list\">\n <li class = \"nav-header\">Image</li>\n\t\t\t\t\t\t\n <li><img src = \"https://graph.facebook.com/<?php \n echo $_SESSION['FBID']; ?>/picture\"></li>\n \n <li class = \"nav-header\">Facebook ID</li>\n <li><?php echo $_SESSION['FBID']; ?></li>\n \n <li class = \"nav-header\">Facebook fullname</li>\n\t\t\t\t\t\t\n <li><?php echo $_SESSION['FULLNAME']; ?></li>\n \n <li class = \"nav-header\">Facebook Email</li>\n\t\t\t\t\t\t\n <li><?php echo $_SESSION['EMAIL']; ?></li>\n \n <div><a href=\"logout.php\">Logout</a></div>\n\t\t\t\t\t\t\n </ul>\n\t\t\t\t\t\n </div>\n </div>\n \n <?php else: ?> <!-- Before login --> \n \n <div class = \"container\">\n <h1>Login with Facebook</h1>\n Not Connected\n \n <div>\n <a href = \"fbconfig.php\">Login with Facebook</a>\n </div>\n \n <div>\n <a href = \"http://www.tutorialspoint.com\" \n title = \"Login with facebook\">More information about Tutorialspoint</a>\n </div>\n </div>\n \n <?php endif ?>\n \n </body>\n</html>" }, { "code": null, "e": 8071, "s": 7961, "text": "It will produce the result. Before trying this example, please logout your face book account in your browser." }, { "code": null, "e": 8110, "s": 8071, "text": "Below code is used to logout facebook." }, { "code": null, "e": 8300, "s": 8110, "text": "<?php \n session_start();.\n session_unset();\n \n $_SESSION['FBID'] = NULL;\n $_SESSION['FULLNAME'] = NULL;\n $_SESSION['EMAIL'] = NULL;\n header(\"Location: index.php\"); \n?>" }, { "code": null, "e": 8333, "s": 8300, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 8349, "s": 8333, "text": " Malhar Lathkar" }, { "code": null, "e": 8382, "s": 8349, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 8393, "s": 8382, "text": " Syed Raza" }, { "code": null, "e": 8428, "s": 8393, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8445, "s": 8428, "text": " Frahaan Hussain" }, { "code": null, "e": 8478, "s": 8445, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 8493, "s": 8478, "text": " Nivedita Jain" }, { "code": null, "e": 8528, "s": 8493, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 8540, "s": 8528, "text": " Azaz Patel" }, { "code": null, "e": 8575, "s": 8540, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8603, "s": 8575, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 8610, "s": 8603, "text": " Print" }, { "code": null, "e": 8621, "s": 8610, "text": " Add Notes" } ]
How do I run a command on an already existing Docker container?
Suppose you have already created a Docker container previously and have worked with it. Now, you have stopped the container. So, the container is in exited state. What if you want to run a command inside the container? Typically, there can be two cases. Either the container is stopped using the Docker stop command or the container is currently running in the background. In such a case, either you can start the container back, access it’s bash, and execute whatever command that you want. This is perfect for containers that are not running. Another solution is that you use the Docker exec command to run commands in a container that is actively running. For containers that are stopped, you can also start the container using the Docker start command and then run the Docker exec command. Let’s check out all these scenarios one by one. Let’s create a container using the Docker run command. $ docker run -it --name=myubuntu ubuntu:latest bash This command will create an ubuntu container called ubuntu and will open a bash of the container which will allow you to execute commands inside the running container. You can check the status of the container by listing the containers. $ docker ps -a This command will list all the existing containers in your local machine along with their current states. Now, execute the Docker stop command mentioned below to stop the container. $ docker stop myubuntu If you now execute the Docker ps command, you will find that the status of the myubuntu container has now been changed to exited. Now, if you want to run commands inside this stopped container, you will have to first start the container and attach a bash using the following command. $ docker start -ai myubuntu This command will start the container again and you will have access to the bash of the container. You can execute any command that you want here. Another method of executing commands inside Docker containers is by using the Docker exec command. However, you can only use the Docker exec commands on containers that are in running state. Let’s use the Docker run command but using the detached option to run the container in background mode. $ docker run -itd --name=myubuntu ubuntu:latest bash This will run the container in the background mode. You can check the status by listing all the existing containers once again. $ docker ps -a Now, let’s use the Docker exec command to create a file inside the container. The syntax of the Docker exec command is - $ docker exec [OPTIONS] CONTAINER COMMAND [ARG...] $ docker exec myubuntu touch tutorialspoint.txt This command will create a file called tutorialspoint.txt inside the default working directory of the container. You can also use the -w (workdir) flag along with the Docker exec command to specify the path of the directory where you want to execute the command inside the container. If you want to access the bash of a container running in background mode, you can use the -it options and provide the /bin/bash command. $ docker exec -it ubuntu /bin/bash This will open a bash of the container and you will be able to execute commands inside it. Please make sure that after making changes inside the container, you commit the changes using the Docker commit command if you want your changes to persist the next time you start the container. The syntax of the Docker commit command is - $ docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]] To sum up, in this tutorial, you saw two different ways to run commands inside a container that already exists. You know that the Docker run command is used to create or start a new container and then execute commands inside it. But if you already have a container in your system and you want to execute commands inside it, you can use the methods discussed above. Based on whether your container is stopped or running in the background, you can choose any of the methods discussed above.
[ { "code": null, "e": 1281, "s": 1062, "text": "Suppose you have already created a Docker container previously and have worked with it. Now, you have stopped the container. So, the container is in exited state. What if you want to run a command inside the container?" }, { "code": null, "e": 1721, "s": 1281, "text": "Typically, there can be two cases. Either the container is stopped using the Docker stop command or the container is currently running in the background. In such a case, either you can start the container back, access it’s bash, and execute whatever command that you want. This is perfect for containers that are not running. Another solution is that you use the Docker exec command to run commands in a container that is actively running." }, { "code": null, "e": 1904, "s": 1721, "text": "For containers that are stopped, you can also start the container using the Docker start command and then run the Docker exec command. Let’s check out all these scenarios one by one." }, { "code": null, "e": 1959, "s": 1904, "text": "Let’s create a container using the Docker run command." }, { "code": null, "e": 2011, "s": 1959, "text": "$ docker run -it --name=myubuntu ubuntu:latest bash" }, { "code": null, "e": 2179, "s": 2011, "text": "This command will create an ubuntu container called ubuntu and will open a bash of the container which will allow you to execute commands inside the running container." }, { "code": null, "e": 2248, "s": 2179, "text": "You can check the status of the container by listing the containers." }, { "code": null, "e": 2263, "s": 2248, "text": "$ docker ps -a" }, { "code": null, "e": 2369, "s": 2263, "text": "This command will list all the existing containers in your local machine along with their current states." }, { "code": null, "e": 2445, "s": 2369, "text": "Now, execute the Docker stop command mentioned below to stop the container." }, { "code": null, "e": 2468, "s": 2445, "text": "$ docker stop myubuntu" }, { "code": null, "e": 2752, "s": 2468, "text": "If you now execute the Docker ps command, you will find that the status of the myubuntu container has now been changed to exited. Now, if you want to run commands inside this stopped container, you will have to first start the container and attach a bash using the following command." }, { "code": null, "e": 2781, "s": 2752, "text": "$ docker start -ai myubuntu\n" }, { "code": null, "e": 2928, "s": 2781, "text": "This command will start the container again and you will have access to the bash of the container. You can execute any command that you want here." }, { "code": null, "e": 3119, "s": 2928, "text": "Another method of executing commands inside Docker containers is by using the Docker exec command. However, you can only use the Docker exec commands on containers that are in running state." }, { "code": null, "e": 3223, "s": 3119, "text": "Let’s use the Docker run command but using the detached option to run the container in background mode." }, { "code": null, "e": 3276, "s": 3223, "text": "$ docker run -itd --name=myubuntu ubuntu:latest bash" }, { "code": null, "e": 3404, "s": 3276, "text": "This will run the container in the background mode. You can check the status by listing all the existing containers once again." }, { "code": null, "e": 3419, "s": 3404, "text": "$ docker ps -a" }, { "code": null, "e": 3540, "s": 3419, "text": "Now, let’s use the Docker exec command to create a file inside the container. The syntax of the Docker exec command is -" }, { "code": null, "e": 3591, "s": 3540, "text": "$ docker exec [OPTIONS] CONTAINER COMMAND [ARG...]" }, { "code": null, "e": 3640, "s": 3591, "text": "$ docker exec myubuntu touch tutorialspoint.txt\n" }, { "code": null, "e": 3924, "s": 3640, "text": "This command will create a file called tutorialspoint.txt inside the default working directory of the container. You can also use the -w (workdir) flag along with the Docker exec command to specify the path of the directory where you want to execute the command inside the container." }, { "code": null, "e": 4061, "s": 3924, "text": "If you want to access the bash of a container running in background mode, you can use the -it options and provide the /bin/bash command." }, { "code": null, "e": 4096, "s": 4061, "text": "$ docker exec -it ubuntu /bin/bash" }, { "code": null, "e": 4382, "s": 4096, "text": "This will open a bash of the container and you will be able to execute commands inside it. Please make sure that after making changes inside the container, you commit the changes using the Docker commit command if you want your changes to persist the next time you start the container." }, { "code": null, "e": 4427, "s": 4382, "text": "The syntax of the Docker commit command is -" }, { "code": null, "e": 4482, "s": 4427, "text": "$ docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]" }, { "code": null, "e": 4971, "s": 4482, "text": "To sum up, in this tutorial, you saw two different ways to run commands inside a container that already exists. You know that the Docker run command is used to create or start a new container and then execute commands inside it. But if you already have a container in your system and you want to execute commands inside it, you can use the methods discussed above. Based on whether your container is stopped or running in the background, you can choose any of the methods discussed above." } ]
string.char() function in Lua programming
There are so many scenarios where you might want to convert a decimal value into a character representation. The character representation of a decimal or integer value is nothing but the character value, which one can interpret using the ASCII table. In Lua, to convert a decimal value to its internal character value we make use of the string.char() function. string.char(I) In the above syntax, the identifier I represents the decimal value which we want to convert into a character. Let’s consider a very simple example, where you are given different decimal values, and you want to convert them to a character value. Consider the example shown below − Live Demo s = string.char(97) print(s) s = string.char(122) print(s) s = string.char(125) print(s) In the above example, the values passed as argument to the string.char() function are decimal values that correspond to a character. a z } The string.char() function can take multiple arguments as well. Consider the example shown below − Live Demo i = 97 s = string.char(i,i+1,i+2,i+3) print(s) abcd
[ { "code": null, "e": 1313, "s": 1062, "text": "There are so many scenarios where you might want to convert a decimal value into a character representation. The character representation of a decimal or integer value is nothing but the character value, which one can interpret using the ASCII table." }, { "code": null, "e": 1423, "s": 1313, "text": "In Lua, to convert a decimal value to its internal character value we make use of the string.char() function." }, { "code": null, "e": 1438, "s": 1423, "text": "string.char(I)" }, { "code": null, "e": 1548, "s": 1438, "text": "In the above syntax, the identifier I represents the decimal value which we want to convert into a character." }, { "code": null, "e": 1683, "s": 1548, "text": "Let’s consider a very simple example, where you are given different decimal values, and you want to convert them to a character value." }, { "code": null, "e": 1718, "s": 1683, "text": "Consider the example shown below −" }, { "code": null, "e": 1729, "s": 1718, "text": " Live Demo" }, { "code": null, "e": 1818, "s": 1729, "text": "s = string.char(97)\nprint(s)\ns = string.char(122)\nprint(s)\ns = string.char(125)\nprint(s)" }, { "code": null, "e": 1951, "s": 1818, "text": "In the above example, the values passed as argument to the string.char() function are decimal values that correspond to a character." }, { "code": null, "e": 1957, "s": 1951, "text": "a\nz\n}" }, { "code": null, "e": 2021, "s": 1957, "text": "The string.char() function can take multiple arguments as well." }, { "code": null, "e": 2056, "s": 2021, "text": "Consider the example shown below −" }, { "code": null, "e": 2067, "s": 2056, "text": " Live Demo" }, { "code": null, "e": 2114, "s": 2067, "text": "i = 97\ns = string.char(i,i+1,i+2,i+3)\nprint(s)" }, { "code": null, "e": 2119, "s": 2114, "text": "abcd" } ]
Explain the Mandatory Attribute in PowerShell Advanced Function.
We have an example of PowerShell advanced function below and we will try to understand how mandatory parameter works. function math_Operation{ [cmdletbinding()] param([int]$val1,[int]$val2) Write-Host "Multiply : $($val1*$val2)" Write-Host "Addition : $($val1+$val2)" Write-Host "Subtraction : $($val1-$val2)" Write-Host "Divide : $($val1+$val2)" } When you execute the above example and don’t supply values then the script won’t ask you for the values, by default it will take the values and execute the program. See the execution below. PS C:\WINDOWS\system32> math_Operation Multiply : 0 Addition : 0 Subtraction : 0 Divide : 0 Even if you have mentioned two variables (val1,val2) and if you don’t supply them, the function doesn’t ask for the values and takes the null values. To make them necessary, use the Mandatory parameter as shown below. function math_Operation{ [cmdletbinding()] param([parameter(Mandatory=$True)] [int]$val1, [Parameter(Mandatory=$True)] [int]$val2) Write-Host "Multiply : $($val1*$val2)" Write-Host "Addition : $($val1+$val2)" Write-Host "Subtraction : $($val1-$val2)" Write-Host "Divide : $($val1+$val2)" } Output − PS C:\WINDOWS\system32> math_Operation cmdlet math_Operation at command pipeline position 1 Supply values for the following parameters: val1: 20 val2: 10 Multiply : 200 Addition : 30 Subtraction : 10 Divide : 30 As you can see in the output, when you mention the mandatory parameter, the script will ask the values of those variables when you execute without providing values. What happens when you don’t provide the value of the variables, does the mandatory parameter accepts the value? Yes, it does. It accepts the NULL values as default for integer variables. See the output below. PS C:\WINDOWS\system32> math_Operation cmdlet math_Operation at command pipeline position 1 Supply values for the following parameters: val1: val2: Multiply : 0 Addition : 0 Subtraction : 0 Divide : 0 Please remember, above default value 0 is accepted for datatype Integer single variable but if you use the integer array (int[]) then PowerShell will not accept the empty array for example, function print_number{ [cmdletbinding()] param( [parameter(Mandatory=$True)] [int[]]$numbers ) Write-Output "Integer Array" $numbers } Output − PS C:\WINDOWS\system32> print_number cmdlet print_number at command pipeline position 1 Supply values for the following parameters: numbers[0]: print_number : Cannot bind argument to parameter 'numbers' because it is an empty array. At line:1 char:1 + print_number + ~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [print_number], ParameterBindin g ValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAll o wed,print_number But if you provide the empty input for a string value and a string array, they both don’t accept the empty or null strings. function print_String{ [cmdletbinding()] param( [parameter(Mandatory=$True)] [string]$name, [parameter(Mandatory=$True)] [string[]]$names ) $name $names } PS C:\WINDOWS\system32> print_String cmdlet print_String at command pipeline position 1 Supply values for the following parameters: name: print_String : Cannot bind argument to parameter 'name' because it is an empty string. At line:1 char:1 + print_String + ~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [print_String], ParameterBindin g ValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl l owed,print_String Conclusion of the above examples is when mandatory parameter specified, null, or Empty value acceptance depends on the datatype and none of the collections accept the null value.
[ { "code": null, "e": 1180, "s": 1062, "text": "We have an example of PowerShell advanced function below and we will try to understand how mandatory parameter works." }, { "code": null, "e": 1429, "s": 1180, "text": "function math_Operation{\n [cmdletbinding()]\n param([int]$val1,[int]$val2)\n Write-Host \"Multiply : $($val1*$val2)\"\n Write-Host \"Addition : $($val1+$val2)\"\n Write-Host \"Subtraction : $($val1-$val2)\"\n Write-Host \"Divide : $($val1+$val2)\"\n}" }, { "code": null, "e": 1619, "s": 1429, "text": "When you execute the above example and don’t supply values then the script won’t ask you for the values, by default it will take the values and execute the program. See the execution below." }, { "code": null, "e": 1711, "s": 1619, "text": "PS C:\\WINDOWS\\system32> math_Operation\nMultiply : 0\nAddition : 0\nSubtraction : 0\nDivide : 0" }, { "code": null, "e": 1929, "s": 1711, "text": "Even if you have mentioned two variables (val1,val2) and if you don’t supply them, the function doesn’t ask for the values and takes the null values. To make them necessary, use the Mandatory parameter as shown below." }, { "code": null, "e": 2255, "s": 1929, "text": "function math_Operation{\n [cmdletbinding()]\n param([parameter(Mandatory=$True)]\n [int]$val1,\n [Parameter(Mandatory=$True)]\n [int]$val2)\n Write-Host \"Multiply : $($val1*$val2)\"\n Write-Host \"Addition : $($val1+$val2)\"\n Write-Host \"Subtraction : $($val1-$val2)\"\n Write-Host \"Divide : $($val1+$val2)\"\n}" }, { "code": null, "e": 2264, "s": 2255, "text": "Output −" }, { "code": null, "e": 2476, "s": 2264, "text": "PS C:\\WINDOWS\\system32> math_Operation\ncmdlet math_Operation at command pipeline position 1\nSupply values for the following parameters:\nval1: 20\nval2: 10\nMultiply : 200\nAddition : 30\nSubtraction : 10\nDivide : 30" }, { "code": null, "e": 2850, "s": 2476, "text": "As you can see in the output, when you mention the mandatory parameter, the script will ask the values of those variables when you execute without providing values. What happens when you don’t provide the value of the variables, does the mandatory parameter accepts the value? Yes, it does. It accepts the NULL values as default for integer variables. See the output below." }, { "code": null, "e": 3051, "s": 2850, "text": "PS C:\\WINDOWS\\system32> math_Operation\ncmdlet math_Operation at command pipeline position 1\nSupply values for the following parameters:\nval1:\nval2:\nMultiply : 0\nAddition : 0\nSubtraction : 0\nDivide : 0" }, { "code": null, "e": 3241, "s": 3051, "text": "Please remember, above default value 0 is accepted for datatype Integer single variable but if you use the integer array (int[]) then PowerShell will not accept the empty array for example," }, { "code": null, "e": 3403, "s": 3241, "text": "function print_number{\n [cmdletbinding()]\n param(\n [parameter(Mandatory=$True)]\n [int[]]$numbers\n )\n Write-Output \"Integer Array\"\n $numbers\n}" }, { "code": null, "e": 3412, "s": 3403, "text": "Output −" }, { "code": null, "e": 3895, "s": 3412, "text": "PS C:\\WINDOWS\\system32> print_number\ncmdlet print_number at command pipeline position 1\nSupply values for the following parameters:\nnumbers[0]:\nprint_number : Cannot bind argument to parameter 'numbers' because it is an\nempty array.\nAt line:1 char:1\n+ print_number\n+ ~~~~~~~~~~~~\n + CategoryInfo : InvalidData: (:) [print_number], ParameterBindin\ng\n ValidationException\n + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAll\no\n wed,print_number" }, { "code": null, "e": 4019, "s": 3895, "text": "But if you provide the empty input for a string value and a string array, they both don’t accept the empty or null strings." }, { "code": null, "e": 4213, "s": 4019, "text": "function print_String{\n [cmdletbinding()]\n param(\n [parameter(Mandatory=$True)]\n [string]$name,\n [parameter(Mandatory=$True)]\n [string[]]$names\n )\n $name\n $names\n}" }, { "code": null, "e": 4689, "s": 4213, "text": "PS C:\\WINDOWS\\system32> print_String\ncmdlet print_String at command pipeline position 1\nSupply values for the following parameters:\nname:\nprint_String : Cannot bind argument to parameter 'name' because it is an empty\nstring.\nAt line:1 char:1\n+ print_String\n+ ~~~~~~~~~~~~\n + CategoryInfo : InvalidData: (:) [print_String], ParameterBindin\ng\n ValidationException\n + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl\nl\n owed,print_String" }, { "code": null, "e": 4868, "s": 4689, "text": "Conclusion of the above examples is when mandatory parameter specified, null, or Empty value acceptance depends on the datatype and none of the collections accept the null value." } ]
How can Keras be used to load weights from checkpoint and re-evaluate the model using Python?
Tensorflow is a machine learning framework that is provided by Google. It is an open−source framework used in conjunction with Python to implement algorithms, deep learning applications and much more. It is used in research and for production purposes. The ‘tensorflow’ package can be installed on Windows using the below line of code − pip install tensorflow Tensor is a data structure used in TensorFlow. It helps connect edges in a flow diagram. This flow diagram is known as the ‘Data flow graph’. Tensors are nothing but multidimensional array or a list. They can be identified using three main attributes − Rank − It tells about the dimensionality of the tensor. It can be understood as the order of the tensor or the number of dimensions in the tensor that has been defined. Rank − It tells about the dimensionality of the tensor. It can be understood as the order of the tensor or the number of dimensions in the tensor that has been defined. Type − It tells about the data type associated with the elements of the Tensor. It can be a one dimensional, two dimensional or n dimensional tensor. Type − It tells about the data type associated with the elements of the Tensor. It can be a one dimensional, two dimensional or n dimensional tensor. Shape − It is the number of rows and columns together. Shape − It is the number of rows and columns together. Keras means ‘horn’ in Greek. Keras was developed as a part of research for the project ONEIROS (Open ended Neuro-Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems. It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions. Keras is already present within the Tensorflow package. It can be accessed using the below line of code. import tensorflow from tensorflow import keras We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. Following is the code − print("The weights are loaded") model.load_weights(checkpoint_path) print("The model is being re-evaluated") loss, acc = model.evaluate(test_images, test_labels, verbose=2) print("This is the restored model, with accuracy: {:5.3f}%".format(100 * acc)) Code credit − https://www.tensorflow.org/tutorials/keras/save_and_load The Weights are loaded The model is beign re-evaluated 32/32 - 0 - loss:0.4066 - sparse_categorical_accuracy:0.8740 This is the restored model, with accuracy:87.400% This new model is used to map weights to it. This new model is used to map weights to it. The ‘evaluate’ method is used to check how well the model performs on new data. The ‘evaluate’ method is used to check how well the model performs on new data. In addition, the loss when the model is being trained and the accuracy of the model are both determined. In addition, the loss when the model is being trained and the accuracy of the model are both determined. The loss and accuracy are printed on the console. The loss and accuracy are printed on the console.
[ { "code": null, "e": 1315, "s": 1062, "text": "Tensorflow is a machine learning framework that is provided by Google. It is an open−source framework used in conjunction with Python to implement algorithms, deep learning applications and much more. It is used in research and for production purposes." }, { "code": null, "e": 1399, "s": 1315, "text": "The ‘tensorflow’ package can be installed on Windows using the below line of code −" }, { "code": null, "e": 1422, "s": 1399, "text": "pip install tensorflow" }, { "code": null, "e": 1675, "s": 1422, "text": "Tensor is a data structure used in TensorFlow. It helps connect edges in a flow diagram. This flow diagram is known as the ‘Data flow graph’. Tensors are nothing but multidimensional array or a list. They can be identified using three main attributes −" }, { "code": null, "e": 1844, "s": 1675, "text": "Rank − It tells about the dimensionality of the tensor. It can be understood as the order of the tensor or the number of dimensions in the tensor that has been defined." }, { "code": null, "e": 2013, "s": 1844, "text": "Rank − It tells about the dimensionality of the tensor. It can be understood as the order of the tensor or the number of dimensions in the tensor that has been defined." }, { "code": null, "e": 2163, "s": 2013, "text": "Type − It tells about the data type associated with the elements of the Tensor. It can be a one dimensional, two dimensional or n dimensional tensor." }, { "code": null, "e": 2313, "s": 2163, "text": "Type − It tells about the data type associated with the elements of the Tensor. It can be a one dimensional, two dimensional or n dimensional tensor." }, { "code": null, "e": 2368, "s": 2313, "text": "Shape − It is the number of rows and columns together." }, { "code": null, "e": 2423, "s": 2368, "text": "Shape − It is the number of rows and columns together." }, { "code": null, "e": 2966, "s": 2423, "text": "Keras means ‘horn’ in Greek. Keras was developed as a part of research for the project ONEIROS (Open ended Neuro-Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems. It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions." }, { "code": null, "e": 3071, "s": 2966, "text": "Keras is already present within the Tensorflow package. It can be accessed using the below line of code." }, { "code": null, "e": 3118, "s": 3071, "text": "import tensorflow\nfrom tensorflow import keras" }, { "code": null, "e": 3412, "s": 3118, "text": "We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. Following is the code −" }, { "code": null, "e": 3665, "s": 3412, "text": "print(\"The weights are loaded\")\nmodel.load_weights(checkpoint_path)\n\nprint(\"The model is being re-evaluated\")\nloss, acc = model.evaluate(test_images, test_labels, verbose=2)\nprint(\"This is the restored model, with accuracy: {:5.3f}%\".format(100 * acc))" }, { "code": null, "e": 3737, "s": 3665, "text": "Code credit − https://www.tensorflow.org/tutorials/keras/save_and_load" }, { "code": null, "e": 3903, "s": 3737, "text": "The Weights are loaded\nThe model is beign re-evaluated\n32/32 - 0 - loss:0.4066 - sparse_categorical_accuracy:0.8740\nThis is the restored model, with accuracy:87.400%" }, { "code": null, "e": 3948, "s": 3903, "text": "This new model is used to map weights to it." }, { "code": null, "e": 3993, "s": 3948, "text": "This new model is used to map weights to it." }, { "code": null, "e": 4073, "s": 3993, "text": "The ‘evaluate’ method is used to check how well the model performs on new data." }, { "code": null, "e": 4153, "s": 4073, "text": "The ‘evaluate’ method is used to check how well the model performs on new data." }, { "code": null, "e": 4258, "s": 4153, "text": "In addition, the loss when the model is being trained and the accuracy of the model are both determined." }, { "code": null, "e": 4363, "s": 4258, "text": "In addition, the loss when the model is being trained and the accuracy of the model are both determined." }, { "code": null, "e": 4413, "s": 4363, "text": "The loss and accuracy are printed on the console." }, { "code": null, "e": 4463, "s": 4413, "text": "The loss and accuracy are printed on the console." } ]
How to implement Multithreaded queue With Python
In this example, we will create a task queue that holds all the tasks to be executed and a thread pool that interacts with the queue to process its elements individually. We will begin with the question, what is a Queue?. A queue is a data structure that is a collection of different elements maintained in a very specific order. Let me explain by taking a real life example. Assume you stand in line to pay your grocery billat a grocery shop counter, (don't ask me which grocery shop) In a line of people waiting to pay their bills, you will notice the following: 1. People enter at one end of the line and exit from the other end. 2. If person A enters the line before person B, person A will leave the line before person B (unless person B is a celebrity or has more priority). 3. Once everyone has paid their bills, there will be no one left in the line. Well, back to programming where a queue works in a similar fashion. 1. enqueue - Elements added to the end of the queue. 2. dequeue - Elements removed from the beginning of the queue. There is more, First In First Out (FIFO) - elements that are added first will be removed first. Last In First Out (LIFO) - last element that is added will be removed first. The queue module in Python provides a simple implementation of the queue data structure. Each queue can have the following methods. get(): returns the next element. get(): returns the next element. put(): adds a new element. put(): adds a new element. qsize(): number of current elements in queue. qsize(): number of current elements in queue. empty(): returns a Boolean, indicating whether the queue is empty. empty(): returns a Boolean, indicating whether the queue is empty. full(): returns a Boolean, indicating whether the queueis full. full(): returns a Boolean, indicating whether the queueis full. 1. We will create a function which takes an argument x then iterates through the numbers between 1 and itself(x), to perform multiplication. For e.g. when you pass 5 to this function it iterates through 1 to 5 and keep multiplying i.e. 1 times 5, 2 times 5, 3 times 5, 4 times 5, 5 times 5 finally returning the values as a list. def print_multiply(x): output_value = [] for i in range(1, x + 1): output_value.append(i * x) print(f"Output \n *** The multiplication result for the {x} is - {output_value}") print_multiply(5) *** The multiplication result for the 5 is - [5, 10, 15, 20, 25] 2. We will write another function called process_queue() which will attempt to obtain the next element of the queue object. The logic for this quite simple, keep passing the elements until the queue is empty. I will use sleep to delay proceeding a bit. def process_queue(): while True: try: value = my_queue.get(block=False) except queue.Empty: return else: print_multiply(value) time.sleep(2) 3. Create a class, when a new instance is initialized and started, the process_queue() function will be called. class MultiThread(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): print(f" ** Starting the thread - {self.name}") process_queue() print(f" ** Completed the thread - {self.name}") 4. Finally, we will pass the input list of numbers and fill the queue. # setting up variables input_values = [5, 10, 15, 20] # fill the queue my_queue = queue.Queue() for x in input_values: my_queue.put(x) 5. Finally, putting all together. import queue import threading import time # Class class MultiThread(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): print(f"Output \n ** Starting the thread - {self.name}") process_queue() print(f" ** Completed the thread - {self.name}") # Process thr queue def process_queue(): while True: try: value = my_queue.get(block=False) except queue.Empty: return else: print_multiply(value) time.sleep(2) # function to multiply def print_multiply(x): output_value = [] for i in range(1, x + 1): output_value.append(i * x) print(f" \n *** The multiplication result for the {x} is - {output_value}") # Input variables input_values = [2, 4, 6, 5,10,3] # fill the queue my_queue = queue.Queue() for x in input_values: my_queue.put(x) # initializing and starting 3 threads thread1 = MultiThread('First') thread2 = MultiThread('Second') thread3 = MultiThread('Third') thread4 = MultiThread('Fourth') # Start the threads thread1.start() thread2.start() thread3.start() thread4.start() # Join the threads thread1.join() thread2.join() thread3.join() thread4.join() ** Starting the thread - First *** The multiplication result for the 2 is - [2, 4] ** Starting the thread - Second *** The multiplication result for the 4 is - [4, 8, 12, 16] ** Starting the thread - Third *** The multiplication result for the 6 is - [6, 12, 18, 24, 30, 36] ** Starting the thread - Fourth *** The multiplication result for the 5 is - [5, 10, 15, 20, 25] *** The multiplication result for the 10 is - [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] *** The multiplication result for the 3 is - [3, 6, 9] ** Completed the thread - Third ** Completed the thread - Fourth ** Completed the thread - Second ** Completed the thread - First 6. We have successfully implemented queue concept. See, we have 4 threads but there are 6 values to process, so whoever comes first to the Queue will be executed and others will be in line to wait for others to complete. This is similar to a real life, assume there are 3 counters but 10 people waiting to pay their bills so 10 people will be in 3 queues and who ever have completed paying the bills will leave the line and make way for next person.
[ { "code": null, "e": 1233, "s": 1062, "text": "In this example, we will create a task queue that holds all the tasks to be executed and a thread pool that interacts with the queue to process its elements individually." }, { "code": null, "e": 1438, "s": 1233, "text": "We will begin with the question, what is a Queue?. A queue is a data structure that is a collection of different elements maintained in a very specific order. Let me explain by taking a real life example." }, { "code": null, "e": 1548, "s": 1438, "text": "Assume you stand in line to pay your grocery billat a grocery shop counter, (don't ask me which grocery shop)" }, { "code": null, "e": 1627, "s": 1548, "text": "In a line of people waiting to pay their bills, you will notice the following:" }, { "code": null, "e": 1695, "s": 1627, "text": "1. People enter at one end of the line and exit from the other end." }, { "code": null, "e": 1843, "s": 1695, "text": "2. If person A enters the line before person B, person A will leave the line before person B (unless person B is a celebrity or has more priority)." }, { "code": null, "e": 1921, "s": 1843, "text": "3. Once everyone has paid their bills, there will be no one left in the line." }, { "code": null, "e": 1989, "s": 1921, "text": "Well, back to programming where a queue works in a similar fashion." }, { "code": null, "e": 2042, "s": 1989, "text": "1. enqueue - Elements added to the end of the queue." }, { "code": null, "e": 2105, "s": 2042, "text": "2. dequeue - Elements removed from the beginning of the queue." }, { "code": null, "e": 2278, "s": 2105, "text": "There is more, First In First Out (FIFO) - elements that are added first will be removed first. Last In First Out (LIFO) - last element that is added will be removed first." }, { "code": null, "e": 2410, "s": 2278, "text": "The queue module in Python provides a simple implementation of the queue data structure. Each queue can have the following methods." }, { "code": null, "e": 2443, "s": 2410, "text": "get(): returns the next element." }, { "code": null, "e": 2476, "s": 2443, "text": "get(): returns the next element." }, { "code": null, "e": 2503, "s": 2476, "text": "put(): adds a new element." }, { "code": null, "e": 2530, "s": 2503, "text": "put(): adds a new element." }, { "code": null, "e": 2576, "s": 2530, "text": "qsize(): number of current elements in queue." }, { "code": null, "e": 2622, "s": 2576, "text": "qsize(): number of current elements in queue." }, { "code": null, "e": 2689, "s": 2622, "text": "empty(): returns a Boolean, indicating whether the queue is empty." }, { "code": null, "e": 2756, "s": 2689, "text": "empty(): returns a Boolean, indicating whether the queue is empty." }, { "code": null, "e": 2820, "s": 2756, "text": "full(): returns a Boolean, indicating whether the queueis full." }, { "code": null, "e": 2884, "s": 2820, "text": "full(): returns a Boolean, indicating whether the queueis full." }, { "code": null, "e": 3214, "s": 2884, "text": "1.\nWe will create a function which takes an argument x then iterates through the numbers between 1 and itself(x), to perform multiplication. For e.g. when you pass 5 to this function it iterates through 1 to 5 and keep multiplying i.e. 1 times 5, 2 times 5, 3 times 5, 4 times 5, 5 times 5 finally returning the values as a list." }, { "code": null, "e": 3408, "s": 3214, "text": "def print_multiply(x):\noutput_value = []\nfor i in range(1, x + 1):\noutput_value.append(i * x)\nprint(f\"Output \\n *** The multiplication result for the {x} is - {output_value}\")\nprint_multiply(5)" }, { "code": null, "e": 3473, "s": 3408, "text": "*** The multiplication result for the 5 is - [5, 10, 15, 20, 25]" }, { "code": null, "e": 3726, "s": 3473, "text": "2.\nWe will write another function called process_queue() which will attempt to obtain the next element of the queue object.\nThe logic for this quite simple, keep passing the elements until the queue is empty. I will use sleep to delay proceeding a bit." }, { "code": null, "e": 3867, "s": 3726, "text": "def process_queue():\nwhile True:\ntry:\nvalue = my_queue.get(block=False)\nexcept queue.Empty:\nreturn\nelse:\nprint_multiply(value)\ntime.sleep(2)" }, { "code": null, "e": 3979, "s": 3867, "text": "3.\nCreate a class, when a new instance is initialized and started, the process_queue() function will be called." }, { "code": null, "e": 4220, "s": 3979, "text": "class MultiThread(threading.Thread):\ndef __init__(self, name):\nthreading.Thread.__init__(self)\nself.name = name\n\ndef run(self):\nprint(f\" ** Starting the thread - {self.name}\")\nprocess_queue()\nprint(f\" ** Completed the thread - {self.name}\")" }, { "code": null, "e": 4291, "s": 4220, "text": "4.\nFinally, we will pass the input list of numbers and fill the queue." }, { "code": null, "e": 4427, "s": 4291, "text": "# setting up variables\ninput_values = [5, 10, 15, 20]\n\n# fill the queue\nmy_queue = queue.Queue()\nfor x in input_values:\nmy_queue.put(x)" }, { "code": null, "e": 4461, "s": 4427, "text": "5.\nFinally, putting all together." }, { "code": null, "e": 5581, "s": 4461, "text": "import queue\nimport threading\nimport time\n\n# Class\nclass MultiThread(threading.Thread):\ndef __init__(self, name):\nthreading.Thread.__init__(self)\nself.name = name\n\ndef run(self):\nprint(f\"Output \\n ** Starting the thread - {self.name}\")\nprocess_queue()\nprint(f\" ** Completed the thread - {self.name}\")\n\n# Process thr queue\ndef process_queue():\nwhile True:\ntry:\nvalue = my_queue.get(block=False)\nexcept queue.Empty:\nreturn\nelse:\nprint_multiply(value)\ntime.sleep(2)\n\n# function to multiply\ndef print_multiply(x):\noutput_value = []\nfor i in range(1, x + 1):\noutput_value.append(i * x)\nprint(f\" \\n *** The multiplication result for the {x} is - {output_value}\")\n\n# Input variables\ninput_values = [2, 4, 6, 5,10,3]\n\n# fill the queue\nmy_queue = queue.Queue()\nfor x in input_values:\nmy_queue.put(x)\n# initializing and starting 3 threads\nthread1 = MultiThread('First')\nthread2 = MultiThread('Second')\nthread3 = MultiThread('Third')\nthread4 = MultiThread('Fourth')\n\n# Start the threads\nthread1.start()\nthread2.start()\nthread3.start()\nthread4.start()\n\n# Join the threads\nthread1.join()\nthread2.join()\nthread3.join()\nthread4.join()" }, { "code": null, "e": 5664, "s": 5581, "text": "** Starting the thread - First\n*** The multiplication result for the 2 is - [2, 4]" }, { "code": null, "e": 5756, "s": 5664, "text": "** Starting the thread - Second\n*** The multiplication result for the 4 is - [4, 8, 12, 16]" }, { "code": null, "e": 5856, "s": 5756, "text": "** Starting the thread - Third\n*** The multiplication result for the 6 is - [6, 12, 18, 24, 30, 36]" }, { "code": null, "e": 6226, "s": 5856, "text": "** Starting the thread - Fourth\n*** The multiplication result for the 5 is - [5, 10, 15, 20, 25]\n*** The multiplication result for the 10 is - [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n*** The multiplication result for the 3 is - [3, 6, 9] ** Completed the thread - Third\n** Completed the thread - Fourth\n** Completed the thread - Second ** Completed the thread - First" }, { "code": null, "e": 6447, "s": 6226, "text": "6.\nWe have successfully implemented queue concept. See, we have 4 threads but there are 6 values to process, so whoever comes first to the Queue will be executed and others will be in line to wait for others to complete." }, { "code": null, "e": 6676, "s": 6447, "text": "This is similar to a real life, assume there are 3 counters but 10 people waiting to pay their bills so 10 people will be in 3 queues and who ever have completed paying the bills will leave the line and make way for next person." } ]
How to check if a service is running on Android?
Before getting into example, we should know what service is in android. Service is going to do back ground operation without interact with UI and it works even after activity destroy. This example demonstrate about How to check if a service is running on 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"> <TextView android:id = "@+id/text" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Start Service" android:textSize = "25sp" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </android.support.constraint.ConstraintLayout> In the above code, we have taken text view, when user click on text view, it will start service and stop service. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView text = findViewById(R.id.text); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isMyServiceRunning(service.class)) { text.setText("Stoped"); stopService(new Intent(MainActivity.this, service.class)); } else { text.setText("Started"); startService(new Intent(MainActivity.this, service.class)); } } }); } private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } } In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code – package com.example.andy.myapplication; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; public class service extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show(); } } To identify service is working or not, use the following code- ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; To call the above method, use the following code- isMyServiceRunning(service.class) Step 4 − Add the following code to manifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <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> <service android:name = ".service"/> </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 – In the above result is an initial screen, Click on Text view, it will start service as shown below – In the above result, service is startd now click on text view, it will stop service as shown below - Click here to download the project code
[ { "code": null, "e": 1246, "s": 1062, "text": "Before getting into example, we should know what service is in android. Service is going to do back ground operation without interact with UI and it works even after activity destroy." }, { "code": null, "e": 1326, "s": 1246, "text": "This example demonstrate about How to check if a service is running on Android." }, { "code": null, "e": 1455, "s": 1326, "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": 1520, "s": 1455, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2361, "s": 1520, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout 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 <TextView\n android:id = \"@+id/text\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Start Service\"\n android:textSize = \"25sp\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2475, "s": 2361, "text": "In the above code, we have taken text view, when user click on text view, it will start service and stop service." }, { "code": null, "e": 2532, "s": 2475, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3963, "s": 2532, "text": "package com.example.andy.myapplication;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final TextView text = findViewById(R.id.text);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (isMyServiceRunning(service.class)) {\n text.setText(\"Stoped\");\n stopService(new Intent(MainActivity.this, service.class));\n } else {\n text.setText(\"Started\");\n startService(new Intent(MainActivity.this, service.class));\n }\n }\n });\n }\n private boolean isMyServiceRunning(Class<?> serviceClass) {\n ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);\n for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n}" }, { "code": null, "e": 4157, "s": 3963, "text": "In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code –" }, { "code": null, "e": 4785, "s": 4157, "text": "package com.example.andy.myapplication;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.os.IBinder;\nimport android.widget.Toast;\npublic class service extends Service {\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n Toast.makeText(this, \"Service started by user.\", Toast.LENGTH_LONG).show();\n return START_STICKY;\n }\n @Override\n public void onDestroy() {\n super.onDestroy();\n Toast.makeText(this, \"Service destroyed by user.\", Toast.LENGTH_LONG).show();\n }\n}" }, { "code": null, "e": 4848, "s": 4785, "text": "To identify service is working or not, use the following code-" }, { "code": null, "e": 5147, "s": 4848, "text": "ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);\nfor (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n}\nreturn false;" }, { "code": null, "e": 5197, "s": 5147, "text": "To call the above method, use the following code-" }, { "code": null, "e": 5231, "s": 5197, "text": "isMyServiceRunning(service.class)" }, { "code": null, "e": 5279, "s": 5231, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 6037, "s": 5279, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\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 <service android:name = \".service\"/>\n </application>\n</manifest>" }, { "code": null, "e": 6384, "s": 6037, "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": 6485, "s": 6384, "text": "In the above result is an initial screen, Click on Text view, it will start service as shown below –" }, { "code": null, "e": 6586, "s": 6485, "text": "In the above result, service is startd now click on text view, it will stop service as shown below -" }, { "code": null, "e": 6626, "s": 6586, "text": "Click here to download the project code" } ]
How to listen for a WebView finishing loading a URL in Android?
This example demonstrates how do I listen for a webview finishing loading a URL 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. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:textColor="#000000" android:padding="5dp" /> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/textView"/> <Button android:id="@+id/btnLoad" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Load URL" android:layout_alignParentBottom="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { WebView webView; TextView textView; Button btnLoad; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); btnLoad = findViewById(R.id.btnLoad); webView = findViewById(R.id.webView); webView.setWebViewClient(new WebViewClient()); btnLoad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { webView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String weburl) { Toast.makeText(MainActivity.this, "Your WebView is Loaded....", Toast.LENGTH_LONG).show(); } }); webView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int newProgress) { textView.setText("Page loading : " + newProgress + "%"); if (newProgress == 100) { textView.setText("Page Loaded."); } } }); webView.loadUrl("http://www.tutorialspoint.com"); } }); } } 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"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the 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": 1154, "s": 1062, "text": "This example demonstrates how do I listen for a webview finishing loading a URL in android." }, { "code": null, "e": 1282, "s": 1154, "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": 1347, "s": 1282, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2233, "s": 1347, "text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"24sp\"\n android:textColor=\"#000000\"\n android:padding=\"5dp\" />\n <WebView\n android:id=\"@+id/webView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_below=\"@id/textView\"/>\n <Button\n android:id=\"@+id/btnLoad\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Load URL\"\n android:layout_alignParentBottom=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 2290, "s": 2233, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3885, "s": 2290, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n WebView webView;\n TextView textView;\n Button btnLoad;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n btnLoad = findViewById(R.id.btnLoad);\n webView = findViewById(R.id.webView);\n webView.setWebViewClient(new WebViewClient());\n btnLoad.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n webView.setWebViewClient(new WebViewClient() {\n public void onPageFinished(WebView view, String weburl) {\n Toast.makeText(MainActivity.this, \"Your WebView is Loaded....\", Toast.LENGTH_LONG).show();\n }\n });\n webView.setWebChromeClient(new WebChromeClient() {\n public void onProgressChanged(WebView view, int newProgress) {\n textView.setText(\"Page loading : \" + newProgress + \"%\");\n if (newProgress == 100) {\n textView.setText(\"Page Loaded.\");\n }\n }\n });\n webView.loadUrl(\"http://www.tutorialspoint.com\");\n }\n });\n }\n}" }, { "code": null, "e": 3940, "s": 3885, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4693, "s": 3940, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5044, "s": 4693, "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 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": 5085, "s": 5044, "text": "Click here to download the project code." } ]
Java program for Multiplication of Array elements.
To find the product of elements of an array. create an empty variable. (product) Initialize it with 1. In a loop traverse through each element (or get each element from user) multiply each element to product. Print the product. Live Demo import java.util.Arrays; import java.util.Scanner; public class ProductOfArrayOfElements { public static void main(String args[]){ System.out.println("Enter the required size of the array :: "); Scanner s = new Scanner(System.in); int size = s.nextInt(); int myArray[] = new int [size]; int product = 1; System.out.println("Enter the elements of the array one by one "); for(int i=0; i<size; i++){ myArray[i] = s.nextInt(); product = product * myArray[i]; } System.out.println("Elements of the array are: "+Arrays.toString(myArray)); System.out.println("Sum of the elements of the array ::"+product); } } Enter the required size of the array: 5 Enter the elements of the array one by one 11 65 22 18 47 Elements of the array are: [11, 65, 22, 18, 47] Sum of the elements of the array:13307580
[ { "code": null, "e": 1107, "s": 1062, "text": "To find the product of elements of an array." }, { "code": null, "e": 1143, "s": 1107, "text": "create an empty variable. (product)" }, { "code": null, "e": 1165, "s": 1143, "text": "Initialize it with 1." }, { "code": null, "e": 1271, "s": 1165, "text": "In a loop traverse through each element (or get each element from user) multiply each element to product." }, { "code": null, "e": 1290, "s": 1271, "text": "Print the product." }, { "code": null, "e": 1301, "s": 1290, "text": " Live Demo" }, { "code": null, "e": 1990, "s": 1301, "text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class ProductOfArrayOfElements {\n public static void main(String args[]){\n System.out.println(\"Enter the required size of the array :: \");\n Scanner s = new Scanner(System.in);\n int size = s.nextInt();\n int myArray[] = new int [size];\n int product = 1;\n System.out.println(\"Enter the elements of the array one by one \");\n for(int i=0; i<size; i++){\n myArray[i] = s.nextInt();\n product = product * myArray[i];\n }\n System.out.println(\"Elements of the array are: \"+Arrays.toString(myArray));\n System.out.println(\"Sum of the elements of the array ::\"+product);\n }\n}" }, { "code": null, "e": 2178, "s": 1990, "text": "Enter the required size of the array:\n5\nEnter the elements of the array one by one\n11\n65\n22\n18\n47\nElements of the array are: [11, 65, 22, 18, 47]\nSum of the elements of the array:13307580" } ]
How to create EditText with rounded corners in Android?
This example demonstrates how to create EditText with rounded corners 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: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" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/et_style" android:hint="Your name" android:padding="10dp" /> </LinearLayout> Step 3 − Create a drawable resource file and Add the following code to drawable/et_style.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:width="2dp" android:color="#0274be" /> <corners android:radius="8dp"/> </shape> Step 4 − Add the following code to src/MainActivity.java package com.example.sample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 5 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.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": 1144, "s": 1062, "text": "This example demonstrates how to create EditText with rounded corners in Android." }, { "code": null, "e": 1273, "s": 1144, "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": 1338, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1984, "s": 1338, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout 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 android:orientation=\"vertical\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:background=\"@drawable/et_style\"\n android:hint=\"Your name\"\n android:padding=\"10dp\" />\n</LinearLayout>" }, { "code": null, "e": 2077, "s": 1984, "text": "Step 3 − Create a drawable resource file and Add the following code to drawable/et_style.xml" }, { "code": null, "e": 2323, "s": 2077, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\">\n <stroke\n android:width=\"2dp\"\n android:color=\"#0274be\" />\n <corners android:radius=\"8dp\"/>\n</shape>" }, { "code": null, "e": 2382, "s": 2323, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2735, "s": 2382, "text": "package com.example.sample;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.EditText;\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}" }, { "code": null, "e": 2800, "s": 2735, "text": "Step 5 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 3474, "s": 2800, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.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": 3822, "s": 3474, "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": 3862, "s": 3822, "text": "Click here to download the project code" } ]
Naïve Bayes Spam Filter — From Scratch | by Mark Garvey | Towards Data Science
Probability is all around us. It's in the weather updates we receive daily, to sports team strategies we see on TV, to insurance premiums we purchase. It is also heavily prevalent in the field of Machine Learning, as one of the mathematical driving forces powering modern algorithms. It also powers earlier algorithms, such as the Naïve Bayes Classifier. This was a unique approach to applying Bayes' Theorem to real world problems when the classifier was first devised in the 1990s, and is best known for it's application as an early method of spam filtering - the topic of this article. Bayes' theorem was invented by Thomas Bayes in 1763, when he published a work titled An Essay towards solving a Problem in the Doctrine of Chances (1763). In this essay, Bayes describes how conditional probability can be used to estimate the likelihood of certain events occurring, given certain external events have also occurred. The formula for the theorem is as follows: Where: Pr(A) = the probability of event A occurring, Pr(B) = the probability of event B occurring, Pr(A|B) = Conditional Probability - the probability of event A occurring, given event B also occurs, Pr(B|A) = Conditional Probability - the probability of event B occurring, given event A also occurs. This formula can alternatively be expanded out into: This alternative equation also computes Pr(A|B), but is more useful in the context of spam filtering than the original simpler equation. We will look more in-depth at how this is done below. The concept of spam filtering is simple - detect spam emails from authentic (non-spam/ham) emails. To do this, the goal would be to get a measure of how 'spammy' an incoming email is. The extended form of Bayes' Rule comes into play here. With Bayes' Rule, we want to find the probability an email is spam, given it contains certain words. We do this by finding the probability that each word in the email is spam, and then multiply these probabilities together to get the overall email spam metric to be used in classification. The the probability of an email being spam S given a certain word W appears is defined by the left hand side of the above equation Pr(S|W). The right hand side gives the formula to compute this probability. This is: the probability the word occurs in the email given it is a spam email Pr(W|S) multiplied by the probability of an email being spam Pr(S), divided the probability the word occurs in the email given it is a spam email multiplied by the probability of an email being spam, plus the probability the word occurs in the email given it is a non-spam email Pr(W|¬S) multiplied by the probability of an email being non-spam Pr(¬S). Probabilities can range between 0 and 1. For this spam filter, we will define that any email with a total 'spaminess' metric of over 0.5 (50%) will be deemed a spam email. When the Pr(S|W) has been found for each word in the email, they are multiplied together to give the overall probability that the email is spam. If this probability is over the 'spam threshold' of 0.5, the email is classified as a spam email. ML libraries such as scikit-learn are brilliant for testing out-of-the box algorithms on your data. However it can be beneficial to explore the inner workings of an algorithm in order to better understand and appreciate it by writing it from scratch. Here we will write an implementation of Naïve Bayes Classifier for Spam Filtering in pure python, without the aid of external libraries. We'll also see where the classifier gets the "Naïve" part of its moniker from. Define some training and test data for each class, spam and ham. These emails will be short for brevity and clarity. train_spam = ['send us your password', 'review our website', 'send your password', 'send us your account']train_ham = ['Your activity report','benefits physical activity', 'the importance vows']test_emails = {'spam':['renew your password', 'renew your vows'], 'ham':['benefits of our account', 'the importance of physical activity']} # make a vocabulary of unique words that occur in known spam emails​vocab_words_spam = []​for sentence in train_spam: sentence_as_list = sentence.split() for word in sentence_as_list: vocab_words_spam.append(word) print(vocab_words_spam)['send', 'us', 'your', 'password', 'review', 'our', 'website', 'send', 'your', 'password', 'send', 'us', 'your', 'account'] vocab_unique_words_spam = list(dict.fromkeys(vocab_words_spam))print(vocab_unique_words_spam)['send', 'us', 'your', 'password', 'review', 'our', 'website', 'account'] How do you determine how 'spammy' a word is? According to this overview on Naïve Bayes spam filtering, 'Spamicity' can be calculated by taking the total number of emails that have already been hand-labelled as either spam or ham, and using that data to compute word spam probabilities, by counting the frequency of each word. This uses the same type of conditional probability found in Bayes' Rule. We can count how many spam emails have the word “send” and divide that by the total number of spam emails - this gives a measure of the word's 'spamicity', or how likely it is to be in a spam email. The same approach can be applied for evaluating how 'hamicity' or authenticity of a word. Smoothing should be applied to avoid the scenario that a word would appear zero times in the spam training examples, but would appear in the ham training example, or vice-versa. We want to avoid this scenario, as this would lead to a 0 as the numerator when performing the spamicity calculation: zero divided by anything is zero. A spam-bot could send us an email with this word, and the final email spam calculation would be returned as 0, when we multiplied all the other word spam probabilities together - any other numbers multiplied by zero will be zero. This fraudulent email now having 0% spamicity would be classified as ham, and pass quietly into our inbox. The solution is to add 1 to every word count, so there will never be a zero word count. Add 2 to the denominator to account for this increase to the numerator. We add 2 here in order to account for the number of classes we have - a spam class and a ham class. This would keep the total probability at 1.0 if you were to add up all the individual word probabilities together. In this example, the word "send" has a spamicity of 75% (66% with smoothing applied.) This is over the defined spam threshold of 0.5, meaning it has a high probability of being 'spammy' word. dict_spamicity = {}for w in vocab_unique_words_spam: emails_with_w = 0 # counter for sentence in train_spam: if w in sentence: emails_with_w+=1 print(f"Number of spam emails with the word {w}: {emails_with_w}") total_spam = len(train_spam) spamicity = (emails_with_w+1)/(total_spam+2) print(f"Spamicity of the word '{w}': {spamicity} \n") dict_spamicity[w.lower()] = spamicityNumber of spam emails with the word send: 3Spamicity of the word 'send': 0.6666666666666666 ​Number of spam emails with the word us: 2Spamicity of the word 'us': 0.5 ​Number of spam emails with the word your: 3Spamicity of the word 'your': 0.6666666666666666 ​Number of spam emails with the word password: 2Spamicity of the word 'password': 0.5 ​Number of spam emails with the word review: 1Spamicity of the word 'review': 0.3333333333333333 ​Number of spam emails with the word our: 4Spamicity of the word 'our': 0.8333333333333334 ​Number of spam emails with the word website: 1Spamicity of the word 'website': 0.3333333333333333 ​Number of spam emails with the word account: 1Spamicity of the word 'account': 0.3333333333333333 ​print(dict_spamicity){'send': 0.6666666666666666, 'us': 0.5, 'your': 0.6666666666666666, 'password': 0.5, 'review': 0.3333333333333333, 'our': 0.8333333333333334, 'website': 0.3333333333333333, 'account': 0.3333333333333333} # make a vocabulary of unique words that occur in known ham emails​vocab_words_ham = []​for sentence in train_ham: sentence_as_list = sentence.split() for word in sentence_as_list: vocab_words_ham.append(word) vocab_unique_words_ham = list(dict.fromkeys(vocab_words_ham))print(vocab_unique_words_ham)['Your', 'activity', 'report', 'benefits', 'physical', 'the', 'importance', 'vows']dict_hamicity = {}for w in vocab_unique_words_ham: emails_with_w = 0 # counter for sentence in train_ham: if w in sentence: print(w+":", sentence) emails_with_w+=1 print(f"Number of ham emails with the word '{w}': {emails_with_w}") total_ham = len(train_ham) Hamicity = (emails_with_w+1)/(total_ham+2) # Smoothing applied print(f"Hamicity of the word '{w}': {Hamicity} ") dict_hamicity[w.lower()] = Hamicity # Use built-in lower() to keep all words lower case - useful later when # comparing spamicity vs hamicity of a single word - e.g. 'Your' and # 'your' will be treated as 2 different words if not normalized to lower # case.Your: Your activity reportNumber of ham emails with the word 'Your': 1Hamicity of the word 'Your': 0.4 activity: Your activity reportactivity: benefits physical activityNumber of ham emails with the word 'activity': 2Hamicity of the word 'activity': 0.6 report: Your activity reportNumber of ham emails with the word 'report': 1Hamicity of the word 'report': 0.4 benefits: benefits physical activityNumber of ham emails with the word 'benefits': 1Hamicity of the word 'benefits': 0.4 physical: benefits physical activityNumber of ham emails with the word 'physical': 1Hamicity of the word 'physical': 0.4 the: the importance vowsNumber of ham emails with the word 'the': 1Hamicity of the word 'the': 0.4 importance: the importance vowsNumber of ham emails with the word 'importance': 1Hamicity of the word 'importance': 0.4 vows: the importance vowsNumber of ham emails with the word 'vows': 1Hamicity of the word 'vows': 0.4print(dict_hamicity){'your': 0.4, 'activity': 0.6, 'report': 0.4, 'benefits': 0.4, 'physical': 0.4, 'the': 0.4, 'importance': 0.4, 'vows': 0.4} This computes the probability of any one email being spam, by dividing the total number of spam emails by the total number of all emails. prob_spam = len(train_spam) / (len(train_spam)+(len(train_ham)))print(prob_spam)0.5714285714285714 This computes the probability of any one email being ham, by dividing the total number of ham emails by the total number of all emails. prob_ham = len(train_ham) / (len(train_spam)+(len(train_ham)))print(prob_ham)0.42857142857142855 tests = []for i in test_emails['spam']: tests.append(i) for i in test_emails['ham']: tests.append(i) print(tests) ​['renew your password', 'renew your vows', 'benefits of our account', 'the importance of physical activity']# split emails into distinct words​distinct_words_as_sentences_test = []​for sentence in tests: sentence_as_list = sentence.split() senten = [] for word in sentence_as_list: senten.append(word) distinct_words_as_sentences_test.append(senten) print(distinct_words_as_sentences_test)[['renew', 'your', 'password'], ['renew', 'your', 'vows'], ['benefits', 'of', 'our', 'account'], ['the', 'importance', 'of', 'physical', 'activity']]test_spam_tokenized = [distinct_words_as_sentences_test[0], distinct_words_as_sentences_test[1]]test_ham_tokenized = [distinct_words_as_sentences_test[2], distinct_words_as_sentences_test[3]]print(test_spam_tokenized)[['renew', 'your', 'password'], ['renew', 'your', 'vows']] The reason you would ignore totally unseen words is that you have nothing to really base their level of spamicity or hamicity off. Simply dropping them therefore will not affect the overall probability one way or another, and will not have a significant impact on the class the algorithm selects. It makes more sense to drop unseen words than to add a 1-count with smoothing therefore. reduced_sentences_spam_test = []for sentence in test_spam_tokenized: words_ = [] for word in sentence: if word in vocab_unique_words_spam: print(f"'{word}', ok") words_.append(word) elif word in vocab_unique_words_ham: print(f"'{word}', ok") words_.append(word) else: print(f"'{word}', word not present in labelled spam training data") reduced_sentences_spam_test.append(words_)print(reduced_sentences_spam_test)'renew', word not present in labelled spam training data'your', ok'password', ok'renew', word not present in labelled spam training data'your', ok'vows', ok[['your', 'password'], ['your', 'vows']]reduced_sentences_ham_test = [] # repeat for ham wordsfor sentence in test_ham_tokenized: words_ = [] for word in sentence: if word in vocab_unique_words_ham: print(f"'{word}', ok") words_.append(word) elif word in vocab_unique_words_spam: print(f"'{word}', ok") words_.append(word) else: print(f"'{word}', word not present in labelled ham training data") reduced_sentences_ham_test.append(words_)print(reduced_sentences_ham_test)'benefits', ok'of', word not present in labelled ham training data'our', ok'account', ok'the', ok'importance', ok'of', word not present in labelled ham training data'physical', ok'activity', ok[['benefits', 'our', 'account'], ['the', 'importance', 'physical', 'activity']] Removal of non-key words can help the classifier focus on what words are most important. Deciding what words to remove in this specific case can involve some trial and error, as including or excluding words from a small toy dataset like this will influence the overall classification result. test_spam_stemmed = []non_key = ['us', 'the', 'of','your'] # non-key words, gathered from spam,ham and test sentencesfor email in reduced_sentences_spam_test: email_stemmed=[] for word in email: if word in non_key: print('remove') else: email_stemmed.append(word) test_spam_stemmed.append(email_stemmed) print(test_spam_stemmed)​removeremove[['password'], ['vows']]test_ham_stemmed = []non_key = ['us', 'the', 'of', 'your'] for email in reduced_sentences_ham_test: email_stemmed=[] for word in email: if word in non_key: print('remove') else: email_stemmed.append(word) test_ham_stemmed.append(email_stemmed) print(test_ham_stemmed)​remove[['benefits', 'our', 'account'], ['importance', 'physical', 'activity']] We now use the formula for Bayes' Rule to compute the probability of spam given a certain word from an email. We have already calculated all the necessary probabilities and conditional probabilities needed for the right-hand side of the equation. Computing the overall probability for the entire email is then obtained by multiplying of all these individual word probabilities together. This approach speaks to the reason this Bayes' classifier is 'Naïve' - it does not take into account the relationship of any one word to the next. It assumes there is no order to the words appearing in a sentence, and that they are all independent of each other, as if language was a random pass though a dictionary. This of course is not the case, which is why this early form of spam filtering has been overtaken by more advanced forms of NLP, such as using word embeddings. def mult(list_) : # function to multiply all word probs together total_prob = 1 for i in list_: total_prob = total_prob * i return total_prob​def Bayes(email): probs = [] for word in email: Pr_S = prob_spam print('prob of spam in general ',Pr_S) try: pr_WS = dict_spamicity[word] print(f'prob "{word}" is a spam word : {pr_WS}') except KeyError: pr_WS = 1/(total_spam+2) # Apply smoothing for word not seen in spam training data, but seen in ham training print(f"prob '{word}' is a spam word: {pr_WS}") Pr_H = prob_ham print('prob of ham in general ', Pr_H) try: pr_WH = dict_hamicity[word] print(f'prob "{word}" is a ham word: ',pr_WH) except KeyError: pr_WH = (1/(total_ham+2)) # Apply smoothing for word not seen in ham training data, but seen in spam training print(f"WH for {word} is {pr_WH}") print(f"prob '{word}' is a ham word: {pr_WH}") prob_word_is_spam_BAYES = (pr_WS*Pr_S)/((pr_WS*Pr_S)+(pr_WH*Pr_H)) print('') print(f"Using Bayes, prob the the word '{word}' is spam: {prob_word_is_spam_BAYES}") print('###########################') probs.append(prob_word_is_spam_BAYES) print(f"All word probabilities for this sentence: {probs}") final_classification = mult(probs) if final_classification >= 0.5: print(f'email is SPAM: with spammy confidence of {final_classification*100}%') else: print(f'email is HAM: with spammy confidence of {final_classification*100}%') return final_classificationfor email in test_spam_stemmed: print('') print(f" Testing stemmed SPAM email {email} :") print(' Test word by word: ') all_word_probs = Bayes(email) print(all_word_probs)​ Testing stemmed SPAM email ['password'] : Test word by word: prob of spam in general 0.5714285714285714prob "password" is a spam word : 0.5prob of ham in general 0.42857142857142855WH for password is 0.2prob 'password' is a ham word: 0.2​Using Bayes, prob the the word 'password' is spam: 0.7692307692307692###########################All word probabilities for this sentence: [0.7692307692307692]email is SPAM: with spammy confidence of 76.92307692307692%0.7692307692307692​ Testing stemmed SPAM email ['vows'] : Test word by word: prob of spam in general 0.5714285714285714prob 'vows' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob "vows" is a ham word: 0.4​Using Bayes, prob the the word 'vows' is spam: 0.35714285714285715###########################All word probabilities for this sentence: [0.35714285714285715]email is HAM: with spammy confidence of 35.714285714285715%0.35714285714285715 Result: 1 out of 2 SPAM emails correctly classified. This should be closer to zero than to 0.5, as this is an example of finding the probability of SPAM for emails that contain only words not previously seen in HAM training data, (as the stemmed HAM words have all never had their 'spamicity' calculated for the spamicity dictionary, therefore stemming will add a count of just 1 to these words, giving them a low probability and low spamicity.) for email in test_ham_stemmed: print('') print(f" Testing stemmed HAM email {email} :") print(' Test word by word: ') all_word_probs = Bayes(email) print(all_word_probs)Testing stemmed HAM email ['benefits', 'our', 'account'] : Test word by word: prob of spam in general 0.5714285714285714prob 'benefits' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob "benefits" is a ham word: 0.4​Using Bayes, prob the the word 'benefits' is spam: 0.35714285714285715###########################prob of spam in general 0.5714285714285714prob "our" is a spam word : 0.8333333333333334prob of ham in general 0.42857142857142855WH for our is 0.2prob 'our' is a ham word: 0.2​Using Bayes, prob the the word 'our' is spam: 0.847457627118644###########################prob of spam in general 0.5714285714285714prob "account" is a spam word : 0.3333333333333333prob of ham in general 0.42857142857142855WH for account is 0.2prob 'account' is a ham word: 0.2​Using Bayes, prob the the word 'account' is spam: 0.689655172413793###########################All word probabilities for this sentence: [0.35714285714285715, 0.847457627118644, 0.689655172413793]email is HAM: with spammy confidence of 20.873340569424727%0.20873340569424728​ Testing stemmed HAM email ['importance', 'physical', 'activity'] : Test word by word: prob of spam in general 0.5714285714285714prob 'importance' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob "importance" is a ham word: 0.4​Using Bayes, prob the the word 'importance' is spam: 0.35714285714285715###########################prob of spam in general 0.5714285714285714prob 'physical' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob "physical" is a ham word: 0.4​Using Bayes, prob the the word 'physical' is spam: 0.35714285714285715###########################prob of spam in general 0.5714285714285714prob 'activity' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob "activity" is a ham word: 0.6​Using Bayes, prob the the word 'activity' is spam: 0.2702702702702703###########################All word probabilities for this sentence: [0.35714285714285715, 0.35714285714285715, 0.2702702702702703]email is HAM: with spammy confidence of 3.447324875896305%0.03447324875896305 Result: 2 out of 2 HAM emails correctly classified. This implementation of the Naïve Bayes classifier seemed to work well for most cases. It could classify both HAM test emails as HAM, however it could not accurately classify one of the HAM emails - specifically the 'renew your vows' email. This is due to the word 'vows' only occurring in the HAM training set, and had the major influence on he classifier decision, as the word 'renew' was dropped for not featuring in either HAM or SPAM training sets at the beginning, and the 'your' was stemmed. Different methodologies for spam filtering have since evolved, including different versions of Naïve Bayes (for example Multinomial Naïve Bayes, which has a handy scikit-learn implementation.) Naïve Bayes is a useful algorithm in many respects, especially for solving low-data text classification problems. The way in which it can make accurate predictions with limited training data by assuming naïve independence of words is its main advantage, but ironically also a disadvantage when comparing it to more advanced forms of NLP. Other approaches, such as classifiers which use word embeddings, can encode meaning such as context from sentences to obtain more accurate predictions. Still, there is no denying that Naïve Bayes can act as a powerful spam filter. If you liked this story, please consider following me on Medium. You can find more on https://mark-garvey.com/ Find me on LinkedIn: https://www.linkedin.com/in/mark-garvey/
[ { "code": null, "e": 456, "s": 172, "text": "Probability is all around us. It's in the weather updates we receive daily, to sports team strategies we see on TV, to insurance premiums we purchase. It is also heavily prevalent in the field of Machine Learning, as one of the mathematical driving forces powering modern algorithms." }, { "code": null, "e": 762, "s": 456, "text": "It also powers earlier algorithms, such as the Naïve Bayes Classifier. This was a unique approach to applying Bayes' Theorem to real world problems when the classifier was first devised in the 1990s, and is best known for it's application as an early method of spam filtering - the topic of this article." }, { "code": null, "e": 1137, "s": 762, "text": "Bayes' theorem was invented by Thomas Bayes in 1763, when he published a work titled An Essay towards solving a Problem in the Doctrine of Chances (1763). In this essay, Bayes describes how conditional probability can be used to estimate the likelihood of certain events occurring, given certain external events have also occurred. The formula for the theorem is as follows:" }, { "code": null, "e": 1144, "s": 1137, "text": "Where:" }, { "code": null, "e": 1190, "s": 1144, "text": "Pr(A) = the probability of event A occurring," }, { "code": null, "e": 1236, "s": 1190, "text": "Pr(B) = the probability of event B occurring," }, { "code": null, "e": 1337, "s": 1236, "text": "Pr(A|B) = Conditional Probability - the probability of event A occurring, given event B also occurs," }, { "code": null, "e": 1438, "s": 1337, "text": "Pr(B|A) = Conditional Probability - the probability of event B occurring, given event A also occurs." }, { "code": null, "e": 1491, "s": 1438, "text": "This formula can alternatively be expanded out into:" }, { "code": null, "e": 1682, "s": 1491, "text": "This alternative equation also computes Pr(A|B), but is more useful in the context of spam filtering than the original simpler equation. We will look more in-depth at how this is done below." }, { "code": null, "e": 1921, "s": 1682, "text": "The concept of spam filtering is simple - detect spam emails from authentic (non-spam/ham) emails. To do this, the goal would be to get a measure of how 'spammy' an incoming email is. The extended form of Bayes' Rule comes into play here." }, { "code": null, "e": 2211, "s": 1921, "text": "With Bayes' Rule, we want to find the probability an email is spam, given it contains certain words. We do this by finding the probability that each word in the email is spam, and then multiply these probabilities together to get the overall email spam metric to be used in classification." }, { "code": null, "e": 2351, "s": 2211, "text": "The the probability of an email being spam S given a certain word W appears is defined by the left hand side of the above equation Pr(S|W)." }, { "code": null, "e": 2427, "s": 2351, "text": "The right hand side gives the formula to compute this probability. This is:" }, { "code": null, "e": 2565, "s": 2427, "text": "the probability the word occurs in the email given it is a spam email Pr(W|S) multiplied by the probability of an email being spam Pr(S)," }, { "code": null, "e": 2697, "s": 2565, "text": "divided the probability the word occurs in the email given it is a spam email multiplied by the probability of an email being spam," }, { "code": null, "e": 2850, "s": 2697, "text": "plus the probability the word occurs in the email given it is a non-spam email Pr(W|¬S) multiplied by the probability of an email being non-spam Pr(¬S)." }, { "code": null, "e": 3022, "s": 2850, "text": "Probabilities can range between 0 and 1. For this spam filter, we will define that any email with a total 'spaminess' metric of over 0.5 (50%) will be deemed a spam email." }, { "code": null, "e": 3265, "s": 3022, "text": "When the Pr(S|W) has been found for each word in the email, they are multiplied together to give the overall probability that the email is spam. If this probability is over the 'spam threshold' of 0.5, the email is classified as a spam email." }, { "code": null, "e": 3654, "s": 3265, "text": "ML libraries such as scikit-learn are brilliant for testing out-of-the box algorithms on your data. However it can be beneficial to explore the inner workings of an algorithm in order to better understand and appreciate it by writing it from scratch. Here we will write an implementation of Naïve Bayes Classifier for Spam Filtering in pure python, without the aid of external libraries." }, { "code": null, "e": 3734, "s": 3654, "text": "We'll also see where the classifier gets the \"Naïve\" part of its moniker from." }, { "code": null, "e": 3851, "s": 3734, "text": "Define some training and test data for each class, spam and ham. These emails will be short for brevity and clarity." }, { "code": null, "e": 4185, "s": 3851, "text": "train_spam = ['send us your password', 'review our website', 'send your password', 'send us your account']train_ham = ['Your activity report','benefits physical activity', 'the importance vows']test_emails = {'spam':['renew your password', 'renew your vows'], 'ham':['benefits of our account', 'the importance of physical activity']}" }, { "code": null, "e": 4571, "s": 4185, "text": "# make a vocabulary of unique words that occur in known spam emails​vocab_words_spam = []​for sentence in train_spam: sentence_as_list = sentence.split() for word in sentence_as_list: vocab_words_spam.append(word) print(vocab_words_spam)['send', 'us', 'your', 'password', 'review', 'our', 'website', 'send', 'your', 'password', 'send', 'us', 'your', 'account']" }, { "code": null, "e": 4738, "s": 4571, "text": "vocab_unique_words_spam = list(dict.fromkeys(vocab_words_spam))print(vocab_unique_words_spam)['send', 'us', 'your', 'password', 'review', 'our', 'website', 'account']" }, { "code": null, "e": 4783, "s": 4738, "text": "How do you determine how 'spammy' a word is?" }, { "code": null, "e": 5065, "s": 4783, "text": "According to this overview on Naïve Bayes spam filtering, 'Spamicity' can be calculated by taking the total number of emails that have already been hand-labelled as either spam or ham, and using that data to compute word spam probabilities, by counting the frequency of each word." }, { "code": null, "e": 5337, "s": 5065, "text": "This uses the same type of conditional probability found in Bayes' Rule. We can count how many spam emails have the word “send” and divide that by the total number of spam emails - this gives a measure of the word's 'spamicity', or how likely it is to be in a spam email." }, { "code": null, "e": 5427, "s": 5337, "text": "The same approach can be applied for evaluating how 'hamicity' or authenticity of a word." }, { "code": null, "e": 5605, "s": 5427, "text": "Smoothing should be applied to avoid the scenario that a word would appear zero times in the spam training examples, but would appear in the ham training example, or vice-versa." }, { "code": null, "e": 6094, "s": 5605, "text": "We want to avoid this scenario, as this would lead to a 0 as the numerator when performing the spamicity calculation: zero divided by anything is zero. A spam-bot could send us an email with this word, and the final email spam calculation would be returned as 0, when we multiplied all the other word spam probabilities together - any other numbers multiplied by zero will be zero. This fraudulent email now having 0% spamicity would be classified as ham, and pass quietly into our inbox." }, { "code": null, "e": 6469, "s": 6094, "text": "The solution is to add 1 to every word count, so there will never be a zero word count. Add 2 to the denominator to account for this increase to the numerator. We add 2 here in order to account for the number of classes we have - a spam class and a ham class. This would keep the total probability at 1.0 if you were to add up all the individual word probabilities together." }, { "code": null, "e": 6661, "s": 6469, "text": "In this example, the word \"send\" has a spamicity of 75% (66% with smoothing applied.) This is over the defined spam threshold of 0.5, meaning it has a high probability of being 'spammy' word." }, { "code": null, "e": 8049, "s": 6661, "text": "dict_spamicity = {}for w in vocab_unique_words_spam: emails_with_w = 0 # counter for sentence in train_spam: if w in sentence: emails_with_w+=1 print(f\"Number of spam emails with the word {w}: {emails_with_w}\") total_spam = len(train_spam) spamicity = (emails_with_w+1)/(total_spam+2) print(f\"Spamicity of the word '{w}': {spamicity} \\n\") dict_spamicity[w.lower()] = spamicityNumber of spam emails with the word send: 3Spamicity of the word 'send': 0.6666666666666666 ​Number of spam emails with the word us: 2Spamicity of the word 'us': 0.5 ​Number of spam emails with the word your: 3Spamicity of the word 'your': 0.6666666666666666 ​Number of spam emails with the word password: 2Spamicity of the word 'password': 0.5 ​Number of spam emails with the word review: 1Spamicity of the word 'review': 0.3333333333333333 ​Number of spam emails with the word our: 4Spamicity of the word 'our': 0.8333333333333334 ​Number of spam emails with the word website: 1Spamicity of the word 'website': 0.3333333333333333 ​Number of spam emails with the word account: 1Spamicity of the word 'account': 0.3333333333333333 ​print(dict_spamicity){'send': 0.6666666666666666, 'us': 0.5, 'your': 0.6666666666666666, 'password': 0.5, 'review': 0.3333333333333333, 'our': 0.8333333333333334, 'website': 0.3333333333333333, 'account': 0.3333333333333333}" }, { "code": null, "e": 10384, "s": 8049, "text": "# make a vocabulary of unique words that occur in known ham emails​vocab_words_ham = []​for sentence in train_ham: sentence_as_list = sentence.split() for word in sentence_as_list: vocab_words_ham.append(word) vocab_unique_words_ham = list(dict.fromkeys(vocab_words_ham))print(vocab_unique_words_ham)['Your', 'activity', 'report', 'benefits', 'physical', 'the', 'importance', 'vows']dict_hamicity = {}for w in vocab_unique_words_ham: emails_with_w = 0 # counter for sentence in train_ham: if w in sentence: print(w+\":\", sentence) emails_with_w+=1 print(f\"Number of ham emails with the word '{w}': {emails_with_w}\") total_ham = len(train_ham) Hamicity = (emails_with_w+1)/(total_ham+2) # Smoothing applied print(f\"Hamicity of the word '{w}': {Hamicity} \") dict_hamicity[w.lower()] = Hamicity # Use built-in lower() to keep all words lower case - useful later when # comparing spamicity vs hamicity of a single word - e.g. 'Your' and # 'your' will be treated as 2 different words if not normalized to lower # case.Your: Your activity reportNumber of ham emails with the word 'Your': 1Hamicity of the word 'Your': 0.4 activity: Your activity reportactivity: benefits physical activityNumber of ham emails with the word 'activity': 2Hamicity of the word 'activity': 0.6 report: Your activity reportNumber of ham emails with the word 'report': 1Hamicity of the word 'report': 0.4 benefits: benefits physical activityNumber of ham emails with the word 'benefits': 1Hamicity of the word 'benefits': 0.4 physical: benefits physical activityNumber of ham emails with the word 'physical': 1Hamicity of the word 'physical': 0.4 the: the importance vowsNumber of ham emails with the word 'the': 1Hamicity of the word 'the': 0.4 importance: the importance vowsNumber of ham emails with the word 'importance': 1Hamicity of the word 'importance': 0.4 vows: the importance vowsNumber of ham emails with the word 'vows': 1Hamicity of the word 'vows': 0.4print(dict_hamicity){'your': 0.4, 'activity': 0.6, 'report': 0.4, 'benefits': 0.4, 'physical': 0.4, 'the': 0.4, 'importance': 0.4, 'vows': 0.4}" }, { "code": null, "e": 10522, "s": 10384, "text": "This computes the probability of any one email being spam, by dividing the total number of spam emails by the total number of all emails." }, { "code": null, "e": 10621, "s": 10522, "text": "prob_spam = len(train_spam) / (len(train_spam)+(len(train_ham)))print(prob_spam)0.5714285714285714" }, { "code": null, "e": 10757, "s": 10621, "text": "This computes the probability of any one email being ham, by dividing the total number of ham emails by the total number of all emails." }, { "code": null, "e": 10854, "s": 10757, "text": "prob_ham = len(train_ham) / (len(train_spam)+(len(train_ham)))print(prob_ham)0.42857142857142855" }, { "code": null, "e": 11824, "s": 10854, "text": "tests = []for i in test_emails['spam']: tests.append(i) for i in test_emails['ham']: tests.append(i) print(tests) ​['renew your password', 'renew your vows', 'benefits of our account', 'the importance of physical activity']# split emails into distinct words​distinct_words_as_sentences_test = []​for sentence in tests: sentence_as_list = sentence.split() senten = [] for word in sentence_as_list: senten.append(word) distinct_words_as_sentences_test.append(senten) print(distinct_words_as_sentences_test)[['renew', 'your', 'password'], ['renew', 'your', 'vows'], ['benefits', 'of', 'our', 'account'], ['the', 'importance', 'of', 'physical', 'activity']]test_spam_tokenized = [distinct_words_as_sentences_test[0], distinct_words_as_sentences_test[1]]test_ham_tokenized = [distinct_words_as_sentences_test[2], distinct_words_as_sentences_test[3]]print(test_spam_tokenized)[['renew', 'your', 'password'], ['renew', 'your', 'vows']]" }, { "code": null, "e": 12210, "s": 11824, "text": "The reason you would ignore totally unseen words is that you have nothing to really base their level of spamicity or hamicity off. Simply dropping them therefore will not affect the overall probability one way or another, and will not have a significant impact on the class the algorithm selects. It makes more sense to drop unseen words than to add a 1-count with smoothing therefore." }, { "code": null, "e": 13709, "s": 12210, "text": "reduced_sentences_spam_test = []for sentence in test_spam_tokenized: words_ = [] for word in sentence: if word in vocab_unique_words_spam: print(f\"'{word}', ok\") words_.append(word) elif word in vocab_unique_words_ham: print(f\"'{word}', ok\") words_.append(word) else: print(f\"'{word}', word not present in labelled spam training data\") reduced_sentences_spam_test.append(words_)print(reduced_sentences_spam_test)'renew', word not present in labelled spam training data'your', ok'password', ok'renew', word not present in labelled spam training data'your', ok'vows', ok[['your', 'password'], ['your', 'vows']]reduced_sentences_ham_test = [] # repeat for ham wordsfor sentence in test_ham_tokenized: words_ = [] for word in sentence: if word in vocab_unique_words_ham: print(f\"'{word}', ok\") words_.append(word) elif word in vocab_unique_words_spam: print(f\"'{word}', ok\") words_.append(word) else: print(f\"'{word}', word not present in labelled ham training data\") reduced_sentences_ham_test.append(words_)print(reduced_sentences_ham_test)'benefits', ok'of', word not present in labelled ham training data'our', ok'account', ok'the', ok'importance', ok'of', word not present in labelled ham training data'physical', ok'activity', ok[['benefits', 'our', 'account'], ['the', 'importance', 'physical', 'activity']]" }, { "code": null, "e": 14001, "s": 13709, "text": "Removal of non-key words can help the classifier focus on what words are most important. Deciding what words to remove in this specific case can involve some trial and error, as including or excluding words from a small toy dataset like this will influence the overall classification result." }, { "code": null, "e": 14833, "s": 14001, "text": "test_spam_stemmed = []non_key = ['us', 'the', 'of','your'] # non-key words, gathered from spam,ham and test sentencesfor email in reduced_sentences_spam_test: email_stemmed=[] for word in email: if word in non_key: print('remove') else: email_stemmed.append(word) test_spam_stemmed.append(email_stemmed) print(test_spam_stemmed)​removeremove[['password'], ['vows']]test_ham_stemmed = []non_key = ['us', 'the', 'of', 'your'] for email in reduced_sentences_ham_test: email_stemmed=[] for word in email: if word in non_key: print('remove') else: email_stemmed.append(word) test_ham_stemmed.append(email_stemmed) print(test_ham_stemmed)​remove[['benefits', 'our', 'account'], ['importance', 'physical', 'activity']]" }, { "code": null, "e": 15080, "s": 14833, "text": "We now use the formula for Bayes' Rule to compute the probability of spam given a certain word from an email. We have already calculated all the necessary probabilities and conditional probabilities needed for the right-hand side of the equation." }, { "code": null, "e": 15220, "s": 15080, "text": "Computing the overall probability for the entire email is then obtained by multiplying of all these individual word probabilities together." }, { "code": null, "e": 15698, "s": 15220, "text": "This approach speaks to the reason this Bayes' classifier is 'Naïve' - it does not take into account the relationship of any one word to the next. It assumes there is no order to the words appearing in a sentence, and that they are all independent of each other, as if language was a random pass though a dictionary. This of course is not the case, which is why this early form of spam filtering has been overtaken by more advanced forms of NLP, such as using word embeddings." }, { "code": null, "e": 18576, "s": 15698, "text": "def mult(list_) : # function to multiply all word probs together total_prob = 1 for i in list_: total_prob = total_prob * i return total_prob​def Bayes(email): probs = [] for word in email: Pr_S = prob_spam print('prob of spam in general ',Pr_S) try: pr_WS = dict_spamicity[word] print(f'prob \"{word}\" is a spam word : {pr_WS}') except KeyError: pr_WS = 1/(total_spam+2) # Apply smoothing for word not seen in spam training data, but seen in ham training print(f\"prob '{word}' is a spam word: {pr_WS}\") Pr_H = prob_ham print('prob of ham in general ', Pr_H) try: pr_WH = dict_hamicity[word] print(f'prob \"{word}\" is a ham word: ',pr_WH) except KeyError: pr_WH = (1/(total_ham+2)) # Apply smoothing for word not seen in ham training data, but seen in spam training print(f\"WH for {word} is {pr_WH}\") print(f\"prob '{word}' is a ham word: {pr_WH}\") prob_word_is_spam_BAYES = (pr_WS*Pr_S)/((pr_WS*Pr_S)+(pr_WH*Pr_H)) print('') print(f\"Using Bayes, prob the the word '{word}' is spam: {prob_word_is_spam_BAYES}\") print('###########################') probs.append(prob_word_is_spam_BAYES) print(f\"All word probabilities for this sentence: {probs}\") final_classification = mult(probs) if final_classification >= 0.5: print(f'email is SPAM: with spammy confidence of {final_classification*100}%') else: print(f'email is HAM: with spammy confidence of {final_classification*100}%') return final_classificationfor email in test_spam_stemmed: print('') print(f\" Testing stemmed SPAM email {email} :\") print(' Test word by word: ') all_word_probs = Bayes(email) print(all_word_probs)​ Testing stemmed SPAM email ['password'] : Test word by word: prob of spam in general 0.5714285714285714prob \"password\" is a spam word : 0.5prob of ham in general 0.42857142857142855WH for password is 0.2prob 'password' is a ham word: 0.2​Using Bayes, prob the the word 'password' is spam: 0.7692307692307692###########################All word probabilities for this sentence: [0.7692307692307692]email is SPAM: with spammy confidence of 76.92307692307692%0.7692307692307692​ Testing stemmed SPAM email ['vows'] : Test word by word: prob of spam in general 0.5714285714285714prob 'vows' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob \"vows\" is a ham word: 0.4​Using Bayes, prob the the word 'vows' is spam: 0.35714285714285715###########################All word probabilities for this sentence: [0.35714285714285715]email is HAM: with spammy confidence of 35.714285714285715%0.35714285714285715" }, { "code": null, "e": 18629, "s": 18576, "text": "Result: 1 out of 2 SPAM emails correctly classified." }, { "code": null, "e": 18806, "s": 18629, "text": "This should be closer to zero than to 0.5, as this is an example of finding the probability of SPAM for emails that contain only words not previously seen in HAM training data," }, { "code": null, "e": 19022, "s": 18806, "text": "(as the stemmed HAM words have all never had their 'spamicity' calculated for the spamicity dictionary, therefore stemming will add a count of just 1 to these words, giving them a low probability and low spamicity.)" }, { "code": null, "e": 21442, "s": 19022, "text": "for email in test_ham_stemmed: print('') print(f\" Testing stemmed HAM email {email} :\") print(' Test word by word: ') all_word_probs = Bayes(email) print(all_word_probs)Testing stemmed HAM email ['benefits', 'our', 'account'] : Test word by word: prob of spam in general 0.5714285714285714prob 'benefits' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob \"benefits\" is a ham word: 0.4​Using Bayes, prob the the word 'benefits' is spam: 0.35714285714285715###########################prob of spam in general 0.5714285714285714prob \"our\" is a spam word : 0.8333333333333334prob of ham in general 0.42857142857142855WH for our is 0.2prob 'our' is a ham word: 0.2​Using Bayes, prob the the word 'our' is spam: 0.847457627118644###########################prob of spam in general 0.5714285714285714prob \"account\" is a spam word : 0.3333333333333333prob of ham in general 0.42857142857142855WH for account is 0.2prob 'account' is a ham word: 0.2​Using Bayes, prob the the word 'account' is spam: 0.689655172413793###########################All word probabilities for this sentence: [0.35714285714285715, 0.847457627118644, 0.689655172413793]email is HAM: with spammy confidence of 20.873340569424727%0.20873340569424728​ Testing stemmed HAM email ['importance', 'physical', 'activity'] : Test word by word: prob of spam in general 0.5714285714285714prob 'importance' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob \"importance\" is a ham word: 0.4​Using Bayes, prob the the word 'importance' is spam: 0.35714285714285715###########################prob of spam in general 0.5714285714285714prob 'physical' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob \"physical\" is a ham word: 0.4​Using Bayes, prob the the word 'physical' is spam: 0.35714285714285715###########################prob of spam in general 0.5714285714285714prob 'activity' is a spam word: 0.16666666666666666prob of ham in general 0.42857142857142855prob \"activity\" is a ham word: 0.6​Using Bayes, prob the the word 'activity' is spam: 0.2702702702702703###########################All word probabilities for this sentence: [0.35714285714285715, 0.35714285714285715, 0.2702702702702703]email is HAM: with spammy confidence of 3.447324875896305%0.03447324875896305" }, { "code": null, "e": 21494, "s": 21442, "text": "Result: 2 out of 2 HAM emails correctly classified." }, { "code": null, "e": 21993, "s": 21494, "text": "This implementation of the Naïve Bayes classifier seemed to work well for most cases. It could classify both HAM test emails as HAM, however it could not accurately classify one of the HAM emails - specifically the 'renew your vows' email. This is due to the word 'vows' only occurring in the HAM training set, and had the major influence on he classifier decision, as the word 'renew' was dropped for not featuring in either HAM or SPAM training sets at the beginning, and the 'your' was stemmed." }, { "code": null, "e": 22188, "s": 21993, "text": "Different methodologies for spam filtering have since evolved, including different versions of Naïve Bayes (for example Multinomial Naïve Bayes, which has a handy scikit-learn implementation.)" }, { "code": null, "e": 22760, "s": 22188, "text": "Naïve Bayes is a useful algorithm in many respects, especially for solving low-data text classification problems. The way in which it can make accurate predictions with limited training data by assuming naïve independence of words is its main advantage, but ironically also a disadvantage when comparing it to more advanced forms of NLP. Other approaches, such as classifiers which use word embeddings, can encode meaning such as context from sentences to obtain more accurate predictions. Still, there is no denying that Naïve Bayes can act as a powerful spam filter." }, { "code": null, "e": 22871, "s": 22760, "text": "If you liked this story, please consider following me on Medium. You can find more on https://mark-garvey.com/" } ]
JavaScript - Check if value is a percentage?
Let’s say the following is our value − var value="97%"; To check the value for percentage, use regular expression. Following is the code − var value="97%"; var result=/^\d+(\.\d+)?%$/.test(value); if (result==true) { console.log("The percent is="+value); } else { console.log("This is not percentage"); } var value1="percent"; var result1=/^\d+(\.\d+)?%$/.test(value1); if (result1==true) { console.log("The percent is="+value1); } else { console.log("This is not percentage"); } To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo214.js. The output is as follows on console − PS C:\Users\Amit\JavaScript-code> node demo214.js The percent is=97% This is not percentage
[ { "code": null, "e": 1101, "s": 1062, "text": "Let’s say the following is our value −" }, { "code": null, "e": 1118, "s": 1101, "text": "var value=\"97%\";" }, { "code": null, "e": 1177, "s": 1118, "text": "To check the value for percentage, use regular expression." }, { "code": null, "e": 1201, "s": 1177, "text": "Following is the code −" }, { "code": null, "e": 1562, "s": 1201, "text": "var value=\"97%\";\nvar result=/^\\d+(\\.\\d+)?%$/.test(value);\nif (result==true) {\n console.log(\"The percent is=\"+value); \n}\nelse\n{\n console.log(\"This is not percentage\"); \n}\nvar value1=\"percent\";\nvar result1=/^\\d+(\\.\\d+)?%$/.test(value1);\nif (result1==true) {\n console.log(\"The percent is=\"+value1); \n}\nelse\n{\n console.log(\"This is not percentage\"); \n}" }, { "code": null, "e": 1628, "s": 1562, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1646, "s": 1628, "text": "node fileName.js." }, { "code": null, "e": 1680, "s": 1646, "text": "Here, my file name is demo214.js." }, { "code": null, "e": 1718, "s": 1680, "text": "The output is as follows on console −" }, { "code": null, "e": 1810, "s": 1718, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo214.js\nThe percent is=97%\nThis is not percentage" } ]
How to add a new row to JTable with insertRow() in Java Swing
Let us first create a table with DefaulTabelMode − DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel); Now, add a column to the table − tableModel.addColumn("Languages"); The insertRow() method will now add a row − tableModel.insertRow(0, new Object[] { "CSS" }); tableModel.insertRow(0, new Object[] { "HTML5" }); tableModel.insertRow(0, new Object[] { "JavaScript" }); tableModel.insertRow(0, new Object[] { "jQuery" }); The following is an example to add a new row to JTable − package my; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SwingDemo { public static void main(String[] argv) throws Exception { DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel); tableModel.addColumn("Languages"); tableModel.insertRow(0, new Object[] { "CSS" }); tableModel.insertRow(0, new Object[] { "HTML5" }); tableModel.insertRow(0, new Object[] { "JavaScript" }); tableModel.insertRow(0, new Object[] { "jQuery" }); tableModel.insertRow(0, new Object[] { "AngularJS" }); // adding a new row tableModel.insertRow(tableModel.getRowCount(), new Object[] { "ExpressJS" }); JFrame f = new JFrame(); f.setSize(550, 350); f.add(new JScrollPane(table)); f.setVisible(true); } } This will produce the following output −
[ { "code": null, "e": 1113, "s": 1062, "text": "Let us first create a table with DefaulTabelMode −" }, { "code": null, "e": 1208, "s": 1113, "text": "DefaultTableModel tableModel = new DefaultTableModel();\nJTable table = new JTable(tableModel);" }, { "code": null, "e": 1241, "s": 1208, "text": "Now, add a column to the table −" }, { "code": null, "e": 1276, "s": 1241, "text": "tableModel.addColumn(\"Languages\");" }, { "code": null, "e": 1320, "s": 1276, "text": "The insertRow() method will now add a row −" }, { "code": null, "e": 1528, "s": 1320, "text": "tableModel.insertRow(0, new Object[] { \"CSS\" });\ntableModel.insertRow(0, new Object[] { \"HTML5\" });\ntableModel.insertRow(0, new Object[] { \"JavaScript\" });\ntableModel.insertRow(0, new Object[] { \"jQuery\" });" }, { "code": null, "e": 1585, "s": 1528, "text": "The following is an example to add a new row to JTable −" }, { "code": null, "e": 2492, "s": 1585, "text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.DefaultTableModel;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n DefaultTableModel tableModel = new DefaultTableModel();\n JTable table = new JTable(tableModel);\n tableModel.addColumn(\"Languages\");\n tableModel.insertRow(0, new Object[] { \"CSS\" });\n tableModel.insertRow(0, new Object[] { \"HTML5\" });\n tableModel.insertRow(0, new Object[] { \"JavaScript\" });\n tableModel.insertRow(0, new Object[] { \"jQuery\" });\n tableModel.insertRow(0, new Object[] { \"AngularJS\" });\n // adding a new row\n tableModel.insertRow(tableModel.getRowCount(), new Object[] { \"ExpressJS\" });\n JFrame f = new JFrame();\n f.setSize(550, 350);\n f.add(new JScrollPane(table));\n f.setVisible(true);\n }\n}" }, { "code": null, "e": 2533, "s": 2492, "text": "This will produce the following output −" } ]
What is the use of -Force parameter in Get-ChildItem in PowerShell?
To display files along with hidden files, you need to use –Force parameter. Get-ChildItem D:\Temp\ -Force If you see the above output, hiddenfile.xlsx is the hidden file and same can be identified with the mode where –a-h—attribute of the file. You can also use this parameter with –Recurse or –Depth. Get-ChildItem D:\Temp\ -Recurse -Force
[ { "code": null, "e": 1138, "s": 1062, "text": "To display files along with hidden files, you need to use –Force parameter." }, { "code": null, "e": 1168, "s": 1138, "text": "Get-ChildItem D:\\Temp\\ -Force" }, { "code": null, "e": 1307, "s": 1168, "text": "If you see the above output, hiddenfile.xlsx is the hidden file and same can be identified with the mode where –a-h—attribute of the file." }, { "code": null, "e": 1364, "s": 1307, "text": "You can also use this parameter with –Recurse or –Depth." }, { "code": null, "e": 1404, "s": 1364, "text": "Get-ChildItem D:\\Temp\\ -Recurse -Force\n" } ]
Display array structure and values in PHP 7
An array in PHP is a type of data structure that can store multiple elements of similar data type under a single variable. To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array. print_r: It is used to display the variable information in a human-readable format. Array values will be present in a format so that keys and elements can show. print_r also shows protected and private properties of objects but it will not show the static class and members. Live Demo <?php $x = array ('x' => 'Dept', 'y' => 'Employee', 'z' => array ('a', 'b', 'c')); print_r ($x); ?> Output for the above print_r program will be: Array ( [x] => Dept [y] => Employee [z] => Array ( [0] => a [1] => b [2] => c ) ) var_dump: It is used to display the structure information of one or more variables and expressions including its type and value. Arrays and objects are explored recursively with their values indented to show the structure. Live Demo <?php $x = array(1, 2,3, array("x", "y", "z","a")); var_dump($x); ?> Output for the above var_dump program will be − array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> array(4) { [0]=> string(1) "x" [1]=> string(1) "y" [2]=> string(1) "z" [3]=> string(1) "a" } } Live Demo <?php $students = array("Rohan", "Mohan", "Thomas"); // it will print the students print_r($students); //echo "<hr>"; var_dump($students); ?> The output for the above program will be − Array ( [0] => Rohan [1] => Mohan [2] => Thomas ) array(3) { [0]=> string(5) "Rohan" [1]=> string(5) "Mohan" [2]=> string(6) "Thomas" }
[ { "code": null, "e": 1185, "s": 1062, "text": "An array in PHP is a type of data structure that can store multiple elements of similar data type under a single variable." }, { "code": null, "e": 1400, "s": 1185, "text": "To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array." }, { "code": null, "e": 1675, "s": 1400, "text": "print_r: It is used to display the variable information in a human-readable format. Array values will be present in a format so that keys and elements can show. print_r also shows protected and private properties of objects but it will not show the static class and members." }, { "code": null, "e": 1685, "s": 1675, "text": "Live Demo" }, { "code": null, "e": 1791, "s": 1685, "text": "<?php\n $x = array ('x' => 'Dept', 'y' => 'Employee', 'z' => array ('a', 'b', 'c'));\n print_r ($x);\n?>" }, { "code": null, "e": 1837, "s": 1791, "text": "Output for the above print_r program will be:" }, { "code": null, "e": 1967, "s": 1837, "text": "Array\n(\n [x] => Dept\n [y] => Employee\n [z] => Array\n (\n [0] => a\n [1] => b\n [2] => c\n )\n)" }, { "code": null, "e": 2190, "s": 1967, "text": "var_dump: It is used to display the structure information of one or more variables and expressions including its type and value. Arrays and objects are explored recursively with their values indented to show the structure." }, { "code": null, "e": 2200, "s": 2190, "text": "Live Demo" }, { "code": null, "e": 2275, "s": 2200, "text": "<?php\n $x = array(1, 2,3, array(\"x\", \"y\", \"z\",\"a\"));\n var_dump($x);\n?>" }, { "code": null, "e": 2323, "s": 2275, "text": "Output for the above var_dump program will be −" }, { "code": null, "e": 2549, "s": 2323, "text": "array(4) {\n [0]=>\n int(1)\n [1]=>\n int(2)\n [2]=>\n int(3)\n [3]=>\n array(4) {\n [0]=>\n string(1) \"x\"\n [1]=>\n string(1) \"y\"\n [2]=>\n string(1) \"z\"\n [3]=>\n string(1) \"a\"\n }\n}" }, { "code": null, "e": 2559, "s": 2549, "text": "Live Demo" }, { "code": null, "e": 2713, "s": 2559, "text": "<?php\n $students = array(\"Rohan\", \"Mohan\", \"Thomas\"); // it will print the students\n print_r($students);\n //echo \"<hr>\";\n var_dump($students);\n?>" }, { "code": null, "e": 2756, "s": 2713, "text": "The output for the above program will be −" }, { "code": null, "e": 2919, "s": 2756, "text": "Array\n(\n [0] => Rohan\n [1] => Mohan\n [2] => Thomas\n)\narray(3) {\n [0]=>\n string(5) \"Rohan\"\n [1]=>\n string(5) \"Mohan\"\n [2]=>\n string(6) \"Thomas\"\n}" } ]
Aquatone - Tool for domain flyovers - GeeksforGeeks
27 Jan, 2022 AQUATONE is a set of tools used for performing reconnaissance, scanning, and discovery o domain names. AQUATONE can discover subdomains on a given target domain using OSINT source and the most common domain brute force method. After discovering the subdomain, the AQUATONE tool can scan the domain for standard web ports and HTTP headers information. HTML bodies and snapshots can be collected and considered as the report to analyze the attack environment quickly. To increase the efficiency and simpleness of aquatone tool, it is divided into 3 phases DiscoveryScanningGathering Discovery Scanning Gathering The first stage of an AQUATONE assessment is the discovery stage, where subdomains are discovered on the victim domain using open sources, services, and the more common dictionary brute force approach. aquatone-discover ships with the following collector modules: Dictionary brute forceDNSDB.orgGoogle Transparency ReportHackerTargetNetcraftShodan (requires API key)ThreatCrowdVirusTotal (requires API key) Dictionary brute force DNSDB.org Google Transparency Report HackerTarget Netcraft Shodan (requires API key) ThreatCrowd VirusTotal (requires API key) The scanning stage is where AQUATONE will enumerate the recognized hosts for open TCP ports that are usually used for web services. The last stage is the gathering phase, in which the results of discovery and scanning stages are used to make the discovered web services return and save HTTP response headers packets and HTML bodies, as well as taking the snapshots of how the web page or domain looks like in web browser which makes the analysis much more accessible. Step 1: Download Google Chrome on your Linux System, by using the following command. wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb Step 2: Install Google Chrome, using the following command sudo apt install ./google-chrome-stable_current_amd64.deb Step 3: Download Aquatone Zip from Github Page. https://github.com/michenriksen/aquatone/releases/tag/v1.7.0 Step 4: After Downloading Extract the zip folder. Right Click and Extract Step 5: Go to Terminal and change directory to Downloads cd Downloads cd aquatone_linux_amd64_1.7.0/ Step 6: Move Aquatone in the bin directory. sudo mv aquatone /usr/local/bin/ Step 7: Check the help page of aquatone for a better understanding of usage, use the following command. aquatone --help Example 1: Discovery aquatone-discover --domain geeksforgeeks.org 1. The aquatone does is to identify the information about the target domain (geeksforgeeks.org). 2. 8277 Unique Hosts are Resolved along with the IP addresses and the subdomains. Example 2: Scanning aquatone-scan -d geeksforgeeks.org 1. Using the hosts.json file, which contains the 90 hosts is used for scanning to get the port details. 2. All the Probed Ports are stored in open_ports.txt with IP address and port number opened. 3. All the URLs are stored in urls.txt file. Example 3: Gathering aquatone-gather -d geeksforgeeks.org In this example, we are gathering the information on geeksforgeeks.org (like subdomains, status codes, Ip addresses, etc). Example 4: CLI Tricks Getting more Subdomains of geeksforgeeks.org (filtering the results) cat * | egrep -o '[a-z0-9\-\_\.]+\geeksforgeeks\.org' | sort -u Example 5: Finding HTML Comments Using Filtering skills to get HTML comments from HTML directory data. cat * | egrep -o '<!--.*-->' Example 6: Finding pages with password fields Finding Password fields using Filtering the results (grep). grep 'type="password"' * Example 7 : Specifying ports to scan 1. By default, the Aquatone tool will scan target hosts with a small list of commonly used HTTP ports: 80, 443, 8000, 8080, and 8443. We can change this variety of ports list using the -ports flag. You can check the help section for more details cat hosts.txt | aquatone -ports 80,443,3000,3001 2. Aquatone also supports nicknames of built-in port records to make it more comfortable for you: small: 80, 443 medium: 80, 443, 8000, 8080, 8443 (same as default) large: 80, 81, 443, 591, 2082, 2087, 2095, 2096, 3000, 8000, 8001, 8008, 8080, 8083, 8443, 8834, 8888 xlarge: 80, 81, 300, 443, 591, 593, 832, 981, 1010, 1311, 2082, 2087, 2095, 2096, 2480, 3000, 3128, 3333, 4243, 4567, 4711, 4712, 4993, 5000, 5104, 5108, 5800, 6543, 7000, 7396, 7474, 8000, 8001, 8008, 8014, 8042, 8069, 8080, 8081, 8088, 8090, 8091, 8118, 8123, 8172, 8222, 8243, 8280, 8281, 8333, 8443, 8500, 8834, 8880, 8888, 8983, 9000, 9043, 9060, 9080, 9090, 9091, 9200, 9443, 9800, 9981, 12443, 16080, 18091, 18092, 20720, 28017 cat hosts.txt | aquatone -ports large In the below screenshot, we have used large ports lists for getting the ports enabled on hosts. Example 8: Subdomain Takeover aquatone-takeover --domain geeksforgeeks.org aquatone has the feature to check the domain if it is vulnerable to Subdomain Takeover or not. Example 9: Amass DNS enumeration amass enum -active -brute -o hosts.txt -d geeksforgeeks.org Aquatone has the feature to integrate with the Amass tool for DNS Enumeration. Example 10: Screen Shots 1. Aquatone is popular for its Screenshot taking feature, in the below screenshot aquatone has taken the screenshot of geeksforgeeks.org Example 11: More Information about geeksforgeeks.org You can see we have got more information about geeksforgeeks.org like Server information, Response Header info, etc. AQUATONE is a very useful tool for discovering information of multiple targets at the same time. The Screenshot-taking feature makes it more attractive and special as attackers need to check each subdomain manually, so to avoid this attackers can now run the aquatone on various subdomains at a time and check the subdomain’s status (active/inactive). infoseczak Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ mv command in Linux with examples chown command in Linux with Examples SED command in Linux | Set 2 Docker - COPY Instruction Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting nslookup command in Linux with Examples
[ { "code": null, "e": 24406, "s": 24378, "text": "\n27 Jan, 2022" }, { "code": null, "e": 24872, "s": 24406, "text": "AQUATONE is a set of tools used for performing reconnaissance, scanning, and discovery o domain names. AQUATONE can discover subdomains on a given target domain using OSINT source and the most common domain brute force method. After discovering the subdomain, the AQUATONE tool can scan the domain for standard web ports and HTTP headers information. HTML bodies and snapshots can be collected and considered as the report to analyze the attack environment quickly." }, { "code": null, "e": 24960, "s": 24872, "text": "To increase the efficiency and simpleness of aquatone tool, it is divided into 3 phases" }, { "code": null, "e": 24987, "s": 24960, "text": "DiscoveryScanningGathering" }, { "code": null, "e": 24997, "s": 24987, "text": "Discovery" }, { "code": null, "e": 25006, "s": 24997, "text": "Scanning" }, { "code": null, "e": 25016, "s": 25006, "text": "Gathering" }, { "code": null, "e": 25280, "s": 25016, "text": "The first stage of an AQUATONE assessment is the discovery stage, where subdomains are discovered on the victim domain using open sources, services, and the more common dictionary brute force approach. aquatone-discover ships with the following collector modules:" }, { "code": null, "e": 25423, "s": 25280, "text": "Dictionary brute forceDNSDB.orgGoogle Transparency ReportHackerTargetNetcraftShodan (requires API key)ThreatCrowdVirusTotal (requires API key)" }, { "code": null, "e": 25446, "s": 25423, "text": "Dictionary brute force" }, { "code": null, "e": 25456, "s": 25446, "text": "DNSDB.org" }, { "code": null, "e": 25483, "s": 25456, "text": "Google Transparency Report" }, { "code": null, "e": 25496, "s": 25483, "text": "HackerTarget" }, { "code": null, "e": 25505, "s": 25496, "text": "Netcraft" }, { "code": null, "e": 25531, "s": 25505, "text": "Shodan (requires API key)" }, { "code": null, "e": 25543, "s": 25531, "text": "ThreatCrowd" }, { "code": null, "e": 25573, "s": 25543, "text": "VirusTotal (requires API key)" }, { "code": null, "e": 25705, "s": 25573, "text": "The scanning stage is where AQUATONE will enumerate the recognized hosts for open TCP ports that are usually used for web services." }, { "code": null, "e": 26041, "s": 25705, "text": "The last stage is the gathering phase, in which the results of discovery and scanning stages are used to make the discovered web services return and save HTTP response headers packets and HTML bodies, as well as taking the snapshots of how the web page or domain looks like in web browser which makes the analysis much more accessible." }, { "code": null, "e": 26126, "s": 26041, "text": "Step 1: Download Google Chrome on your Linux System, by using the following command." }, { "code": null, "e": 26205, "s": 26126, "text": "wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb" }, { "code": null, "e": 26264, "s": 26205, "text": "Step 2: Install Google Chrome, using the following command" }, { "code": null, "e": 26322, "s": 26264, "text": "sudo apt install ./google-chrome-stable_current_amd64.deb" }, { "code": null, "e": 26370, "s": 26322, "text": "Step 3: Download Aquatone Zip from Github Page." }, { "code": null, "e": 26431, "s": 26370, "text": "https://github.com/michenriksen/aquatone/releases/tag/v1.7.0" }, { "code": null, "e": 26481, "s": 26431, "text": "Step 4: After Downloading Extract the zip folder." }, { "code": null, "e": 26505, "s": 26481, "text": "Right Click and Extract" }, { "code": null, "e": 26562, "s": 26505, "text": "Step 5: Go to Terminal and change directory to Downloads" }, { "code": null, "e": 26606, "s": 26562, "text": "cd Downloads\ncd aquatone_linux_amd64_1.7.0/" }, { "code": null, "e": 26651, "s": 26606, "text": "Step 6: Move Aquatone in the bin directory." }, { "code": null, "e": 26684, "s": 26651, "text": "sudo mv aquatone /usr/local/bin/" }, { "code": null, "e": 26788, "s": 26684, "text": "Step 7: Check the help page of aquatone for a better understanding of usage, use the following command." }, { "code": null, "e": 26804, "s": 26788, "text": "aquatone --help" }, { "code": null, "e": 26825, "s": 26804, "text": "Example 1: Discovery" }, { "code": null, "e": 26870, "s": 26825, "text": "aquatone-discover --domain geeksforgeeks.org" }, { "code": null, "e": 26967, "s": 26870, "text": "1. The aquatone does is to identify the information about the target domain (geeksforgeeks.org)." }, { "code": null, "e": 27049, "s": 26967, "text": "2. 8277 Unique Hosts are Resolved along with the IP addresses and the subdomains." }, { "code": null, "e": 27069, "s": 27049, "text": "Example 2: Scanning" }, { "code": null, "e": 27104, "s": 27069, "text": "aquatone-scan -d geeksforgeeks.org" }, { "code": null, "e": 27208, "s": 27104, "text": "1. Using the hosts.json file, which contains the 90 hosts is used for scanning to get the port details." }, { "code": null, "e": 27301, "s": 27208, "text": "2. All the Probed Ports are stored in open_ports.txt with IP address and port number opened." }, { "code": null, "e": 27346, "s": 27301, "text": "3. All the URLs are stored in urls.txt file." }, { "code": null, "e": 27367, "s": 27346, "text": "Example 3: Gathering" }, { "code": null, "e": 27404, "s": 27367, "text": "aquatone-gather -d geeksforgeeks.org" }, { "code": null, "e": 27527, "s": 27404, "text": "In this example, we are gathering the information on geeksforgeeks.org (like subdomains, status codes, Ip addresses, etc)." }, { "code": null, "e": 27550, "s": 27527, "text": "Example 4: CLI Tricks " }, { "code": null, "e": 27619, "s": 27550, "text": "Getting more Subdomains of geeksforgeeks.org (filtering the results)" }, { "code": null, "e": 27683, "s": 27619, "text": "cat * | egrep -o '[a-z0-9\\-\\_\\.]+\\geeksforgeeks\\.org' | sort -u" }, { "code": null, "e": 27716, "s": 27683, "text": "Example 5: Finding HTML Comments" }, { "code": null, "e": 27786, "s": 27716, "text": "Using Filtering skills to get HTML comments from HTML directory data." }, { "code": null, "e": 27815, "s": 27786, "text": "cat * | egrep -o '<!--.*-->'" }, { "code": null, "e": 27861, "s": 27815, "text": "Example 6: Finding pages with password fields" }, { "code": null, "e": 27921, "s": 27861, "text": "Finding Password fields using Filtering the results (grep)." }, { "code": null, "e": 27946, "s": 27921, "text": "grep 'type=\"password\"' *" }, { "code": null, "e": 27983, "s": 27946, "text": "Example 7 : Specifying ports to scan" }, { "code": null, "e": 28229, "s": 27983, "text": "1. By default, the Aquatone tool will scan target hosts with a small list of commonly used HTTP ports: 80, 443, 8000, 8080, and 8443. We can change this variety of ports list using the -ports flag. You can check the help section for more details" }, { "code": null, "e": 28278, "s": 28229, "text": "cat hosts.txt | aquatone -ports 80,443,3000,3001" }, { "code": null, "e": 28376, "s": 28278, "text": "2. Aquatone also supports nicknames of built-in port records to make it more comfortable for you:" }, { "code": null, "e": 28391, "s": 28376, "text": "small: 80, 443" }, { "code": null, "e": 28443, "s": 28391, "text": "medium: 80, 443, 8000, 8080, 8443 (same as default)" }, { "code": null, "e": 28545, "s": 28443, "text": "large: 80, 81, 443, 591, 2082, 2087, 2095, 2096, 3000, 8000, 8001, 8008, 8080, 8083, 8443, 8834, 8888" }, { "code": null, "e": 28980, "s": 28545, "text": "xlarge: 80, 81, 300, 443, 591, 593, 832, 981, 1010, 1311, 2082, 2087, 2095, 2096, 2480, 3000, 3128, 3333, 4243, 4567, 4711, 4712, 4993, 5000, 5104, 5108, 5800, 6543, 7000, 7396, 7474, 8000, 8001, 8008, 8014, 8042, 8069, 8080, 8081, 8088, 8090, 8091, 8118, 8123, 8172, 8222, 8243, 8280, 8281, 8333, 8443, 8500, 8834, 8880, 8888, 8983, 9000, 9043, 9060, 9080, 9090, 9091, 9200, 9443, 9800, 9981, 12443, 16080, 18091, 18092, 20720, 28017" }, { "code": null, "e": 29018, "s": 28980, "text": "cat hosts.txt | aquatone -ports large" }, { "code": null, "e": 29114, "s": 29018, "text": "In the below screenshot, we have used large ports lists for getting the ports enabled on hosts." }, { "code": null, "e": 29144, "s": 29114, "text": "Example 8: Subdomain Takeover" }, { "code": null, "e": 29189, "s": 29144, "text": "aquatone-takeover --domain geeksforgeeks.org" }, { "code": null, "e": 29284, "s": 29189, "text": "aquatone has the feature to check the domain if it is vulnerable to Subdomain Takeover or not." }, { "code": null, "e": 29317, "s": 29284, "text": "Example 9: Amass DNS enumeration" }, { "code": null, "e": 29377, "s": 29317, "text": "amass enum -active -brute -o hosts.txt -d geeksforgeeks.org" }, { "code": null, "e": 29456, "s": 29377, "text": "Aquatone has the feature to integrate with the Amass tool for DNS Enumeration." }, { "code": null, "e": 29481, "s": 29456, "text": "Example 10: Screen Shots" }, { "code": null, "e": 29618, "s": 29481, "text": "1. Aquatone is popular for its Screenshot taking feature, in the below screenshot aquatone has taken the screenshot of geeksforgeeks.org" }, { "code": null, "e": 29671, "s": 29618, "text": "Example 11: More Information about geeksforgeeks.org" }, { "code": null, "e": 29788, "s": 29671, "text": "You can see we have got more information about geeksforgeeks.org like Server information, Response Header info, etc." }, { "code": null, "e": 30140, "s": 29788, "text": "AQUATONE is a very useful tool for discovering information of multiple targets at the same time. The Screenshot-taking feature makes it more attractive and special as attackers need to check each subdomain manually, so to avoid this attackers can now run the aquatone on various subdomains at a time and check the subdomain’s status (active/inactive)." }, { "code": null, "e": 30151, "s": 30140, "text": "infoseczak" }, { "code": null, "e": 30162, "s": 30151, "text": "Kali-Linux" }, { "code": null, "e": 30174, "s": 30162, "text": "Linux-Tools" }, { "code": null, "e": 30185, "s": 30174, "text": "Linux-Unix" }, { "code": null, "e": 30283, "s": 30185, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30320, "s": 30283, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 30355, "s": 30320, "text": "scp command in Linux with Examples" }, { "code": null, "e": 30381, "s": 30355, "text": "Thread functions in C/C++" }, { "code": null, "e": 30415, "s": 30381, "text": "mv command in Linux with examples" }, { "code": null, "e": 30452, "s": 30415, "text": "chown command in Linux with Examples" }, { "code": null, "e": 30481, "s": 30452, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 30507, "s": 30481, "text": "Docker - COPY Instruction" }, { "code": null, "e": 30547, "s": 30507, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 30582, "s": 30547, "text": "Basic Operators in Shell Scripting" } ]
Multiple Time Series Forecast & Demand Pattern Classification using R — Part 2 | by Gouthaman Tharmathasan | Towards Data Science
Ensemble, ARIMA, ETS, Dynamic Harmonic Regression, Time Series Linear Regression, STL Decomposition ETS, Holt’s Linear, Holt’s Linear Damp, Simple Exponential Smoothing, Drift, Seasonal NAIVE, NAIVE, CROSTON, SBA This is a continuation of my previous blog. In the previous blog, we looked at how we perform basic data preprocessing & how to classify time series using the function idclass. This series will have the following 5 parts: Part 1: Data Cleaning & Demand categorization. Part 2: Fit statistical Time Series models (ARIMA, ETS, CROSTON etc.) using fpp3 (tidy forecasting) R Package. Part 3: Time Series Feature Engineering using timetk R Package. Part 4: Fit Machine Learning models (XGBoost, Random Forest, etc.) & Hyperparameter tuning using modeltime & tidymodels R packages. Part 5: Fit Deeplearning models (NBeats & DeepAR) & Hyperparameter tuning using modeltime, modeltime.gluonts R packages. In this blog, I will explain how to fit the classical time series models (ARIMA, ETS, Decomposition Model etc.) on a group time-series data (3,548 groups) and select suitable time series model for each group. Let’s get started! The above diagram shows the workflow carried out to fit classic statistical models. In this workflow, the first stage (Read Data, Data Preparation & Demand Categorization) was explained in my previous blog. Here we will focus on fitting statistical models & calculating Root Mean Squared Logarithmic Error (RMSLE) accuracy measure to select suitable models. Let’s import libraries. pacman::p_load(tidyverse, magrittr) # data wrangling packagespacman::p_load(lubridate, tsintermittent, fpp3, modeltime, timetk, modeltime.gluonts, tidymodels, modeltime.ensemble, modeltime.resample) # time series model packagespacman::p_load(foreach, future) # parallel functionspacman::p_load(viridis, plotly) # visualizations packagestheme_set(hrbrthemes::theme_ipsum()) # set default themes We have already identified a demand type for each meal/centre group. Now we will filter only smooth & erratic demand types meal/centre groups time series data. smooth_tbl <- master_data_tbl %>% filter(demand_cate %in% c("Smooth", "Erratic")) Now filtered data is split into train & test (last 10 weeks) data for each meal/centre combo. train_tbl <- smooth_tbl %>% filter_index(. ~ "2018-07-23")test_tbl <- smooth_tbl %>% filter_index("2018-07-30" ~ .) Note: Here our data frame is a tsibble object, which is a special type of data frame which works with time-series data. We have already specified “center & meal IDs” as key variables in tsibble “master_data_tbl”. So our tidyverse functions will apply to all the meal/center groups. For example, when we apply the function “filter_index” this will filter by date for all the groups. Next, we are going to fit the following 11-time series models for each meal/centre group i.e. fit a total of 34,265 models. How are there 34,265 models? There are 1,839 smooth & 1,276 erratic types meal/centre groups, which makes a total of 3,115 different groups. We will fit 11 different models for each group, making a total of 3,115 * 11 = 34,265. Naive: The Naive model sets all future values the same as the last observation value. Seasonal Naive: The seasonal naive model is used for seasonal data. In this situation, each future value is equal to the last value of the same season. Drift: The drift model is a variation of Naive model, allowing forecast to increase or decrease over time. Simple Exponential Smooth: The simple exponential smooth model is used when a clear trend or seasonal pattern cannot be identified. Holt’s Linear: The Holt’s Linear model is an extended version of SES allowing to forecast with the trend. Damped Holt’s Linear: The Damped Additive Trend model is an extended version of Holt’s Linear, allowing the trend to change over time with a damped parameter phi. Forecasting with Decomposition: The decomposition model is used to decompose the time series using the Seasonal and Trend decomposition using Loess (STL) method. ETS method can then be used to forecast the seasonally adjusted data, after which the seasonal component can be added to the forecast data. ARIMA: The ARIMA models explain the autocorrelations in the data. Here we are going to fit an automatic ARIMA model which automatically selects the ARMA orders using min AICC. Dynamic Harmonic Regression: The Dynamic Harmonic Regression model allows the inclusion of other data, such as base price, checkout price, email promotion & homepage featured. Time Series Regression: The time series regression model is used to forecast the dependent variable Y assuming that it has a linear relationship with other independent variables X. i.e. in this situation, an assumption is made when forecasting that the number of orders and checkout price, base price, emailer for promotion & homepage featured have a linear relationship. Ensemble: The ensemble model simply uses several different models at the same time and calculates an average value of the resulting forecasts. For example, here, ARIMA, SES & Decomposition models are used together to calculate the average forecast value. Now, we will fit the above 11 models in R using the R package fpp3 . Here we have log-transformed the number of orders to impose a positive constraint. You can see in R code we have added one as an offset; this is to overcome log(0) infinity issue. This will take longer to run since it is fitting 34k models. fpp3_model_table <- train_tbl %>% model( ## Model 1: Naive ---- naive_mod = NAIVE(log(num_orders + 1)), ## Model 2: Snaive ---- snaive_mod = SNAIVE(log(num_orders + 1)), ## Model 3: Drift ---- drift_mod = RW(log(num_orders + 1) ~ drift()), ## Model 4: SES ---- ses_mod = ETS(log(num_orders + 1) ~ error("A") + trend("N") + season("N"), opt_crit = "mse"), ## Model 5: Holt's Linear ---- hl_mod = ETS(log(num_orders + 1) ~ error("A") + trend("A") + season("N"), opt_crit = "mse"), ## Model 6: Damped Holt's Linear ---- hldamp_mod = ETS(log(num_orders + 1) ~ error("A") + trend("Ad") + season("N"), opt_crit = "mse"), ## Model 7: STL decomposition with ETS ---- stl_ets_mod = decomposition_model(STL(log(num_orders + 1)), ETS(season_adjust ~ season("N"))), ## Model 8: ARIMA ---- arima_mod = ARIMA(log(num_orders + 1)), ## Model 9: Dynamic harmonic regression ---- dhr_mod = ARIMA(log(num_orders + 1) ~ PDQ(0,0,0) + fourier(K=6) + checkout_price + emailer_for_promotion), ## Model 10: TSLM ---- tslm_mod = TSLM(log(num_orders + 1) ~ checkout_price + base_price + emailer_for_promotion)) %>% ## Model 11: Ensemble Model ---- mutate(ensemble_sm_mod = combination_ensemble(arima_mod, ses_mod, stl_ets_mod)) In this step, we will filter the intermittent & lumpy meal/centre groups time series data. inter_tbl <- master_data_tbl %>% filter(demand_cate %in% c("Intermittent", "Lumpy")) Now the filtered data is split into train & test (last 10 weeks) data for each meal/centre group. train_tbl <- inter_tbl %>% filter_index(. ~ "2018 W30")test_tbl <- inter_tbl %>% filter_index("2018 W31" ~ .) Next, we will fit the following 5-time series models for each meal/centre group i.e. fit a total of 1,960 models. How are there 1,960 models? There are 273 Intermittent & 119 lumpy types meal/centre groups, which makes a total of 392 different groups. We are going to fit 5 different models for each group, making a total of 392* 5= 1,960. Simple Exponential Smooth: Refer to the above explanation. ARIMA: Refer to the above explanation. CROSTON: The Croston model is the most suitable method for slow-moving products (intermittent). SBA: The SBA model is another variant / improved version of Croston method. Ensemble: Here, CROSTON, SBA, ARIMA & SES models are used together to calculate the average forecast value. Now, we will fit the above 5 models in R using the R package fpp3 . fpp3_model_table <- train_tbl %>% model( ## Model 1: Croston ---- crost_mod = CROSTON(log(num_orders + 1)), ## Model 2: SBA ---- sba_mod = CROSTON(log(num_orders + 1), type = "sba"), ## Model 3: SES ---- ses_mod = ETS(log(num_orders + 1) ~ error("A") + trend("N") + season("N"), opt_crit = "mse"), ## Model 4: ARIMA ---- arima_mod = ARIMA(log(num_orders + 1))) %>% ## Model 5: Ensemble ---- mutate(ensemble_inter_mod = combination_ensemble(crost_mod, sba_mod, ses_mod, arima_mod)) We have now 36,225 (i.e. 34,265 + 1,960) fitted models. Next, we need to find out which model is suitable for each meal/centre group. In order to do this, we have to forecast each model on the Test period and calculate their accuracy measure. Now we will forecast on the Test period. forecast_tbl <- fpp3_model_table %>% forecast(test_tbl, times = 0) %>% as_tibble() %>% select(week_date, meal_id, center_id, .model, fc_qty = .mean) In this stage, we will calculate the accuracy of each model in order to select a suitable model for each meal/centre group. The accuracy measure used here was the Root Mean Squared Logarithmic Error (RMSLE). I chose RMSLE simply because it was the measure used for this competition to evaluate. However, I personally prefer RMSSE as this was used in the M5 forecasting competition. RMSLE can be calculated in R by using the functionrmsle in the R package Metrics. forecast_tbl <- master_data_tbl %>% as_tibble() %>% # change tsibble -> tibble select(week_date, center_id, meal_id, num_orders) %>% right_join(forecast_tbl, by = c("week_date", "meal_id", "center_id")) %>% # join forecast values mutate(fc_qty = ifelse(fc_qty < 0, 0, fc_qty)) # change negative & NA ordersaccuracy_tbl <- forecast_tbl %>% group_by(center_id, meal_id, .model) %>% summarise(accuracy_rmsle = Metrics::rmsle(num_orders, fc_qty)) # calculate RMSLE In this stage, we are going to select a suitable model for each meal/centre group based on minimum RMSLE. suitable_model_tbl <- accuracy_tbl %>% ungroup() %>% group_by(meal_id, center_id) %>% filter(accuracy_rmsle == min(accuracy_rmsle)) %>% slice(n = 1) Now we have a list of models which are suitable for each meal/centre group. For example, the table below shows us that for Centre 110 & Meal 2104, the most suitable model is Seasonal Naive (snaive_mod ), whereas, the most suitable model for Centre 67 & Meal 1885 is Holt’s Linear model (hl_mod). These corresponding models can be used for each group in the future to forecast the number of orders. The above plot shows an overview of the accuracy of our suitable models. It shows that high accuracy (i.e. less than 1 RMSLE) was achieved for a majority of meal/centre groups. However, there were a few meal/centre groups which revealed low accuracy; for these low accuracy groups, other advanced time-series/machine learning models could be fitted to increase the forecast accuracy. Furthermore, the majority of groups with low accuracy were Lumpy/Intermittent which meant that for these type of groups, rather than fitting advance models, the focus should be on safety stock calculations. The above plot shows the number of meal/centre groups against the suitable models, chosen by minimum RMSLE. It shows that ARIMA, Dynamic Harmonic Regression & Time-Series Regression models are the most fitted models for meal/centre groups. So, now we know how to fit classical time series models for a group of time-series data. However, this has some disadvantage in practical/business world. What are those disadvantages? Time: It takes a very long time to train when the number of groups increases. For example, in our case, we need to train nearly 35k models in order to find 3.5k suitable models.Reproducibility: Once you find a suitable model for a group we assume that the same model will also be used for the future. In practice, this is not the case, since the most suitable model can change when new transactions are added.No Scalability: There is no one global model. i.e. we have had to fit different models for each group. Time: It takes a very long time to train when the number of groups increases. For example, in our case, we need to train nearly 35k models in order to find 3.5k suitable models. Reproducibility: Once you find a suitable model for a group we assume that the same model will also be used for the future. In practice, this is not the case, since the most suitable model can change when new transactions are added. No Scalability: There is no one global model. i.e. we have had to fit different models for each group. What can we do to overcome these issues? The answer to these issues is Machine Learning & Deep Learning models. In my next blog, I will explain how we can fit Machine Learning & Deep Learning models and do feature engineering. This machine learning model also increases our accuracy significantly. Hyndman, R.J., & Athanasopoulos, G. (2021) Forecasting: principles and practice, 3rd edition, OTexts: Melbourne, Australia. OTexts.com/fpp3. Accessed on [Accessed 08 February 2021]. Kourentzes, N., 2014. Intermittent Demand Forecasting Package For R — Nikolaos Kourentzes. Kourentzes.com. Available at: <https://kourentzes.com/forecasting/2014/06/23/intermittent-demand-forecasting-package-for-r/> [Accessed 22 January 2021].
[ { "code": null, "e": 384, "s": 171, "text": "Ensemble, ARIMA, ETS, Dynamic Harmonic Regression, Time Series Linear Regression, STL Decomposition ETS, Holt’s Linear, Holt’s Linear Damp, Simple Exponential Smoothing, Drift, Seasonal NAIVE, NAIVE, CROSTON, SBA" }, { "code": null, "e": 606, "s": 384, "text": "This is a continuation of my previous blog. In the previous blog, we looked at how we perform basic data preprocessing & how to classify time series using the function idclass. This series will have the following 5 parts:" }, { "code": null, "e": 653, "s": 606, "text": "Part 1: Data Cleaning & Demand categorization." }, { "code": null, "e": 764, "s": 653, "text": "Part 2: Fit statistical Time Series models (ARIMA, ETS, CROSTON etc.) using fpp3 (tidy forecasting) R Package." }, { "code": null, "e": 828, "s": 764, "text": "Part 3: Time Series Feature Engineering using timetk R Package." }, { "code": null, "e": 960, "s": 828, "text": "Part 4: Fit Machine Learning models (XGBoost, Random Forest, etc.) & Hyperparameter tuning using modeltime & tidymodels R packages." }, { "code": null, "e": 1081, "s": 960, "text": "Part 5: Fit Deeplearning models (NBeats & DeepAR) & Hyperparameter tuning using modeltime, modeltime.gluonts R packages." }, { "code": null, "e": 1290, "s": 1081, "text": "In this blog, I will explain how to fit the classical time series models (ARIMA, ETS, Decomposition Model etc.) on a group time-series data (3,548 groups) and select suitable time series model for each group." }, { "code": null, "e": 1309, "s": 1290, "text": "Let’s get started!" }, { "code": null, "e": 1667, "s": 1309, "text": "The above diagram shows the workflow carried out to fit classic statistical models. In this workflow, the first stage (Read Data, Data Preparation & Demand Categorization) was explained in my previous blog. Here we will focus on fitting statistical models & calculating Root Mean Squared Logarithmic Error (RMSLE) accuracy measure to select suitable models." }, { "code": null, "e": 1691, "s": 1667, "text": "Let’s import libraries." }, { "code": null, "e": 2085, "s": 1691, "text": "pacman::p_load(tidyverse, magrittr) # data wrangling packagespacman::p_load(lubridate, tsintermittent, fpp3, modeltime, timetk, modeltime.gluonts, tidymodels, modeltime.ensemble, modeltime.resample) # time series model packagespacman::p_load(foreach, future) # parallel functionspacman::p_load(viridis, plotly) # visualizations packagestheme_set(hrbrthemes::theme_ipsum()) # set default themes" }, { "code": null, "e": 2245, "s": 2085, "text": "We have already identified a demand type for each meal/centre group. Now we will filter only smooth & erratic demand types meal/centre groups time series data." }, { "code": null, "e": 2328, "s": 2245, "text": "smooth_tbl <- master_data_tbl %>% filter(demand_cate %in% c(\"Smooth\", \"Erratic\"))" }, { "code": null, "e": 2422, "s": 2328, "text": "Now filtered data is split into train & test (last 10 weeks) data for each meal/centre combo." }, { "code": null, "e": 2540, "s": 2422, "text": "train_tbl <- smooth_tbl %>% filter_index(. ~ \"2018-07-23\")test_tbl <- smooth_tbl %>% filter_index(\"2018-07-30\" ~ .)" }, { "code": null, "e": 2922, "s": 2540, "text": "Note: Here our data frame is a tsibble object, which is a special type of data frame which works with time-series data. We have already specified “center & meal IDs” as key variables in tsibble “master_data_tbl”. So our tidyverse functions will apply to all the meal/center groups. For example, when we apply the function “filter_index” this will filter by date for all the groups." }, { "code": null, "e": 3046, "s": 2922, "text": "Next, we are going to fit the following 11-time series models for each meal/centre group i.e. fit a total of 34,265 models." }, { "code": null, "e": 3075, "s": 3046, "text": "How are there 34,265 models?" }, { "code": null, "e": 3274, "s": 3075, "text": "There are 1,839 smooth & 1,276 erratic types meal/centre groups, which makes a total of 3,115 different groups. We will fit 11 different models for each group, making a total of 3,115 * 11 = 34,265." }, { "code": null, "e": 3360, "s": 3274, "text": "Naive: The Naive model sets all future values the same as the last observation value." }, { "code": null, "e": 3512, "s": 3360, "text": "Seasonal Naive: The seasonal naive model is used for seasonal data. In this situation, each future value is equal to the last value of the same season." }, { "code": null, "e": 3619, "s": 3512, "text": "Drift: The drift model is a variation of Naive model, allowing forecast to increase or decrease over time." }, { "code": null, "e": 3751, "s": 3619, "text": "Simple Exponential Smooth: The simple exponential smooth model is used when a clear trend or seasonal pattern cannot be identified." }, { "code": null, "e": 3857, "s": 3751, "text": "Holt’s Linear: The Holt’s Linear model is an extended version of SES allowing to forecast with the trend." }, { "code": null, "e": 4020, "s": 3857, "text": "Damped Holt’s Linear: The Damped Additive Trend model is an extended version of Holt’s Linear, allowing the trend to change over time with a damped parameter phi." }, { "code": null, "e": 4322, "s": 4020, "text": "Forecasting with Decomposition: The decomposition model is used to decompose the time series using the Seasonal and Trend decomposition using Loess (STL) method. ETS method can then be used to forecast the seasonally adjusted data, after which the seasonal component can be added to the forecast data." }, { "code": null, "e": 4498, "s": 4322, "text": "ARIMA: The ARIMA models explain the autocorrelations in the data. Here we are going to fit an automatic ARIMA model which automatically selects the ARMA orders using min AICC." }, { "code": null, "e": 4674, "s": 4498, "text": "Dynamic Harmonic Regression: The Dynamic Harmonic Regression model allows the inclusion of other data, such as base price, checkout price, email promotion & homepage featured." }, { "code": null, "e": 5046, "s": 4674, "text": "Time Series Regression: The time series regression model is used to forecast the dependent variable Y assuming that it has a linear relationship with other independent variables X. i.e. in this situation, an assumption is made when forecasting that the number of orders and checkout price, base price, emailer for promotion & homepage featured have a linear relationship." }, { "code": null, "e": 5301, "s": 5046, "text": "Ensemble: The ensemble model simply uses several different models at the same time and calculates an average value of the resulting forecasts. For example, here, ARIMA, SES & Decomposition models are used together to calculate the average forecast value." }, { "code": null, "e": 5550, "s": 5301, "text": "Now, we will fit the above 11 models in R using the R package fpp3 . Here we have log-transformed the number of orders to impose a positive constraint. You can see in R code we have added one as an offset; this is to overcome log(0) infinity issue." }, { "code": null, "e": 5611, "s": 5550, "text": "This will take longer to run since it is fitting 34k models." }, { "code": null, "e": 6875, "s": 5611, "text": "fpp3_model_table <- train_tbl %>% model( ## Model 1: Naive ---- naive_mod = NAIVE(log(num_orders + 1)), ## Model 2: Snaive ---- snaive_mod = SNAIVE(log(num_orders + 1)), ## Model 3: Drift ---- drift_mod = RW(log(num_orders + 1) ~ drift()), ## Model 4: SES ---- ses_mod = ETS(log(num_orders + 1) ~ error(\"A\") + trend(\"N\") + season(\"N\"), opt_crit = \"mse\"), ## Model 5: Holt's Linear ---- hl_mod = ETS(log(num_orders + 1) ~ error(\"A\") + trend(\"A\") + season(\"N\"), opt_crit = \"mse\"), ## Model 6: Damped Holt's Linear ---- hldamp_mod = ETS(log(num_orders + 1) ~ error(\"A\") + trend(\"Ad\") + season(\"N\"), opt_crit = \"mse\"), ## Model 7: STL decomposition with ETS ---- stl_ets_mod = decomposition_model(STL(log(num_orders + 1)), ETS(season_adjust ~ season(\"N\"))), ## Model 8: ARIMA ---- arima_mod = ARIMA(log(num_orders + 1)), ## Model 9: Dynamic harmonic regression ---- dhr_mod = ARIMA(log(num_orders + 1) ~ PDQ(0,0,0) + fourier(K=6) + checkout_price + emailer_for_promotion), ## Model 10: TSLM ---- tslm_mod = TSLM(log(num_orders + 1) ~ checkout_price + base_price + emailer_for_promotion)) %>% ## Model 11: Ensemble Model ---- mutate(ensemble_sm_mod = combination_ensemble(arima_mod, ses_mod, stl_ets_mod))" }, { "code": null, "e": 6966, "s": 6875, "text": "In this step, we will filter the intermittent & lumpy meal/centre groups time series data." }, { "code": null, "e": 7052, "s": 6966, "text": "inter_tbl <- master_data_tbl %>% filter(demand_cate %in% c(\"Intermittent\", \"Lumpy\"))" }, { "code": null, "e": 7150, "s": 7052, "text": "Now the filtered data is split into train & test (last 10 weeks) data for each meal/centre group." }, { "code": null, "e": 7262, "s": 7150, "text": "train_tbl <- inter_tbl %>% filter_index(. ~ \"2018 W30\")test_tbl <- inter_tbl %>% filter_index(\"2018 W31\" ~ .)" }, { "code": null, "e": 7376, "s": 7262, "text": "Next, we will fit the following 5-time series models for each meal/centre group i.e. fit a total of 1,960 models." }, { "code": null, "e": 7404, "s": 7376, "text": "How are there 1,960 models?" }, { "code": null, "e": 7602, "s": 7404, "text": "There are 273 Intermittent & 119 lumpy types meal/centre groups, which makes a total of 392 different groups. We are going to fit 5 different models for each group, making a total of 392* 5= 1,960." }, { "code": null, "e": 7661, "s": 7602, "text": "Simple Exponential Smooth: Refer to the above explanation." }, { "code": null, "e": 7700, "s": 7661, "text": "ARIMA: Refer to the above explanation." }, { "code": null, "e": 7796, "s": 7700, "text": "CROSTON: The Croston model is the most suitable method for slow-moving products (intermittent)." }, { "code": null, "e": 7872, "s": 7796, "text": "SBA: The SBA model is another variant / improved version of Croston method." }, { "code": null, "e": 7980, "s": 7872, "text": "Ensemble: Here, CROSTON, SBA, ARIMA & SES models are used together to calculate the average forecast value." }, { "code": null, "e": 8048, "s": 7980, "text": "Now, we will fit the above 5 models in R using the R package fpp3 ." }, { "code": null, "e": 8556, "s": 8048, "text": "fpp3_model_table <- train_tbl %>% model( ## Model 1: Croston ---- crost_mod = CROSTON(log(num_orders + 1)), ## Model 2: SBA ---- sba_mod = CROSTON(log(num_orders + 1), type = \"sba\"), ## Model 3: SES ---- ses_mod = ETS(log(num_orders + 1) ~ error(\"A\") + trend(\"N\") + season(\"N\"), opt_crit = \"mse\"), ## Model 4: ARIMA ---- arima_mod = ARIMA(log(num_orders + 1))) %>% ## Model 5: Ensemble ---- mutate(ensemble_inter_mod = combination_ensemble(crost_mod, sba_mod, ses_mod, arima_mod))" }, { "code": null, "e": 8799, "s": 8556, "text": "We have now 36,225 (i.e. 34,265 + 1,960) fitted models. Next, we need to find out which model is suitable for each meal/centre group. In order to do this, we have to forecast each model on the Test period and calculate their accuracy measure." }, { "code": null, "e": 8840, "s": 8799, "text": "Now we will forecast on the Test period." }, { "code": null, "e": 8998, "s": 8840, "text": "forecast_tbl <- fpp3_model_table %>% forecast(test_tbl, times = 0) %>% as_tibble() %>% select(week_date, meal_id, center_id, .model, fc_qty = .mean)" }, { "code": null, "e": 9380, "s": 8998, "text": "In this stage, we will calculate the accuracy of each model in order to select a suitable model for each meal/centre group. The accuracy measure used here was the Root Mean Squared Logarithmic Error (RMSLE). I chose RMSLE simply because it was the measure used for this competition to evaluate. However, I personally prefer RMSSE as this was used in the M5 forecasting competition." }, { "code": null, "e": 9462, "s": 9380, "text": "RMSLE can be calculated in R by using the functionrmsle in the R package Metrics." }, { "code": null, "e": 9929, "s": 9462, "text": "forecast_tbl <- master_data_tbl %>% as_tibble() %>% # change tsibble -> tibble select(week_date, center_id, meal_id, num_orders) %>% right_join(forecast_tbl, by = c(\"week_date\", \"meal_id\", \"center_id\")) %>% # join forecast values mutate(fc_qty = ifelse(fc_qty < 0, 0, fc_qty)) # change negative & NA ordersaccuracy_tbl <- forecast_tbl %>% group_by(center_id, meal_id, .model) %>% summarise(accuracy_rmsle = Metrics::rmsle(num_orders, fc_qty)) # calculate RMSLE" }, { "code": null, "e": 10035, "s": 9929, "text": "In this stage, we are going to select a suitable model for each meal/centre group based on minimum RMSLE." }, { "code": null, "e": 10188, "s": 10035, "text": "suitable_model_tbl <- accuracy_tbl %>% ungroup() %>% group_by(meal_id, center_id) %>% filter(accuracy_rmsle == min(accuracy_rmsle)) %>% slice(n = 1)" }, { "code": null, "e": 10264, "s": 10188, "text": "Now we have a list of models which are suitable for each meal/centre group." }, { "code": null, "e": 10586, "s": 10264, "text": "For example, the table below shows us that for Centre 110 & Meal 2104, the most suitable model is Seasonal Naive (snaive_mod ), whereas, the most suitable model for Centre 67 & Meal 1885 is Holt’s Linear model (hl_mod). These corresponding models can be used for each group in the future to forecast the number of orders." }, { "code": null, "e": 11177, "s": 10586, "text": "The above plot shows an overview of the accuracy of our suitable models. It shows that high accuracy (i.e. less than 1 RMSLE) was achieved for a majority of meal/centre groups. However, there were a few meal/centre groups which revealed low accuracy; for these low accuracy groups, other advanced time-series/machine learning models could be fitted to increase the forecast accuracy. Furthermore, the majority of groups with low accuracy were Lumpy/Intermittent which meant that for these type of groups, rather than fitting advance models, the focus should be on safety stock calculations." }, { "code": null, "e": 11417, "s": 11177, "text": "The above plot shows the number of meal/centre groups against the suitable models, chosen by minimum RMSLE. It shows that ARIMA, Dynamic Harmonic Regression & Time-Series Regression models are the most fitted models for meal/centre groups." }, { "code": null, "e": 11601, "s": 11417, "text": "So, now we know how to fit classical time series models for a group of time-series data. However, this has some disadvantage in practical/business world. What are those disadvantages?" }, { "code": null, "e": 12113, "s": 11601, "text": "Time: It takes a very long time to train when the number of groups increases. For example, in our case, we need to train nearly 35k models in order to find 3.5k suitable models.Reproducibility: Once you find a suitable model for a group we assume that the same model will also be used for the future. In practice, this is not the case, since the most suitable model can change when new transactions are added.No Scalability: There is no one global model. i.e. we have had to fit different models for each group." }, { "code": null, "e": 12291, "s": 12113, "text": "Time: It takes a very long time to train when the number of groups increases. For example, in our case, we need to train nearly 35k models in order to find 3.5k suitable models." }, { "code": null, "e": 12524, "s": 12291, "text": "Reproducibility: Once you find a suitable model for a group we assume that the same model will also be used for the future. In practice, this is not the case, since the most suitable model can change when new transactions are added." }, { "code": null, "e": 12627, "s": 12524, "text": "No Scalability: There is no one global model. i.e. we have had to fit different models for each group." }, { "code": null, "e": 12668, "s": 12627, "text": "What can we do to overcome these issues?" }, { "code": null, "e": 12739, "s": 12668, "text": "The answer to these issues is Machine Learning & Deep Learning models." }, { "code": null, "e": 12925, "s": 12739, "text": "In my next blog, I will explain how we can fit Machine Learning & Deep Learning models and do feature engineering. This machine learning model also increases our accuracy significantly." }, { "code": null, "e": 13107, "s": 12925, "text": "Hyndman, R.J., & Athanasopoulos, G. (2021) Forecasting: principles and practice, 3rd edition, OTexts: Melbourne, Australia. OTexts.com/fpp3. Accessed on [Accessed 08 February 2021]." } ]
Aurelia - Custom Elements
Aurelia offers a way to add components dynamically. You can reuse a single component on different parts of your app without the need to include HTML multiple times. In this chapter, you will learn how to achieve this. Let's create new components directory inside src folder. C:\Users\username\Desktop\aureliaApp\src>mkdir components Inside this directory, we will create custom-component.html. This component will be inserted later in the HTML page. <template> <p>This is some text from dynamic component...</p> </template> We will create simple component in app.js. It will be used to render header and footer text on screen. export class MyComponent { header = "This is Header"; content = "This is content"; } Inside our app.html file, we need to require the custom-component.html to be able to insert it dynamically. Once we do that, we can add a new element custom-component. <template> <require from = "./components/custom-component.html"></require> <h1>${header}</h1> <p>${content}</p> <custom-component></custom-component> </template> Following is the output. Header and Footer text is rendered from myComponent inside app.js. The additional text is rendered from the custom-component.js. Print Add Notes Bookmark this page
[ { "code": null, "e": 2383, "s": 2165, "text": "Aurelia offers a way to add components dynamically. You can reuse a single component on different parts of your app without the need to include HTML multiple times. In this chapter, you will learn how to achieve this." }, { "code": null, "e": 2440, "s": 2383, "text": "Let's create new components directory inside src folder." }, { "code": null, "e": 2499, "s": 2440, "text": "C:\\Users\\username\\Desktop\\aureliaApp\\src>mkdir components\n" }, { "code": null, "e": 2616, "s": 2499, "text": "Inside this directory, we will create custom-component.html. This component will be inserted later in the HTML page." }, { "code": null, "e": 2693, "s": 2616, "text": "<template>\n <p>This is some text from dynamic component...</p>\n</template>" }, { "code": null, "e": 2796, "s": 2693, "text": "We will create simple component in app.js. It will be used to render header and footer text on screen." }, { "code": null, "e": 2887, "s": 2796, "text": "export class MyComponent {\n header = \"This is Header\";\n content = \"This is content\";\n}" }, { "code": null, "e": 3055, "s": 2887, "text": "Inside our app.html file, we need to require the custom-component.html to be able to insert it dynamically. Once we do that, we can add a new element custom-component." }, { "code": null, "e": 3230, "s": 3055, "text": "<template>\n <require from = \"./components/custom-component.html\"></require>\n\n <h1>${header}</h1>\n <p>${content}</p>\n <custom-component></custom-component>\n</template>" }, { "code": null, "e": 3384, "s": 3230, "text": "Following is the output. Header and Footer text is rendered from myComponent inside app.js. The additional text is rendered from the custom-component.js." }, { "code": null, "e": 3391, "s": 3384, "text": " Print" }, { "code": null, "e": 3402, "s": 3391, "text": " Add Notes" } ]
C++ Queue Library - operator== Function
The C++ function std::queue::operator== tests whether two queues are equal or not. Comparison is done by applying corresponding operator to the underlying container. Following is the declaration for std::queue::operator== function form std::queue header. template <class T, class Container> bool operator== (const queue<T,Container>& q1, const queue<T,Container>& q2); q1 − First queue object. q1 − First queue object. q2 − Second queue object. q2 − Second queue object. Returns true if both queues are identical otherwise false. This member function never throws exception. Linear i.e. O(n) The following example shows the usage of std::queue::operator== function. #include <iostream> #include <queue> using namespace std; int main(void) { queue<int> q1, q2; for (int i = 0; i < 5; ++i) { q1.push(i + 1); q2.push(i + 1); } if (q1 == q2) cout << "q1 and q2 are identical." << endl; q1.push(6); if (!(q1 == q2)) cout << "q1 and q2 are not identical." << endl; return 0; } Let us compile and run the above program, this will produce the following result − q1 and q2 are identical. q1 and q2 are not identical. Print Add Notes Bookmark this page
[ { "code": null, "e": 2769, "s": 2603, "text": "The C++ function std::queue::operator== tests whether two queues are equal or not. Comparison is done by applying corresponding operator to the underlying container." }, { "code": null, "e": 2858, "s": 2769, "text": "Following is the declaration for std::queue::operator== function form std::queue header." }, { "code": null, "e": 2973, "s": 2858, "text": "template <class T, class Container>\nbool operator== (const queue<T,Container>& q1, const queue<T,Container>& q2);\n" }, { "code": null, "e": 2998, "s": 2973, "text": "q1 − First queue object." }, { "code": null, "e": 3023, "s": 2998, "text": "q1 − First queue object." }, { "code": null, "e": 3049, "s": 3023, "text": "q2 − Second queue object." }, { "code": null, "e": 3075, "s": 3049, "text": "q2 − Second queue object." }, { "code": null, "e": 3134, "s": 3075, "text": "Returns true if both queues are identical otherwise false." }, { "code": null, "e": 3179, "s": 3134, "text": "This member function never throws exception." }, { "code": null, "e": 3196, "s": 3179, "text": "Linear i.e. O(n)" }, { "code": null, "e": 3270, "s": 3196, "text": "The following example shows the usage of std::queue::operator== function." }, { "code": null, "e": 3627, "s": 3270, "text": "#include <iostream>\n#include <queue>\n\nusing namespace std;\n\nint main(void) {\n queue<int> q1, q2;\n\n for (int i = 0; i < 5; ++i) {\n q1.push(i + 1);\n q2.push(i + 1);\n }\n\n if (q1 == q2)\n cout << \"q1 and q2 are identical.\" << endl;\n\n q1.push(6);\n\n if (!(q1 == q2))\n cout << \"q1 and q2 are not identical.\" << endl;\n\n return 0;\n}" }, { "code": null, "e": 3710, "s": 3627, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3765, "s": 3710, "text": "q1 and q2 are identical.\nq1 and q2 are not identical.\n" }, { "code": null, "e": 3772, "s": 3765, "text": " Print" }, { "code": null, "e": 3783, "s": 3772, "text": " Add Notes" } ]
Tail Recursion in Data Structures
Here we will see what is tail recursion. The tail recursion is basically using the recursive function as the last statement of the function. So when nothing is left to do after coming back from the recursive call, that is called tail recursion. We will see one example of tail recursion. Live Demo #include <iostream> using namespace std; void printN(int n){ if(n < 0){ return; } cout << n << " "; printN(n - 1); } int main() { printN(10); } 10 9 8 7 6 5 4 3 2 1 0 The tail recursion is better than non-tail recursion. As there is no task left after the recursive call, it will be easier for the compiler to optimize the code. When one function is called, its address is stored inside the stack. So if it is tail recursion, then storing addresses into stack is not needed. We can use factorial using recursion, but the function is not tail recursive. The value of fact(n-1) is used inside the fact(n). long fact(int n){ if(n <= 1) return 1; n * fact(n-1); } We can make it tail recursive, by adding some other parameters. This is like below − long fact(long n, long a){ if(n == 0) return a; return fact(n-1, a*n); }
[ { "code": null, "e": 1350, "s": 1062, "text": "Here we will see what is tail recursion. The tail recursion is basically using the recursive function as the last statement of the function. So when nothing is left to do after coming back from the recursive call, that is called tail recursion. We will see one example of tail recursion." }, { "code": null, "e": 1361, "s": 1350, "text": " Live Demo" }, { "code": null, "e": 1526, "s": 1361, "text": "#include <iostream>\nusing namespace std;\nvoid printN(int n){\n if(n < 0){\n return;\n }\n cout << n << \" \";\n printN(n - 1);\n}\nint main() {\n printN(10);\n}" }, { "code": null, "e": 1549, "s": 1526, "text": "10 9 8 7 6 5 4 3 2 1 0" }, { "code": null, "e": 1857, "s": 1549, "text": "The tail recursion is better than non-tail recursion. As there is no task left after the recursive call, it will be easier for the compiler to optimize the code. When one function is called, its address is stored inside the stack. So if it is tail recursion, then storing addresses into stack is not needed." }, { "code": null, "e": 1986, "s": 1857, "text": "We can use factorial using recursion, but the function is not tail recursive. The value of fact(n-1) is used inside the fact(n)." }, { "code": null, "e": 2054, "s": 1986, "text": "long fact(int n){\n if(n <= 1)\n return 1;\n n * fact(n-1);\n}" }, { "code": null, "e": 2139, "s": 2054, "text": "We can make it tail recursive, by adding some other parameters. This is like below −" }, { "code": null, "e": 2224, "s": 2139, "text": "long fact(long n, long a){\n if(n == 0)\n return a;\n return fact(n-1, a*n);\n}" } ]
Program to find lowest sum of pairs greater than given target in Python
Suppose we have a list of numbers called nums and another value target. We have to find the lowest sum of pair of numbers that is larger than target. So, if the input is like nums = [2, 4, 6, 10, 14] target = 10, then the output will be 12, as we pick 2 and 10 To solve this, we will follow these steps − sort the list nums n := size of nums answer := 10^10 i := 0, j := n - 1 while i < j, doif nums[i] + nums[j] > target, thenanswer := minimum of answer and (nums[i] + nums[j])j := j - 1otherwise,i := i + 1 if nums[i] + nums[j] > target, thenanswer := minimum of answer and (nums[i] + nums[j])j := j - 1 answer := minimum of answer and (nums[i] + nums[j]) j := j - 1 otherwise,i := i + 1 i := i + 1 return answer Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, nums, target): nums.sort() n = len(nums) answer = 10 ** 10 i, j = 0, n - 1 while i < j: if nums[i] + nums[j] > target: answer = min(answer, nums[i] + nums[j]) j -= 1 else: i += 1 return answer ob = Solution() nums = [2, 4, 6, 10, 14] target = 10 print(ob.solve(nums, target)) [2, 4, 6, 10, 14], 10 12
[ { "code": null, "e": 1212, "s": 1062, "text": "Suppose we have a list of numbers called nums and another value target. We have to find the lowest sum of pair of numbers that is larger than target." }, { "code": null, "e": 1323, "s": 1212, "text": "So, if the input is like nums = [2, 4, 6, 10, 14] target = 10, then the output will be 12, as we pick 2 and 10" }, { "code": null, "e": 1367, "s": 1323, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1386, "s": 1367, "text": "sort the list nums" }, { "code": null, "e": 1404, "s": 1386, "text": "n := size of nums" }, { "code": null, "e": 1420, "s": 1404, "text": "answer := 10^10" }, { "code": null, "e": 1439, "s": 1420, "text": "i := 0, j := n - 1" }, { "code": null, "e": 1571, "s": 1439, "text": "while i < j, doif nums[i] + nums[j] > target, thenanswer := minimum of answer and (nums[i] + nums[j])j := j - 1otherwise,i := i + 1" }, { "code": null, "e": 1668, "s": 1571, "text": "if nums[i] + nums[j] > target, thenanswer := minimum of answer and (nums[i] + nums[j])j := j - 1" }, { "code": null, "e": 1720, "s": 1668, "text": "answer := minimum of answer and (nums[i] + nums[j])" }, { "code": null, "e": 1731, "s": 1720, "text": "j := j - 1" }, { "code": null, "e": 1752, "s": 1731, "text": "otherwise,i := i + 1" }, { "code": null, "e": 1763, "s": 1752, "text": "i := i + 1" }, { "code": null, "e": 1777, "s": 1763, "text": "return answer" }, { "code": null, "e": 1847, "s": 1777, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1858, "s": 1847, "text": " Live Demo" }, { "code": null, "e": 2253, "s": 1858, "text": "class Solution:\n def solve(self, nums, target): nums.sort()\n n = len(nums)\n answer = 10 ** 10\n i, j = 0, n - 1\n while i < j:\n if nums[i] + nums[j] > target:\n answer = min(answer, nums[i] + nums[j])\n j -= 1\n else:\n i += 1\n return answer\nob = Solution()\nnums = [2, 4, 6, 10, 14]\ntarget = 10\nprint(ob.solve(nums, target))" }, { "code": null, "e": 2275, "s": 2253, "text": "[2, 4, 6, 10, 14], 10" }, { "code": null, "e": 2278, "s": 2275, "text": "12" } ]
Matplotlib.ticker.LogLocator Class in Python
21 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.ticker.LogLocator class is used to determine the tick locations for log axes. In this class the ticks are placed on the location as : subs[j]*base**i. Syntax: class matplotlib.ticker.LogLocator(base=10.0, subs=(1.0, ), numdecs=4, numticks=None) Parameter: subs: It is an optional parameter which is either None, or string or a sequence of floats. It defaults to (1.0, ). It provides the multiples of integer powers of the base at which is used to place ticks. Only at integer powers of the base the default places ticks. The auto and all are the only accepted string values here. The ticks are placed exactly between integer powers with ‘auto’ whereas with “all’ the integers power are accepted. Here None value is equivalent to ‘auto’. Methods of the class: base(self, base): This method is used for setting the base of the log scale. nonsingular(self, vmin, vmax): It is used to expand the range as required to avoid singularities. set_params(self, base=None, subs=None, numdecs=None, numticks=None): It is used to set parameters within the scale. tick_values(self, vmin, vmax): This method returns the values of the located ticks between the range of vmin and vmax. subs(self, subs): It is used to set the minor ticks for the log scaling every base**i*subs[j]. view_limit(self, vmin, vmax): This methods comes in handy while intelligently choosing the vie limits. Example 1: import matplotlib.pyplot as pltfrom matplotlib.ticker import MultipleLocator, LogLocator x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] y = [0.32, 0.30, 0.28, 0.26, 0.24, 0.22, 0.20, 0.18, 0.16, 0.14, 0.12, 0.10] fig = plt.figure()ax1 = fig.add_subplot(111) x_major = MultipleLocator(4)x_minor = MultipleLocator(1) ax1.xaxis.set_major_locator(x_major)ax1.xaxis.set_minor_locator(x_minor)ax1.set_yscale("log") y_major = LogLocator(base = 10)y_minor = LogLocator(base = 10, subs =[1.1, 1.2, 1.3]) ax1.yaxis.set_major_locator(y_major)ax1.yaxis.set_minor_locator(y_minor) ax1.plot(x, y) plt.show() Output: Example 2: import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import LogLocator x = np.linspace(0, 10, 10)y = 2**x f = plt.figure()ax = f.add_subplot(111)plt.yscale('log') ax.yaxis.set_major_locator(LogLocator(base = 100)) ax.plot(x, y) plt.show() Output: Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 240, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 406, "s": 240, "text": "The matplotlib.ticker.LogLocator class is used to determine the tick locations for log axes. In this class the ticks are placed on the location as : subs[j]*base**i." }, { "code": null, "e": 500, "s": 406, "text": "Syntax: class matplotlib.ticker.LogLocator(base=10.0, subs=(1.0, ), numdecs=4, numticks=None)" }, { "code": null, "e": 511, "s": 500, "text": "Parameter:" }, { "code": null, "e": 992, "s": 511, "text": "subs: It is an optional parameter which is either None, or string or a sequence of floats. It defaults to (1.0, ). It provides the multiples of integer powers of the base at which is used to place ticks. Only at integer powers of the base the default places ticks. The auto and all are the only accepted string values here. The ticks are placed exactly between integer powers with ‘auto’ whereas with “all’ the integers power are accepted. Here None value is equivalent to ‘auto’." }, { "code": null, "e": 1014, "s": 992, "text": "Methods of the class:" }, { "code": null, "e": 1091, "s": 1014, "text": "base(self, base): This method is used for setting the base of the log scale." }, { "code": null, "e": 1189, "s": 1091, "text": "nonsingular(self, vmin, vmax): It is used to expand the range as required to avoid singularities." }, { "code": null, "e": 1305, "s": 1189, "text": "set_params(self, base=None, subs=None, numdecs=None, numticks=None): It is used to set parameters within the scale." }, { "code": null, "e": 1424, "s": 1305, "text": "tick_values(self, vmin, vmax): This method returns the values of the located ticks between the range of vmin and vmax." }, { "code": null, "e": 1519, "s": 1424, "text": "subs(self, subs): It is used to set the minor ticks for the log scaling every base**i*subs[j]." }, { "code": null, "e": 1622, "s": 1519, "text": "view_limit(self, vmin, vmax): This methods comes in handy while intelligently choosing the vie limits." }, { "code": null, "e": 1633, "s": 1622, "text": "Example 1:" }, { "code": "import matplotlib.pyplot as pltfrom matplotlib.ticker import MultipleLocator, LogLocator x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] y = [0.32, 0.30, 0.28, 0.26, 0.24, 0.22, 0.20, 0.18, 0.16, 0.14, 0.12, 0.10] fig = plt.figure()ax1 = fig.add_subplot(111) x_major = MultipleLocator(4)x_minor = MultipleLocator(1) ax1.xaxis.set_major_locator(x_major)ax1.xaxis.set_minor_locator(x_minor)ax1.set_yscale(\"log\") y_major = LogLocator(base = 10)y_minor = LogLocator(base = 10, subs =[1.1, 1.2, 1.3]) ax1.yaxis.set_major_locator(y_major)ax1.yaxis.set_minor_locator(y_minor) ax1.plot(x, y) plt.show()", "e": 2245, "s": 1633, "text": null }, { "code": null, "e": 2253, "s": 2245, "text": "Output:" }, { "code": null, "e": 2264, "s": 2253, "text": "Example 2:" }, { "code": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import LogLocator x = np.linspace(0, 10, 10)y = 2**x f = plt.figure()ax = f.add_subplot(111)plt.yscale('log') ax.yaxis.set_major_locator(LogLocator(base = 100)) ax.plot(x, y) plt.show()", "e": 2529, "s": 2264, "text": null }, { "code": null, "e": 2537, "s": 2529, "text": "Output:" }, { "code": null, "e": 2555, "s": 2537, "text": "Python-matplotlib" }, { "code": null, "e": 2562, "s": 2555, "text": "Python" }, { "code": null, "e": 2578, "s": 2562, "text": "Write From Home" } ]
Matplotlib.axes.Axes.plot() in Python
12 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.Example: import datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np date1 = datetime.datetime(2000, 3, 2)date2 = datetime.datetime(2000, 3, 6)delta = datetime.timedelta(hours = 6)dates = drange(date1, date2, delta) y = np.arange(len(dates)) fig, ax = plt.subplots()ax.plot_date(dates, y ** 2) ax.set_xlim(dates[0], dates[-1]) ax.xaxis.set_major_locator(DayLocator())ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))ax.xaxis.set_major_formatter(DateFormatter('% Y-% m-% d')) ax.fmt_xdata = DateFormatter('% Y-% m-% d % H:% M:% S')fig.autofmt_xdate() plt.title("Matplotlib Axes Class Example")plt.show() Output: The Axes.plot() function in axes module of matplotlib library is used to plot y versus x as lines and/or markers. Syntax: Axes.plot(self, *args, scalex=True, scaley=True, data=None, **kwargs) Parameters: This method accept the following parameters that are described below: x, y: These parameter are the horizontal and vertical coordinates of the data points. x values are optional. fmt: This parameter is an optional parameter and it contains the string value. data: This parameter is an optional parameter and it is an object with labelled data. Returns: This returns the following: lines:This returns the list of Line2D objects representing the plotted data. Below examples illustrate the matplotlib.axes.Axes.plot() function in matplotlib.axes: Example #1: # Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np # make an agg figurefig, ax = plt.subplots()ax.plot([1, 2, 3])ax.set_title('matplotlib.axes.Axes.plot() example 1')fig.canvas.draw()plt.show() Output: Example #2: # Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np # Fixing random state for reproducibilitynp.random.seed(19680801) # create random dataxdata = np.random.random([2, 10]) # split the data into two partsxdata1 = xdata[0, :]xdata2 = xdata[1, :] # sort the data so it makes clean curvesxdata1.sort()xdata2.sort() # create some y data pointsydata1 = xdata1 ** 2ydata2 = 1 - xdata2 ** 3 # plot the datafig = plt.figure()ax = fig.add_subplot(1, 1, 1)ax.plot(xdata1, ydata1, color ='tab:blue')ax.plot(xdata2, ydata2, color ='tab:orange') # set the limitsax.set_xlim([0, 1])ax.set_ylim([0, 1]) ax.set_title('matplotlib.axes.Axes.plot() example 2') # display the plotplt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2020" }, { "code": null, "e": 126, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library." }, { "code": null, "e": 336, "s": 126, "text": "The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.Example:" }, { "code": "import datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np date1 = datetime.datetime(2000, 3, 2)date2 = datetime.datetime(2000, 3, 6)delta = datetime.timedelta(hours = 6)dates = drange(date1, date2, delta) y = np.arange(len(dates)) fig, ax = plt.subplots()ax.plot_date(dates, y ** 2) ax.set_xlim(dates[0], dates[-1]) ax.xaxis.set_major_locator(DayLocator())ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))ax.xaxis.set_major_formatter(DateFormatter('% Y-% m-% d')) ax.fmt_xdata = DateFormatter('% Y-% m-% d % H:% M:% S')fig.autofmt_xdate() plt.title(\"Matplotlib Axes Class Example\")plt.show()", "e": 1024, "s": 336, "text": null }, { "code": null, "e": 1032, "s": 1024, "text": "Output:" }, { "code": null, "e": 1146, "s": 1032, "text": "The Axes.plot() function in axes module of matplotlib library is used to plot y versus x as lines and/or markers." }, { "code": null, "e": 1224, "s": 1146, "text": "Syntax: Axes.plot(self, *args, scalex=True, scaley=True, data=None, **kwargs)" }, { "code": null, "e": 1306, "s": 1224, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 1415, "s": 1306, "text": "x, y: These parameter are the horizontal and vertical coordinates of the data points. x values are optional." }, { "code": null, "e": 1494, "s": 1415, "text": "fmt: This parameter is an optional parameter and it contains the string value." }, { "code": null, "e": 1580, "s": 1494, "text": "data: This parameter is an optional parameter and it is an object with labelled data." }, { "code": null, "e": 1617, "s": 1580, "text": "Returns: This returns the following:" }, { "code": null, "e": 1694, "s": 1617, "text": "lines:This returns the list of Line2D objects representing the plotted data." }, { "code": null, "e": 1781, "s": 1694, "text": "Below examples illustrate the matplotlib.axes.Axes.plot() function in matplotlib.axes:" }, { "code": null, "e": 1793, "s": 1781, "text": "Example #1:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np # make an agg figurefig, ax = plt.subplots()ax.plot([1, 2, 3])ax.set_title('matplotlib.axes.Axes.plot() example 1')fig.canvas.draw()plt.show()", "e": 2030, "s": 1793, "text": null }, { "code": null, "e": 2038, "s": 2030, "text": "Output:" }, { "code": null, "e": 2050, "s": 2038, "text": "Example #2:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np # Fixing random state for reproducibilitynp.random.seed(19680801) # create random dataxdata = np.random.random([2, 10]) # split the data into two partsxdata1 = xdata[0, :]xdata2 = xdata[1, :] # sort the data so it makes clean curvesxdata1.sort()xdata2.sort() # create some y data pointsydata1 = xdata1 ** 2ydata2 = 1 - xdata2 ** 3 # plot the datafig = plt.figure()ax = fig.add_subplot(1, 1, 1)ax.plot(xdata1, ydata1, color ='tab:blue')ax.plot(xdata2, ydata2, color ='tab:orange') # set the limitsax.set_xlim([0, 1])ax.set_ylim([0, 1]) ax.set_title('matplotlib.axes.Axes.plot() example 2') # display the plotplt.show()", "e": 2770, "s": 2050, "text": null }, { "code": null, "e": 2778, "s": 2770, "text": "Output:" }, { "code": null, "e": 2796, "s": 2778, "text": "Python-matplotlib" }, { "code": null, "e": 2803, "s": 2796, "text": "Python" } ]
Number of ways to form a heap with n distinct integers
09 Jul, 2021 Given n, how many distinct Max Heap can be made from n distinct integers?Examples: Input : n = 3 Output : Assume the integers are 1, 2, 3. Then the 2 possible max heaps are: 3 / \ 1 2 3 / \ 2 1 Input : n = 4 Output : Assume the integers are 1, 2, 3, 4. Then the 3 possible max heaps are: 4 / \ 3 2 / 1 4 / \ 2 3 / 1 4 / \ 3 1 / 2 Since there is only one element as the root, it must be the largest number. Now we have n-1 remaining elements. The main observation here is that because of the max heap properties, the structure of the heap nodes will remain the same in all instances, but only the values in the nodes will change. Assume there are l elements in the left sub-tree and r elements in the right sub-tree. Now for the root, l + r = n-1. From this we can see that we can choose any l of the remaining n-1 elements for the left sub-tree as they are all smaller than the root. We know the there are ways to do this. Next for each instance of these, we can have many heaps with l elements and for each of those we can have many heaps with r elements. Thus we can consider them as subproblems and recur for the final answer as: T(n) = * T(L) * T(R).Now we have to find the values for l and r for a given n. We know that the height of the heap h = . Also the maximum number of elements that can be present in the h th level of any heap, m = , where the root is at the 0th level. Moreover the number of elements actually present in the last level of the heap p = n – (– 1). (since number of nodes present till the penultimate level). Thus, there can be two cases: when the last level is more than or equal to half-filled: l = – 1, if p >= m / 2 (or) the last level is less than half-filled: l = – 1 – ((m / 2) – p), if p < m / 2 (we get – 1 here because left subtree has nodes. From this we can also say that r = n – l – 1.We can use the dynamic programming approach discussed in this post here to find the values of . Similarly if we look at the recursion tree for the optimal substructure recurrence formed above, we can see that it also has overlapping subproblems property, hence can be solved using dynamic programming: T(7) / \ T(3) T(3) / \ / \ T(1) T(1) T(1) T(1) Following is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program to count max heaps with n distinct keys#include <iostream>using namespace std; #define MAXN 105 // maximum value of n here // dp[i] = number of max heaps for i distinct integersint dp[MAXN]; // nck[i][j] = number of ways to choose j elements// form i elements, no order */int nck[MAXN][MAXN]; // log2[i] = floor of logarithm of base 2 of iint log2[MAXN]; // to calculate nCkint choose(int n, int k){ if (k > n) return 0; if (n <= 1) return 1; if (k == 0) return 1; if (nck[n][k] != -1) return nck[n][k]; int answer = choose(n - 1, k - 1) + choose(n - 1, k); nck[n][k] = answer; return answer;} // calculate l for give value of nint getLeft(int n){ if (n == 1) return 0; int h = log2[n]; // max number of elements that can be present in the // hth level of any heap int numh = (1 << h); //(2 ^ h) // number of elements that are actually present in // last level(hth level) // (2^h - 1) int last = n - ((1 << h) - 1); // if more than half-filled if (last >= (numh / 2)) return (1 << h) - 1; // (2^h) - 1 else return (1 << h) - 1 - ((numh / 2) - last);} // find maximum number of heaps for nint numberOfHeaps(int n){ if (n <= 1) return 1; if (dp[n] != -1) return dp[n]; int left = getLeft(n); int ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)); dp[n] = ans; return ans;} // function to initialize arraysint solve(int n){ for (int i = 0; i <= n; i++) dp[i] = -1; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) nck[i][j] = -1; int currLog2 = -1; int currPower2 = 1; // for each power of two find logarithm for (int i = 1; i <= n; i++) { if (currPower2 == i) { currLog2++; currPower2 *= 2; } log2[i] = currLog2; } return numberOfHeaps(n);} // driver functionint main(){ int n = 10; cout << solve(n) << endl; return 0;} // Java program to count max heaps with n distinct keysclass GFG{ static int MAXN = 105; // maximum value of n here // dp[i] = number of max heaps for i distinct integers static int[] dp = new int[MAXN]; // nck[i][j] = number of ways to choose j elements // form i elements, no order */ static int[][] nck = new int[MAXN][MAXN]; // log2[i] = floor of logarithm of base 2 of i static int[] log2 = new int[MAXN]; // to calculate nCk public static int choose(int n, int k) { if (k > n) { return 0; } if (n <= 1) { return 1; } if (k == 0) { return 1; } if (nck[n][k] != -1) { return nck[n][k]; } int answer = choose(n - 1, k - 1) + choose(n - 1, k); nck[n][k] = answer; return answer; } // calculate l for give value of n public static int getLeft(int n) { if (n == 1) { return 0; } int h = log2[n]; // max number of elements that can be present in the // hth level of any heap int numh = (1 << h); //(2 ^ h) // number of elements that are actually present in // last level(hth level) // (2^h - 1) int last = n - ((1 << h) - 1); // if more than half-filled if (last >= (numh / 2)) { return (1 << h) - 1; // (2^h) - 1 } else { return (1 << h) - 1 - ((numh / 2) - last); } } // find maximum number of heaps for n public static int numberOfHeaps(int n) { if (n <= 1) { return 1; } if (dp[n] != -1) { return dp[n]; } int left = getLeft(n); int ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)); dp[n] = ans; return ans; } // function to initialize arrays public static int solve(int n) { for (int i = 0; i <= n; i++) { dp[i] = -1; } for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { nck[i][j] = -1; } } int currLog2 = -1; int currPower2 = 1; // for each power of two find logarithm for (int i = 1; i <= n; i++) { if (currPower2 == i) { currLog2++; currPower2 *= 2; } log2[i] = currLog2; } return numberOfHeaps(n); } // Driver code public static void main(String[] args) { int n = 10; System.out.print(solve(n)); }} // This code has been contributed by 29AjayKumar # Python program to count max heaps with n distinct keys MAXN = 105 # maximum value of n here # dp[i] = number of max heaps for i distinct integersdp = [0]*MAXN # nck[i][j] = number of ways to choose j elements# form i elements, no order */nck = [[0 for i in range(MAXN)] for j in range(MAXN)] # log2[i] = floor of logarithm of base 2 of ilog2 = [0]*MAXN # to calculate nCkdef choose(n, k): if (k > n): return 0 if (n <= 1): return 1 if (k == 0): return 1 if (nck[n][k] != -1): return nck[n][k] answer = choose(n - 1, k - 1) + choose(n - 1, k) nck[n][k] = answer return answer # calculate l for give value of ndef getLeft(n): if (n == 1): return 0 h = log2[n] # max number of elements that can be present in the # hth level of any heap numh = (1 << h) #(2 ^ h) # number of elements that are actually present in # last level(hth level) # (2^h - 1) last = n - ((1 << h) - 1) # if more than half-filled if (last >= (numh // 2)): return (1 << h) - 1 # (2^h) - 1 else: return (1 << h) - 1 - ((numh // 2) - last) # find maximum number of heaps for ndef numberOfHeaps(n): if (n <= 1): return 1 if (dp[n] != -1): return dp[n] left = getLeft(n) ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)) dp[n] = ans return ans # function to initialize arraysdef solve(n): for i in range(n+1): dp[i] = -1 for i in range(n+1): for j in range(n+1): nck[i][j] = -1 currLog2 = -1 currPower2 = 1 # for each power of two find logarithm for i in range(1,n+1): if (currPower2 == i): currLog2 += 1 currPower2 *= 2 log2[i] = currLog2 return numberOfHeaps(n) # Driver coden = 10print(solve(n)) # This code is contributed by ankush_953 // C# program to count max heaps with n distinct keysusing System; class GFG{ static int MAXN = 105; // maximum value of n here // dp[i] = number of max heaps for i distinct integers static int[] dp = new int[MAXN]; // nck[i][j] = number of ways to choose j elements // form i elements, no order */ static int[,] nck = new int[MAXN,MAXN]; // log2[i] = floor of logarithm of base 2 of i static int[] log2 = new int[MAXN]; // to calculate nCk public static int choose(int n, int k) { if (k > n) return 0; if (n <= 1) return 1; if (k == 0) return 1; if (nck[n,k] != -1) return nck[n,k]; int answer = choose(n - 1, k - 1) + choose(n - 1, k); nck[n,k] = answer; return answer; } // calculate l for give value of n public static int getLeft(int n) { if (n == 1) return 0; int h = log2[n]; // max number of elements that can be present in the // hth level of any heap int numh = (1 << h); //(2 ^ h) // number of elements that are actually present in // last level(hth level) // (2^h - 1) int last = n - ((1 << h) - 1); // if more than half-filled if (last >= (numh / 2)) return (1 << h) - 1; // (2^h) - 1 else return (1 << h) - 1 - ((numh / 2) - last); } // find maximum number of heaps for n public static int numberOfHeaps(int n) { if (n <= 1) return 1; if (dp[n] != -1) return dp[n]; int left = getLeft(n); int ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)); dp[n] = ans; return ans; } // function to initialize arrays public static int solve(int n) { for (int i = 0; i <= n; i++) dp[i] = -1; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) nck[i,j] = -1; int currLog2 = -1; int currPower2 = 1; // for each power of two find logarithm for (int i = 1; i <= n; i++) { if (currPower2 == i) { currLog2++; currPower2 *= 2; } log2[i] = currLog2; } return numberOfHeaps(n); } // driver function static void Main() { int n = 10; Console.Write(solve(n)); } //This code is contributed by DrRoot_} <script> // JavaScript program to count max heaps with n distinct keys let MAXN = 105; // maximum value of n here // dp[i] = number of max heaps for i distinct integerslet dp = new Array(MAXN); // nck[i][j] = number of ways to choose j elements // form i elements, no order */let nck = new Array(MAXN);for(let i=0;i<MAXN;i++){ nck[i]=new Array(MAXN); for(let j=0;j<MAXN;j++) nck[i][j]=0;} // log2[i] = floor of logarithm of base 2 of ilet log2 = new Array(MAXN); // to calculate nCkfunction choose(n,k){ if (k > n) { return 0; } if (n <= 1) { return 1; } if (k == 0) { return 1; } if (nck[n][k] != -1) { return nck[n][k]; } let answer = choose(n - 1, k - 1) + choose(n - 1, k); nck[n][k] = answer; return answer;} // calculate l for give value of nfunction getLeft(n){ if (n == 1) { return 0; } let h = log2[n]; // max number of elements that can be present in the // hth level of any heap let numh = (1 << h); //(2 ^ h) // number of elements that are actually present in // last level(hth level) // (2^h - 1) let last = n - ((1 << h) - 1); // if more than half-filled if (last >= (numh / 2)) { return (1 << h) - 1; // (2^h) - 1 } else { return (1 << h) - 1 - ((numh / 2) - last); }} // find maximum number of heaps for nfunction numberOfHeaps(n){ if (n <= 1) { return 1; } if (dp[n] != -1) { return dp[n]; } let left = getLeft(n); let ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)); dp[n] = ans; return ans;} // function to initialize arraysfunction solve(n){ for (let i = 0; i <= n; i++) { dp[i] = -1; } for (let i = 0; i <= n; i++) { for (let j = 0; j <= n; j++) { nck[i][j] = -1; } } let currLog2 = -1; let currPower2 = 1; // for each power of two find logarithm for (let i = 1; i <= n; i++) { if (currPower2 == i) { currLog2++; currPower2 *= 2; } log2[i] = currLog2; } return numberOfHeaps(n);} // Driver codelet n = 10;document.write(solve(n)); // This code is contributed by rag2127 </script> Output: 3360 rsatish1110 DrRoot_ 29AjayKumar ankush_953 rag2127 Directi Combinatorial Dynamic Programming Heap Directi Dynamic Programming Combinatorial Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jul, 2021" }, { "code": null, "e": 139, "s": 54, "text": "Given n, how many distinct Max Heap can be made from n distinct integers?Examples: " }, { "code": null, "e": 572, "s": 139, "text": "Input : n = 3\nOutput : Assume the integers are 1, 2, 3.\nThen the 2 possible max heaps are: \n 3\n / \\\n 1 2\n\n 3\n / \\\n 2 1\n\nInput : n = 4\nOutput : Assume the integers are 1, 2, 3, 4.\nThen the 3 possible max heaps are:\n 4 \n / \\ \n 3 2 \n / \n 1\n\n 4 \n / \\ \n 2 3 \n / \n 1\n\n 4 \n / \\ \n 3 1 \n / \n 2" }, { "code": null, "e": 2374, "s": 574, "text": "Since there is only one element as the root, it must be the largest number. Now we have n-1 remaining elements. The main observation here is that because of the max heap properties, the structure of the heap nodes will remain the same in all instances, but only the values in the nodes will change. Assume there are l elements in the left sub-tree and r elements in the right sub-tree. Now for the root, l + r = n-1. From this we can see that we can choose any l of the remaining n-1 elements for the left sub-tree as they are all smaller than the root. We know the there are ways to do this. Next for each instance of these, we can have many heaps with l elements and for each of those we can have many heaps with r elements. Thus we can consider them as subproblems and recur for the final answer as: T(n) = * T(L) * T(R).Now we have to find the values for l and r for a given n. We know that the height of the heap h = . Also the maximum number of elements that can be present in the h th level of any heap, m = , where the root is at the 0th level. Moreover the number of elements actually present in the last level of the heap p = n – (– 1). (since number of nodes present till the penultimate level). Thus, there can be two cases: when the last level is more than or equal to half-filled: l = – 1, if p >= m / 2 (or) the last level is less than half-filled: l = – 1 – ((m / 2) – p), if p < m / 2 (we get – 1 here because left subtree has nodes. From this we can also say that r = n – l – 1.We can use the dynamic programming approach discussed in this post here to find the values of . Similarly if we look at the recursion tree for the optimal substructure recurrence formed above, we can see that it also has overlapping subproblems property, hence can be solved using dynamic programming: " }, { "code": null, "e": 2487, "s": 2374, "text": " T(7)\n / \\\n T(3) T(3)\n / \\ / \\ \n T(1) T(1) T(1) T(1) " }, { "code": null, "e": 2544, "s": 2487, "text": "Following is the implementation of the above approach: " }, { "code": null, "e": 2548, "s": 2544, "text": "C++" }, { "code": null, "e": 2553, "s": 2548, "text": "Java" }, { "code": null, "e": 2561, "s": 2553, "text": "Python3" }, { "code": null, "e": 2564, "s": 2561, "text": "C#" }, { "code": null, "e": 2575, "s": 2564, "text": "Javascript" }, { "code": "// CPP program to count max heaps with n distinct keys#include <iostream>using namespace std; #define MAXN 105 // maximum value of n here // dp[i] = number of max heaps for i distinct integersint dp[MAXN]; // nck[i][j] = number of ways to choose j elements// form i elements, no order */int nck[MAXN][MAXN]; // log2[i] = floor of logarithm of base 2 of iint log2[MAXN]; // to calculate nCkint choose(int n, int k){ if (k > n) return 0; if (n <= 1) return 1; if (k == 0) return 1; if (nck[n][k] != -1) return nck[n][k]; int answer = choose(n - 1, k - 1) + choose(n - 1, k); nck[n][k] = answer; return answer;} // calculate l for give value of nint getLeft(int n){ if (n == 1) return 0; int h = log2[n]; // max number of elements that can be present in the // hth level of any heap int numh = (1 << h); //(2 ^ h) // number of elements that are actually present in // last level(hth level) // (2^h - 1) int last = n - ((1 << h) - 1); // if more than half-filled if (last >= (numh / 2)) return (1 << h) - 1; // (2^h) - 1 else return (1 << h) - 1 - ((numh / 2) - last);} // find maximum number of heaps for nint numberOfHeaps(int n){ if (n <= 1) return 1; if (dp[n] != -1) return dp[n]; int left = getLeft(n); int ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)); dp[n] = ans; return ans;} // function to initialize arraysint solve(int n){ for (int i = 0; i <= n; i++) dp[i] = -1; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) nck[i][j] = -1; int currLog2 = -1; int currPower2 = 1; // for each power of two find logarithm for (int i = 1; i <= n; i++) { if (currPower2 == i) { currLog2++; currPower2 *= 2; } log2[i] = currLog2; } return numberOfHeaps(n);} // driver functionint main(){ int n = 10; cout << solve(n) << endl; return 0;}", "e": 4640, "s": 2575, "text": null }, { "code": "// Java program to count max heaps with n distinct keysclass GFG{ static int MAXN = 105; // maximum value of n here // dp[i] = number of max heaps for i distinct integers static int[] dp = new int[MAXN]; // nck[i][j] = number of ways to choose j elements // form i elements, no order */ static int[][] nck = new int[MAXN][MAXN]; // log2[i] = floor of logarithm of base 2 of i static int[] log2 = new int[MAXN]; // to calculate nCk public static int choose(int n, int k) { if (k > n) { return 0; } if (n <= 1) { return 1; } if (k == 0) { return 1; } if (nck[n][k] != -1) { return nck[n][k]; } int answer = choose(n - 1, k - 1) + choose(n - 1, k); nck[n][k] = answer; return answer; } // calculate l for give value of n public static int getLeft(int n) { if (n == 1) { return 0; } int h = log2[n]; // max number of elements that can be present in the // hth level of any heap int numh = (1 << h); //(2 ^ h) // number of elements that are actually present in // last level(hth level) // (2^h - 1) int last = n - ((1 << h) - 1); // if more than half-filled if (last >= (numh / 2)) { return (1 << h) - 1; // (2^h) - 1 } else { return (1 << h) - 1 - ((numh / 2) - last); } } // find maximum number of heaps for n public static int numberOfHeaps(int n) { if (n <= 1) { return 1; } if (dp[n] != -1) { return dp[n]; } int left = getLeft(n); int ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)); dp[n] = ans; return ans; } // function to initialize arrays public static int solve(int n) { for (int i = 0; i <= n; i++) { dp[i] = -1; } for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { nck[i][j] = -1; } } int currLog2 = -1; int currPower2 = 1; // for each power of two find logarithm for (int i = 1; i <= n; i++) { if (currPower2 == i) { currLog2++; currPower2 *= 2; } log2[i] = currLog2; } return numberOfHeaps(n); } // Driver code public static void main(String[] args) { int n = 10; System.out.print(solve(n)); }} // This code has been contributed by 29AjayKumar", "e": 7406, "s": 4640, "text": null }, { "code": "# Python program to count max heaps with n distinct keys MAXN = 105 # maximum value of n here # dp[i] = number of max heaps for i distinct integersdp = [0]*MAXN # nck[i][j] = number of ways to choose j elements# form i elements, no order */nck = [[0 for i in range(MAXN)] for j in range(MAXN)] # log2[i] = floor of logarithm of base 2 of ilog2 = [0]*MAXN # to calculate nCkdef choose(n, k): if (k > n): return 0 if (n <= 1): return 1 if (k == 0): return 1 if (nck[n][k] != -1): return nck[n][k] answer = choose(n - 1, k - 1) + choose(n - 1, k) nck[n][k] = answer return answer # calculate l for give value of ndef getLeft(n): if (n == 1): return 0 h = log2[n] # max number of elements that can be present in the # hth level of any heap numh = (1 << h) #(2 ^ h) # number of elements that are actually present in # last level(hth level) # (2^h - 1) last = n - ((1 << h) - 1) # if more than half-filled if (last >= (numh // 2)): return (1 << h) - 1 # (2^h) - 1 else: return (1 << h) - 1 - ((numh // 2) - last) # find maximum number of heaps for ndef numberOfHeaps(n): if (n <= 1): return 1 if (dp[n] != -1): return dp[n] left = getLeft(n) ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)) dp[n] = ans return ans # function to initialize arraysdef solve(n): for i in range(n+1): dp[i] = -1 for i in range(n+1): for j in range(n+1): nck[i][j] = -1 currLog2 = -1 currPower2 = 1 # for each power of two find logarithm for i in range(1,n+1): if (currPower2 == i): currLog2 += 1 currPower2 *= 2 log2[i] = currLog2 return numberOfHeaps(n) # Driver coden = 10print(solve(n)) # This code is contributed by ankush_953", "e": 9290, "s": 7406, "text": null }, { "code": "// C# program to count max heaps with n distinct keysusing System; class GFG{ static int MAXN = 105; // maximum value of n here // dp[i] = number of max heaps for i distinct integers static int[] dp = new int[MAXN]; // nck[i][j] = number of ways to choose j elements // form i elements, no order */ static int[,] nck = new int[MAXN,MAXN]; // log2[i] = floor of logarithm of base 2 of i static int[] log2 = new int[MAXN]; // to calculate nCk public static int choose(int n, int k) { if (k > n) return 0; if (n <= 1) return 1; if (k == 0) return 1; if (nck[n,k] != -1) return nck[n,k]; int answer = choose(n - 1, k - 1) + choose(n - 1, k); nck[n,k] = answer; return answer; } // calculate l for give value of n public static int getLeft(int n) { if (n == 1) return 0; int h = log2[n]; // max number of elements that can be present in the // hth level of any heap int numh = (1 << h); //(2 ^ h) // number of elements that are actually present in // last level(hth level) // (2^h - 1) int last = n - ((1 << h) - 1); // if more than half-filled if (last >= (numh / 2)) return (1 << h) - 1; // (2^h) - 1 else return (1 << h) - 1 - ((numh / 2) - last); } // find maximum number of heaps for n public static int numberOfHeaps(int n) { if (n <= 1) return 1; if (dp[n] != -1) return dp[n]; int left = getLeft(n); int ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)); dp[n] = ans; return ans; } // function to initialize arrays public static int solve(int n) { for (int i = 0; i <= n; i++) dp[i] = -1; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) nck[i,j] = -1; int currLog2 = -1; int currPower2 = 1; // for each power of two find logarithm for (int i = 1; i <= n; i++) { if (currPower2 == i) { currLog2++; currPower2 *= 2; } log2[i] = currLog2; } return numberOfHeaps(n); } // driver function static void Main() { int n = 10; Console.Write(solve(n)); } //This code is contributed by DrRoot_}", "e": 11940, "s": 9290, "text": null }, { "code": "<script> // JavaScript program to count max heaps with n distinct keys let MAXN = 105; // maximum value of n here // dp[i] = number of max heaps for i distinct integerslet dp = new Array(MAXN); // nck[i][j] = number of ways to choose j elements // form i elements, no order */let nck = new Array(MAXN);for(let i=0;i<MAXN;i++){ nck[i]=new Array(MAXN); for(let j=0;j<MAXN;j++) nck[i][j]=0;} // log2[i] = floor of logarithm of base 2 of ilet log2 = new Array(MAXN); // to calculate nCkfunction choose(n,k){ if (k > n) { return 0; } if (n <= 1) { return 1; } if (k == 0) { return 1; } if (nck[n][k] != -1) { return nck[n][k]; } let answer = choose(n - 1, k - 1) + choose(n - 1, k); nck[n][k] = answer; return answer;} // calculate l for give value of nfunction getLeft(n){ if (n == 1) { return 0; } let h = log2[n]; // max number of elements that can be present in the // hth level of any heap let numh = (1 << h); //(2 ^ h) // number of elements that are actually present in // last level(hth level) // (2^h - 1) let last = n - ((1 << h) - 1); // if more than half-filled if (last >= (numh / 2)) { return (1 << h) - 1; // (2^h) - 1 } else { return (1 << h) - 1 - ((numh / 2) - last); }} // find maximum number of heaps for nfunction numberOfHeaps(n){ if (n <= 1) { return 1; } if (dp[n] != -1) { return dp[n]; } let left = getLeft(n); let ans = (choose(n - 1, left) * numberOfHeaps(left)) * (numberOfHeaps(n - 1 - left)); dp[n] = ans; return ans;} // function to initialize arraysfunction solve(n){ for (let i = 0; i <= n; i++) { dp[i] = -1; } for (let i = 0; i <= n; i++) { for (let j = 0; j <= n; j++) { nck[i][j] = -1; } } let currLog2 = -1; let currPower2 = 1; // for each power of two find logarithm for (let i = 1; i <= n; i++) { if (currPower2 == i) { currLog2++; currPower2 *= 2; } log2[i] = currLog2; } return numberOfHeaps(n);} // Driver codelet n = 10;document.write(solve(n)); // This code is contributed by rag2127 </script>", "e": 14560, "s": 11940, "text": null }, { "code": null, "e": 14570, "s": 14560, "text": "Output: " }, { "code": null, "e": 14575, "s": 14570, "text": "3360" }, { "code": null, "e": 14589, "s": 14577, "text": "rsatish1110" }, { "code": null, "e": 14597, "s": 14589, "text": "DrRoot_" }, { "code": null, "e": 14609, "s": 14597, "text": "29AjayKumar" }, { "code": null, "e": 14620, "s": 14609, "text": "ankush_953" }, { "code": null, "e": 14628, "s": 14620, "text": "rag2127" }, { "code": null, "e": 14636, "s": 14628, "text": "Directi" }, { "code": null, "e": 14650, "s": 14636, "text": "Combinatorial" }, { "code": null, "e": 14670, "s": 14650, "text": "Dynamic Programming" }, { "code": null, "e": 14675, "s": 14670, "text": "Heap" }, { "code": null, "e": 14683, "s": 14675, "text": "Directi" }, { "code": null, "e": 14703, "s": 14683, "text": "Dynamic Programming" }, { "code": null, "e": 14717, "s": 14703, "text": "Combinatorial" }, { "code": null, "e": 14722, "s": 14717, "text": "Heap" } ]
How to remove random symbols in a dataframe in Pandas?
30 Jun, 2021 In this article, we will see how to remove random symbols in a dataframe in Pandas. Method 1: Selecting columns Syntax: dataframe[columns].replace({symbol:},regex=True) First, select the columns which have a symbol that needs to be removed. And inside the method replace() insert the symbol example replace(“h”:””) Python3 import pandas as pd df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': ['f;', 'd:', 'sda;sd'], 'D': ['s', 'd;', 'd;p'], 'E': [5, 3, 6], 'F': [7, 4, 3]}) print(df) cols_to_check = ['C', 'D', 'E']print(df[cols_to_check]) df[cols_to_check] = df[cols_to_check].replace({';': ''}, regex=True)print(df) Output: Method 2: Using dataframe.iloc Syntax: dataframe.iloc[].replace({character},regex=True) In this method, you use dataframe.iloc[] to change the symbols. Python3 import pandas as pd df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': ['f;', 'd:', 'sda;sd'], 'D': ['s', 'd;', 'd;p'], 'E': [5, 3, 6], 'F': [7, 4, 3]}) print(df) cols_to_check = ['C', 'D', 'E']print(df.iloc[[0, 2]]) df.iloc[[0, 2]] = df.iloc[[0, 2]].replace({';': ''}, regex=True)print(df) Output: Method 3: Using dataframe.loc[] Syntax: dataframe.loc[].replace({character},regex=True) Python3 import pandas as pd df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': ['f;', 'd:', 'sda;sd'], 'D': ['s', 'd;', 'd;p'], 'E': [5, 3, 6], 'F': [7, 4, 3]}) print(df) cols_to_check = ['C', 'D', 'E']print(df.loc[:, cols_to_check]) df.loc[:, cols_to_check] = df.loc[ :, cols_to_check].replace({';': ''}, regex=True)print(df) Output: anikakapoor Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 112, "s": 28, "text": "In this article, we will see how to remove random symbols in a dataframe in Pandas." }, { "code": null, "e": 140, "s": 112, "text": "Method 1: Selecting columns" }, { "code": null, "e": 197, "s": 140, "text": "Syntax: dataframe[columns].replace({symbol:},regex=True)" }, { "code": null, "e": 343, "s": 197, "text": "First, select the columns which have a symbol that needs to be removed. And inside the method replace() insert the symbol example replace(“h”:””)" }, { "code": null, "e": 351, "s": 343, "text": "Python3" }, { "code": "import pandas as pd df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': ['f;', 'd:', 'sda;sd'], 'D': ['s', 'd;', 'd;p'], 'E': [5, 3, 6], 'F': [7, 4, 3]}) print(df) cols_to_check = ['C', 'D', 'E']print(df[cols_to_check]) df[cols_to_check] = df[cols_to_check].replace({';': ''}, regex=True)print(df)", "e": 744, "s": 351, "text": null }, { "code": null, "e": 752, "s": 744, "text": "Output:" }, { "code": null, "e": 783, "s": 752, "text": "Method 2: Using dataframe.iloc" }, { "code": null, "e": 791, "s": 783, "text": "Syntax:" }, { "code": null, "e": 840, "s": 791, "text": "dataframe.iloc[].replace({character},regex=True)" }, { "code": null, "e": 904, "s": 840, "text": "In this method, you use dataframe.iloc[] to change the symbols." }, { "code": null, "e": 912, "s": 904, "text": "Python3" }, { "code": "import pandas as pd df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': ['f;', 'd:', 'sda;sd'], 'D': ['s', 'd;', 'd;p'], 'E': [5, 3, 6], 'F': [7, 4, 3]}) print(df) cols_to_check = ['C', 'D', 'E']print(df.iloc[[0, 2]]) df.iloc[[0, 2]] = df.iloc[[0, 2]].replace({';': ''}, regex=True)print(df)", "e": 1298, "s": 912, "text": null }, { "code": null, "e": 1306, "s": 1298, "text": "Output:" }, { "code": null, "e": 1338, "s": 1306, "text": "Method 3: Using dataframe.loc[]" }, { "code": null, "e": 1346, "s": 1338, "text": "Syntax:" }, { "code": null, "e": 1394, "s": 1346, "text": "dataframe.loc[].replace({character},regex=True)" }, { "code": null, "e": 1402, "s": 1394, "text": "Python3" }, { "code": "import pandas as pd df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': ['f;', 'd:', 'sda;sd'], 'D': ['s', 'd;', 'd;p'], 'E': [5, 3, 6], 'F': [7, 4, 3]}) print(df) cols_to_check = ['C', 'D', 'E']print(df.loc[:, cols_to_check]) df.loc[:, cols_to_check] = df.loc[ :, cols_to_check].replace({';': ''}, regex=True)print(df)", "e": 1819, "s": 1402, "text": null }, { "code": null, "e": 1827, "s": 1819, "text": "Output:" }, { "code": null, "e": 1839, "s": 1827, "text": "anikakapoor" }, { "code": null, "e": 1846, "s": 1839, "text": "Picked" }, { "code": null, "e": 1870, "s": 1846, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1893, "s": 1870, "text": "Python Pandas-exercise" }, { "code": null, "e": 1907, "s": 1893, "text": "Python-pandas" }, { "code": null, "e": 1914, "s": 1907, "text": "Python" } ]
PHP | json_decode() Function
09 May, 2019 The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable. Syntax: json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 ) Parameters: This function accepts four parameters as mentioned above and described below: json: It holds the JSON string which need to be decode. It only works with UTF-8 encoded strings. assoc: It is a boolean variable. If it is true then objects returned will be converted into associative arrays. depth: It states the recursion depth specified by user. options: It includes bitmask of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING,, JSON_THROW_ON_ERROR. Return values: This function returns the encoded JSON value in appropriate PHP type. If the json cannot be decoded or if the encoded data is deeper than the recursion limit then it returns NULL. Below examples illustrate the use of json_decode() function in PHP:Example 1: <?php // Declare a json string$json = '{"g":7, "e":5, "e":5, "k":11, "s":19}'; // Use json_decode() function to// decode a stringvar_dump(json_decode($json)); var_dump(json_decode($json, true)); ?> object(stdClass)#1 (4) { ["g"]=> int(7) ["e"]=> int(5) ["k"]=> int(11) ["s"]=> int(19) } array(4) { ["g"]=> int(7) ["e"]=> int(5) ["k"]=> int(11) ["s"]=> int(19) } Example 2: <?php // Declare a json string$json = '{"geeks": 7551119}'; // Use json_decode() function to// decode a string$obj = json_decode($json); // Display the value of json objectprint $obj->{'geeks'}; ?> 7551119 Common Errors while using json_decode() function: Used strings are valid JavaScript but not valid JSON. Name and value must be enclosed in double quotes, single quotes are not allowed. Trailing commas are not allowed. Reference: http://php.net/manual/en/function.json-decode.php shubham_singh PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 May, 2019" }, { "code": null, "e": 179, "s": 28, "text": "The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable." }, { "code": null, "e": 187, "s": 179, "text": "Syntax:" }, { "code": null, "e": 252, "s": 187, "text": "json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )" }, { "code": null, "e": 342, "s": 252, "text": "Parameters: This function accepts four parameters as mentioned above and described below:" }, { "code": null, "e": 440, "s": 342, "text": "json: It holds the JSON string which need to be decode. It only works with UTF-8 encoded strings." }, { "code": null, "e": 552, "s": 440, "text": "assoc: It is a boolean variable. If it is true then objects returned will be converted into associative arrays." }, { "code": null, "e": 608, "s": 552, "text": "depth: It states the recursion depth specified by user." }, { "code": null, "e": 707, "s": 608, "text": "options: It includes bitmask of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING,, JSON_THROW_ON_ERROR." }, { "code": null, "e": 902, "s": 707, "text": "Return values: This function returns the encoded JSON value in appropriate PHP type. If the json cannot be decoded or if the encoded data is deeper than the recursion limit then it returns NULL." }, { "code": null, "e": 980, "s": 902, "text": "Below examples illustrate the use of json_decode() function in PHP:Example 1:" }, { "code": "<?php // Declare a json string$json = '{\"g\":7, \"e\":5, \"e\":5, \"k\":11, \"s\":19}'; // Use json_decode() function to// decode a stringvar_dump(json_decode($json)); var_dump(json_decode($json, true)); ?>", "e": 1182, "s": 980, "text": null }, { "code": null, "e": 1379, "s": 1182, "text": "object(stdClass)#1 (4) {\n [\"g\"]=>\n int(7)\n [\"e\"]=>\n int(5)\n [\"k\"]=>\n int(11)\n [\"s\"]=>\n int(19)\n}\narray(4) {\n [\"g\"]=>\n int(7)\n [\"e\"]=>\n int(5)\n [\"k\"]=>\n int(11)\n [\"s\"]=>\n int(19)\n}\n" }, { "code": null, "e": 1390, "s": 1379, "text": "Example 2:" }, { "code": "<?php // Declare a json string$json = '{\"geeks\": 7551119}'; // Use json_decode() function to// decode a string$obj = json_decode($json); // Display the value of json objectprint $obj->{'geeks'}; ?>", "e": 1592, "s": 1390, "text": null }, { "code": null, "e": 1601, "s": 1592, "text": "7551119\n" }, { "code": null, "e": 1651, "s": 1601, "text": "Common Errors while using json_decode() function:" }, { "code": null, "e": 1705, "s": 1651, "text": "Used strings are valid JavaScript but not valid JSON." }, { "code": null, "e": 1786, "s": 1705, "text": "Name and value must be enclosed in double quotes, single quotes are not allowed." }, { "code": null, "e": 1819, "s": 1786, "text": "Trailing commas are not allowed." }, { "code": null, "e": 1880, "s": 1819, "text": "Reference: http://php.net/manual/en/function.json-decode.php" }, { "code": null, "e": 1894, "s": 1880, "text": "shubham_singh" }, { "code": null, "e": 1907, "s": 1894, "text": "PHP-function" }, { "code": null, "e": 1911, "s": 1907, "text": "PHP" }, { "code": null, "e": 1928, "s": 1911, "text": "Web Technologies" }, { "code": null, "e": 1932, "s": 1928, "text": "PHP" } ]
Node.js Timers module
08 Oct, 2021 The Timers module in Node.js contains various functions that allow us to execute a block of code or a function after a set period of time. The Timers module is global, we do not need to use require() to import it. Timers module has the following functions: Scheduling Timers: It is used to call a function after a set period of time.setImmediate()setInterval()setTimeout()Cancelling Timers: It is used to cancel the scheduled timer.clearImmediate()clearInterval()clearTimeout() Scheduling Timers: It is used to call a function after a set period of time.setImmediate()setInterval()setTimeout() setImmediate() setInterval() setTimeout() Cancelling Timers: It is used to cancel the scheduled timer.clearImmediate()clearInterval()clearTimeout() clearImmediate() clearInterval() clearTimeout() 1. setImmediate() method: It schedules the “immediate” execution of the callback after I/O events callbacks. In the following example, multiple setImmediate functions are called. Whenever we do these callback functions are queued for execution in the order in which they are created. The entire callback queue is processed after every event loop iteration. If an immediate timer is queued from inside an executing callback, that timer will not be triggered until the next event loop iteration. setImmediate(function A() { setImmediate(function B() { console.log(1); setImmediate(function D() { console.log(2); }); }); setImmediate(function C() { console.log(3); setImmediate(function E() { console.log(4); }); });}); console.log('Started...'); Output: Started... 1 3 2 4 In the above example, on the first iteration of event loop function A is fired. Then on second iteration function B is fired, and C is fired on the third iteration. Similarly functions D and E are fired on the fourth and fifth iteration respectively. 2. setInterval() method: It repeats the execution of the callback after every t time in milliseconds passed as a parameter. // Executed after every 1000 milliseconds// from the start of the programsetInterval(function A() { return console.log('Hello World!');}, 1000); // Executed right awayconsole.log('Executed before A...'); Output: Executed before A... Hello World! Hello World! Hello World! Hello World! Hello World! ... 3. setTimeout() method: It schedules the execution of the callback after a certain time in milliseconds which is passed as a parameter. // Executed after 3000 milliseconds // from the start of the programsetTimeout(function A() { return console.log('Hello World!');}, 3000); // executed right awayconsole.log('Executed before A...'); Output: Executed before A... Hello World! 4. clearImmediate() method: It is used to simply cancel the Immediate object created by setImmediate() method. var si = setImmediate(function A() { console.log(1);}); // clears setInterval siclearImmediate(si); console.log(2); Output: 2 5. clearInterval() method: It is used to cancel the Immediate object created by setInterval() method. var si = setInterval(function A() { return console.log("Hello World!");}, 500); setTimeout(function() { clearInterval(si);}, 2000); The clearInterval() clears the setInterval ‘si’ after 500 ms, then function A is executed four times. Output: Hello World! Hello World! Hello World! Hello World! 6. clearTimeout() method: It is used to cancel the Immediate object created by setTimeout() method. // si1 is cleared by clearTimeout()var si1 = setTimeout(function A() { return console.log("Hello World!");}, 3000); // only si2 is executedvar si2 = setTimeout(function B() { return console.log("Hello Geeks!");}, 3000); clearTimeout(si1); Only setInterval ‘si2’ is executed as ‘si1’ is cleared by clearTimeout() method.Output: Hello Geeks! Node.js-Basics Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Oct, 2021" }, { "code": null, "e": 266, "s": 52, "text": "The Timers module in Node.js contains various functions that allow us to execute a block of code or a function after a set period of time. The Timers module is global, we do not need to use require() to import it." }, { "code": null, "e": 309, "s": 266, "text": "Timers module has the following functions:" }, { "code": null, "e": 530, "s": 309, "text": "Scheduling Timers: It is used to call a function after a set period of time.setImmediate()setInterval()setTimeout()Cancelling Timers: It is used to cancel the scheduled timer.clearImmediate()clearInterval()clearTimeout()" }, { "code": null, "e": 646, "s": 530, "text": "Scheduling Timers: It is used to call a function after a set period of time.setImmediate()setInterval()setTimeout()" }, { "code": null, "e": 661, "s": 646, "text": "setImmediate()" }, { "code": null, "e": 675, "s": 661, "text": "setInterval()" }, { "code": null, "e": 688, "s": 675, "text": "setTimeout()" }, { "code": null, "e": 794, "s": 688, "text": "Cancelling Timers: It is used to cancel the scheduled timer.clearImmediate()clearInterval()clearTimeout()" }, { "code": null, "e": 811, "s": 794, "text": "clearImmediate()" }, { "code": null, "e": 827, "s": 811, "text": "clearInterval()" }, { "code": null, "e": 842, "s": 827, "text": "clearTimeout()" }, { "code": null, "e": 1336, "s": 842, "text": "1. setImmediate() method: It schedules the “immediate” execution of the callback after I/O events callbacks. In the following example, multiple setImmediate functions are called. Whenever we do these callback functions are queued for execution in the order in which they are created. The entire callback queue is processed after every event loop iteration. If an immediate timer is queued from inside an executing callback, that timer will not be triggered until the next event loop iteration." }, { "code": "setImmediate(function A() { setImmediate(function B() { console.log(1); setImmediate(function D() { console.log(2); }); }); setImmediate(function C() { console.log(3); setImmediate(function E() { console.log(4); }); });}); console.log('Started...');", "e": 1647, "s": 1336, "text": null }, { "code": null, "e": 1655, "s": 1647, "text": "Output:" }, { "code": null, "e": 1675, "s": 1655, "text": "Started...\n1\n3\n2\n4\n" }, { "code": null, "e": 1926, "s": 1675, "text": "In the above example, on the first iteration of event loop function A is fired. Then on second iteration function B is fired, and C is fired on the third iteration. Similarly functions D and E are fired on the fourth and fifth iteration respectively." }, { "code": null, "e": 2050, "s": 1926, "text": "2. setInterval() method: It repeats the execution of the callback after every t time in milliseconds passed as a parameter." }, { "code": "// Executed after every 1000 milliseconds// from the start of the programsetInterval(function A() { return console.log('Hello World!');}, 1000); // Executed right awayconsole.log('Executed before A...');", "e": 2258, "s": 2050, "text": null }, { "code": null, "e": 2266, "s": 2258, "text": "Output:" }, { "code": null, "e": 2357, "s": 2266, "text": "Executed before A...\nHello World!\nHello World!\nHello World!\nHello World!\nHello World!\n...\n" }, { "code": null, "e": 2493, "s": 2357, "text": "3. setTimeout() method: It schedules the execution of the callback after a certain time in milliseconds which is passed as a parameter." }, { "code": "// Executed after 3000 milliseconds // from the start of the programsetTimeout(function A() { return console.log('Hello World!');}, 3000); // executed right awayconsole.log('Executed before A...');", "e": 2695, "s": 2493, "text": null }, { "code": null, "e": 2703, "s": 2695, "text": "Output:" }, { "code": null, "e": 2738, "s": 2703, "text": "Executed before A...\nHello World!\n" }, { "code": null, "e": 2849, "s": 2738, "text": "4. clearImmediate() method: It is used to simply cancel the Immediate object created by setImmediate() method." }, { "code": "var si = setImmediate(function A() { console.log(1);}); // clears setInterval siclearImmediate(si); console.log(2);", "e": 2970, "s": 2849, "text": null }, { "code": null, "e": 2978, "s": 2970, "text": "Output:" }, { "code": null, "e": 2980, "s": 2978, "text": "2" }, { "code": null, "e": 3082, "s": 2980, "text": "5. clearInterval() method: It is used to cancel the Immediate object created by setInterval() method." }, { "code": "var si = setInterval(function A() { return console.log(\"Hello World!\");}, 500); setTimeout(function() { clearInterval(si);}, 2000);", "e": 3221, "s": 3082, "text": null }, { "code": null, "e": 3323, "s": 3221, "text": "The clearInterval() clears the setInterval ‘si’ after 500 ms, then function A is executed four times." }, { "code": null, "e": 3331, "s": 3323, "text": "Output:" }, { "code": null, "e": 3384, "s": 3331, "text": "Hello World!\nHello World!\nHello World!\nHello World!\n" }, { "code": null, "e": 3484, "s": 3384, "text": "6. clearTimeout() method: It is used to cancel the Immediate object created by setTimeout() method." }, { "code": "// si1 is cleared by clearTimeout()var si1 = setTimeout(function A() { return console.log(\"Hello World!\");}, 3000); // only si2 is executedvar si2 = setTimeout(function B() { return console.log(\"Hello Geeks!\");}, 3000); clearTimeout(si1);", "e": 3731, "s": 3484, "text": null }, { "code": null, "e": 3819, "s": 3731, "text": "Only setInterval ‘si2’ is executed as ‘si1’ is cleared by clearTimeout() method.Output:" }, { "code": null, "e": 3833, "s": 3819, "text": "Hello Geeks!\n" }, { "code": null, "e": 3848, "s": 3833, "text": "Node.js-Basics" }, { "code": null, "e": 3855, "s": 3848, "text": "Picked" }, { "code": null, "e": 3863, "s": 3855, "text": "Node.js" }, { "code": null, "e": 3880, "s": 3863, "text": "Web Technologies" } ]
Draw a Smiley in Java Applet
11 Mar, 2022 Given task is to draw a smiley face in Java Applet.Approach: Create three Ovals, one for the face, two for the eyes.Fill eyes oval with black color.Create an arc for the smile in the face. Create three Ovals, one for the face, two for the eyes. Fill eyes oval with black color. Create an arc for the smile in the face. Below is the implementation of the above approach:Applet Program: Java // Java program to Draw a// Smiley using Java Appletimport java.applet.*;import java.awt.*;/*<applet code ="Smiley" width=600 height=600></applet>*/ public class Smiley extends Applet { public void paint(Graphics g) { // Oval for face outline g.drawOval(80, 70, 150, 150); // Ovals for eyes // with black color filled g.setColor(Color.BLACK); g.fillOval(120, 120, 15, 15); g.fillOval(170, 120, 15, 15); // Arc for the smile g.drawArc(130, 180, 50, 20, 180, 180); }} Note: To run the applet in command line use the following commands > javac Smiley.java > appletviewer Smiley.java You can also refer https://www.geeksforgeeks.org/different-ways-to-run-applet-in-java to run applet program . sahilsulakhe3 java-applet Technical Scripter 2018 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Mar, 2022" }, { "code": null, "e": 115, "s": 52, "text": "Given task is to draw a smiley face in Java Applet.Approach: " }, { "code": null, "e": 243, "s": 115, "text": "Create three Ovals, one for the face, two for the eyes.Fill eyes oval with black color.Create an arc for the smile in the face." }, { "code": null, "e": 299, "s": 243, "text": "Create three Ovals, one for the face, two for the eyes." }, { "code": null, "e": 332, "s": 299, "text": "Fill eyes oval with black color." }, { "code": null, "e": 373, "s": 332, "text": "Create an arc for the smile in the face." }, { "code": null, "e": 440, "s": 373, "text": "Below is the implementation of the above approach:Applet Program: " }, { "code": null, "e": 445, "s": 440, "text": "Java" }, { "code": "// Java program to Draw a// Smiley using Java Appletimport java.applet.*;import java.awt.*;/*<applet code =\"Smiley\" width=600 height=600></applet>*/ public class Smiley extends Applet { public void paint(Graphics g) { // Oval for face outline g.drawOval(80, 70, 150, 150); // Ovals for eyes // with black color filled g.setColor(Color.BLACK); g.fillOval(120, 120, 15, 15); g.fillOval(170, 120, 15, 15); // Arc for the smile g.drawArc(130, 180, 50, 20, 180, 180); }}", "e": 986, "s": 445, "text": null }, { "code": null, "e": 1055, "s": 986, "text": "Note: To run the applet in command line use the following commands " }, { "code": null, "e": 1102, "s": 1055, "text": "> javac Smiley.java\n> appletviewer Smiley.java" }, { "code": null, "e": 1213, "s": 1102, "text": "You can also refer https://www.geeksforgeeks.org/different-ways-to-run-applet-in-java to run applet program . " }, { "code": null, "e": 1227, "s": 1213, "text": "sahilsulakhe3" }, { "code": null, "e": 1239, "s": 1227, "text": "java-applet" }, { "code": null, "e": 1263, "s": 1239, "text": "Technical Scripter 2018" }, { "code": null, "e": 1268, "s": 1263, "text": "Java" }, { "code": null, "e": 1287, "s": 1268, "text": "Technical Scripter" }, { "code": null, "e": 1292, "s": 1287, "text": "Java" } ]
How to convert list to dictionary in Python?
The list is a linear data structure containing data elements. Example 1,2,3,4,5,6 Dictionary is a data structure consisting of key: value pairs. Keys are unique and each key has some value associated with it. Example 1:2, 3:4, 5:6 Given a list, convert this list into the dictionary, such that the odd position elements are the keys and the even position elements are the values as depicted in the above example. Live Demo def convert(l): dic={} for i in range(0,len(l),2): dic[l[i]]=l[i+1] return dic ar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida'] print(convert(ar)) {1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'} Initialize an iterator to the variable i. After that zip together the key and values and typecast into a dictionary using dict(). Live Demo def convert(l): i=iter(l) dic=dict(zip(i,i)) return dic ar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida'] print(convert(ar)) {1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
[ { "code": null, "e": 1249, "s": 1187, "text": "The list is a linear data structure containing data elements." }, { "code": null, "e": 1257, "s": 1249, "text": "Example" }, { "code": null, "e": 1269, "s": 1257, "text": "1,2,3,4,5,6" }, { "code": null, "e": 1396, "s": 1269, "text": "Dictionary is a data structure consisting of key: value pairs. Keys are unique and each key has some value associated with it." }, { "code": null, "e": 1404, "s": 1396, "text": "Example" }, { "code": null, "e": 1418, "s": 1404, "text": "1:2, 3:4, 5:6" }, { "code": null, "e": 1600, "s": 1418, "text": "Given a list, convert this list into the dictionary, such that the odd position elements are the keys and the even position elements are the values as depicted in the above example." }, { "code": null, "e": 1611, "s": 1600, "text": " Live Demo" }, { "code": null, "e": 1777, "s": 1611, "text": "def convert(l):\n dic={}\n for i in range(0,len(l),2):\n dic[l[i]]=l[i+1]\n\n return dic\n\nar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida']\nprint(convert(ar))" }, { "code": null, "e": 1832, "s": 1777, "text": "{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}" }, { "code": null, "e": 1962, "s": 1832, "text": "Initialize an iterator to the variable i. After that zip together the key and values and typecast into a dictionary using dict()." }, { "code": null, "e": 1973, "s": 1962, "text": " Live Demo" }, { "code": null, "e": 2109, "s": 1973, "text": "def convert(l):\n i=iter(l)\n dic=dict(zip(i,i))\n return dic\n\nar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida']\nprint(convert(ar))" }, { "code": null, "e": 2164, "s": 2109, "text": "{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}" } ]
Double colon (::) operator in Java
23 Feb, 2022 The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The only difference it has from lambda expressions is that this uses direct reference to the method by name instead of providing a delegate to the method. Syntax: <Class name>::<method name> Example: To print all elements of the stream: Using Lambda expression:stream.forEach( s-> System.out.println(s));Program:// Java code to print the elements of Stream// without using double colon operator import java.util.stream.*; class GFG { public static void main(String[] args) { // Get the stream Stream<String> stream = Stream.of("Geeks", "For", "Geeks", "A", "Computer", "Portal"); // Print the stream stream.forEach(s -> System.out.println(s)); }}Output:Geeks For Geeks A Computer Portal stream.forEach( s-> System.out.println(s)); Program: // Java code to print the elements of Stream// without using double colon operator import java.util.stream.*; class GFG { public static void main(String[] args) { // Get the stream Stream<String> stream = Stream.of("Geeks", "For", "Geeks", "A", "Computer", "Portal"); // Print the stream stream.forEach(s -> System.out.println(s)); }} Geeks For Geeks A Computer Portal Using double colon operator:stream.forEach( System.out::println);Program: To demonstrate the use of double colon operator// Java code to print the elements of Stream// using double colon operator import java.util.stream.*; class GFG { public static void main(String[] args) { // Get the stream Stream<String> stream = Stream.of("Geeks", "For", "Geeks", "A", "Computer", "Portal"); // Print the stream // using double colon operator stream.forEach(System.out::println); }}Output:Geeks For Geeks A Computer Portal stream.forEach( System.out::println); Program: To demonstrate the use of double colon operator // Java code to print the elements of Stream// using double colon operator import java.util.stream.*; class GFG { public static void main(String[] args) { // Get the stream Stream<String> stream = Stream.of("Geeks", "For", "Geeks", "A", "Computer", "Portal"); // Print the stream // using double colon operator stream.forEach(System.out::println); }} Geeks For Geeks A Computer Portal When and how to use double colon operator? Method reference or double colon operator can be used to refer: a static method, an instance method, or a constructor. How to use method reference in Java: Static methodSyntax:(ClassName::methodName)Example:SomeClass::someStaticMethodProgram:// Java code to show use of double colon operator// for static methods import java.util.*; class GFG { // static function to be called static void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the static method // using double colon operator list.forEach(GFG::someFunction); }}Output:Geeks For GEEKS Instance methodSyntax:(objectOfClass::methodName)Example:System.out::printlnProgram:// Java code to show use of double colon operator// for instance methods import java.util.*; class GFG { // instance function to be called void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the instance method // using double colon operator list.forEach((new GFG())::someFunction); }}Output:Geeks For GEEKS Super methodSyntax:(super::methodName)Example:super::someSuperClassMethodProgram:// Java code to show use of double colon operator// for super methods import java.util.*;import java.util.function.*; class Test { // super function to be called String print(String str) { return ("Hello " + str + "\n"); }} class GFG extends Test { // instance method to override super method @Override String print(String s) { // call the super method // using double colon operator Function<String, String> func = super::print; String newValue = func.apply(s); newValue += "Bye " + s + "\n"; System.out.println(newValue); return newValue; } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the instance method // using double colon operator list.forEach(new GFG()::print); }}Output:Hello Geeks Bye Geeks Hello For Bye For Hello GEEKS Bye GEEKS Instance method of an arbitrary object of a particular typeSyntax:(ClassName::methodName)Example:SomeClass::someInstanceMethodProgram:// Java code to show use of double colon operator // for instance method of arbitrary type import java.util.*; class Test { String str=null; Test(String s) { this.str=s; } // instance function to be called void someFunction() { System.out.println(this.str); } } class GFG { public static void main(String[] args) { List<Test> list = new ArrayList<Test>(); list.add(new Test("Geeks")); list.add(new Test("For")); list.add(new Test("GEEKS")); // call the instance method // using double colon operator list.forEach(Test::someFunction); } }Output:Geeks For GEEKS Class ConstructorSyntax:(ClassName::new)Example:ArrayList::newProgram:// Java code to show use of double colon operator// for class constructor import java.util.*; class GFG { // Class constructor public GFG(String s) { System.out.println("Hello " + s); } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the class constructor // using double colon operator list.forEach(GFG::new); }}Output:Hello Geeks Hello For Hello GEEKS Static methodSyntax:(ClassName::methodName)Example:SomeClass::someStaticMethodProgram:// Java code to show use of double colon operator// for static methods import java.util.*; class GFG { // static function to be called static void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the static method // using double colon operator list.forEach(GFG::someFunction); }}Output:Geeks For GEEKS Syntax: (ClassName::methodName) Example: SomeClass::someStaticMethod Program: // Java code to show use of double colon operator// for static methods import java.util.*; class GFG { // static function to be called static void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the static method // using double colon operator list.forEach(GFG::someFunction); }} Geeks For GEEKS Instance methodSyntax:(objectOfClass::methodName)Example:System.out::printlnProgram:// Java code to show use of double colon operator// for instance methods import java.util.*; class GFG { // instance function to be called void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the instance method // using double colon operator list.forEach((new GFG())::someFunction); }}Output:Geeks For GEEKS Syntax: (objectOfClass::methodName) Example: System.out::println Program: // Java code to show use of double colon operator// for instance methods import java.util.*; class GFG { // instance function to be called void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the instance method // using double colon operator list.forEach((new GFG())::someFunction); }} Geeks For GEEKS Super methodSyntax:(super::methodName)Example:super::someSuperClassMethodProgram:// Java code to show use of double colon operator// for super methods import java.util.*;import java.util.function.*; class Test { // super function to be called String print(String str) { return ("Hello " + str + "\n"); }} class GFG extends Test { // instance method to override super method @Override String print(String s) { // call the super method // using double colon operator Function<String, String> func = super::print; String newValue = func.apply(s); newValue += "Bye " + s + "\n"; System.out.println(newValue); return newValue; } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the instance method // using double colon operator list.forEach(new GFG()::print); }}Output:Hello Geeks Bye Geeks Hello For Bye For Hello GEEKS Bye GEEKS Syntax: (super::methodName) Example: super::someSuperClassMethod Program: // Java code to show use of double colon operator// for super methods import java.util.*;import java.util.function.*; class Test { // super function to be called String print(String str) { return ("Hello " + str + "\n"); }} class GFG extends Test { // instance method to override super method @Override String print(String s) { // call the super method // using double colon operator Function<String, String> func = super::print; String newValue = func.apply(s); newValue += "Bye " + s + "\n"; System.out.println(newValue); return newValue; } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the instance method // using double colon operator list.forEach(new GFG()::print); }} Hello Geeks Bye Geeks Hello For Bye For Hello GEEKS Bye GEEKS Instance method of an arbitrary object of a particular typeSyntax:(ClassName::methodName)Example:SomeClass::someInstanceMethodProgram:// Java code to show use of double colon operator // for instance method of arbitrary type import java.util.*; class Test { String str=null; Test(String s) { this.str=s; } // instance function to be called void someFunction() { System.out.println(this.str); } } class GFG { public static void main(String[] args) { List<Test> list = new ArrayList<Test>(); list.add(new Test("Geeks")); list.add(new Test("For")); list.add(new Test("GEEKS")); // call the instance method // using double colon operator list.forEach(Test::someFunction); } }Output:Geeks For GEEKS Syntax: (ClassName::methodName) Example: SomeClass::someInstanceMethod Program: // Java code to show use of double colon operator // for instance method of arbitrary type import java.util.*; class Test { String str=null; Test(String s) { this.str=s; } // instance function to be called void someFunction() { System.out.println(this.str); } } class GFG { public static void main(String[] args) { List<Test> list = new ArrayList<Test>(); list.add(new Test("Geeks")); list.add(new Test("For")); list.add(new Test("GEEKS")); // call the instance method // using double colon operator list.forEach(Test::someFunction); } } Geeks For GEEKS Class ConstructorSyntax:(ClassName::new)Example:ArrayList::newProgram:// Java code to show use of double colon operator// for class constructor import java.util.*; class GFG { // Class constructor public GFG(String s) { System.out.println("Hello " + s); } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the class constructor // using double colon operator list.forEach(GFG::new); }}Output:Hello Geeks Hello For Hello GEEKS Syntax: (ClassName::new) Example: ArrayList::new Program: // Java code to show use of double colon operator// for class constructor import java.util.*; class GFG { // Class constructor public GFG(String s) { System.out.println("Hello " + s); } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("For"); list.add("GEEKS"); // call the class constructor // using double colon operator list.forEach(GFG::new); }} Hello Geeks Hello For Hello GEEKS Peipei Wang richard20 Operators Java Java Operators Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Feb, 2022" }, { "code": null, "e": 418, "s": 54, "text": "The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The only difference it has from lambda expressions is that this uses direct reference to the method by name instead of providing a delegate to the method." }, { "code": null, "e": 426, "s": 418, "text": "Syntax:" }, { "code": null, "e": 454, "s": 426, "text": "<Class name>::<method name>" }, { "code": null, "e": 500, "s": 454, "text": "Example: To print all elements of the stream:" }, { "code": null, "e": 1074, "s": 500, "text": "Using Lambda expression:stream.forEach( s-> System.out.println(s));Program:// Java code to print the elements of Stream// without using double colon operator import java.util.stream.*; class GFG { public static void main(String[] args) { // Get the stream Stream<String> stream = Stream.of(\"Geeks\", \"For\", \"Geeks\", \"A\", \"Computer\", \"Portal\"); // Print the stream stream.forEach(s -> System.out.println(s)); }}Output:Geeks\nFor\nGeeks\nA\nComputer\nPortal\n" }, { "code": null, "e": 1118, "s": 1074, "text": "stream.forEach( s-> System.out.println(s));" }, { "code": null, "e": 1127, "s": 1118, "text": "Program:" }, { "code": "// Java code to print the elements of Stream// without using double colon operator import java.util.stream.*; class GFG { public static void main(String[] args) { // Get the stream Stream<String> stream = Stream.of(\"Geeks\", \"For\", \"Geeks\", \"A\", \"Computer\", \"Portal\"); // Print the stream stream.forEach(s -> System.out.println(s)); }}", "e": 1585, "s": 1127, "text": null }, { "code": null, "e": 1620, "s": 1585, "text": "Geeks\nFor\nGeeks\nA\nComputer\nPortal\n" }, { "code": null, "e": 2263, "s": 1620, "text": "Using double colon operator:stream.forEach( System.out::println);Program: To demonstrate the use of double colon operator// Java code to print the elements of Stream// using double colon operator import java.util.stream.*; class GFG { public static void main(String[] args) { // Get the stream Stream<String> stream = Stream.of(\"Geeks\", \"For\", \"Geeks\", \"A\", \"Computer\", \"Portal\"); // Print the stream // using double colon operator stream.forEach(System.out::println); }}Output:Geeks\nFor\nGeeks\nA\nComputer\nPortal\n" }, { "code": null, "e": 2301, "s": 2263, "text": "stream.forEach( System.out::println);" }, { "code": null, "e": 2358, "s": 2301, "text": "Program: To demonstrate the use of double colon operator" }, { "code": "// Java code to print the elements of Stream// using double colon operator import java.util.stream.*; class GFG { public static void main(String[] args) { // Get the stream Stream<String> stream = Stream.of(\"Geeks\", \"For\", \"Geeks\", \"A\", \"Computer\", \"Portal\"); // Print the stream // using double colon operator stream.forEach(System.out::println); }}", "e": 2839, "s": 2358, "text": null }, { "code": null, "e": 2874, "s": 2839, "text": "Geeks\nFor\nGeeks\nA\nComputer\nPortal\n" }, { "code": null, "e": 2917, "s": 2874, "text": "When and how to use double colon operator?" }, { "code": null, "e": 2981, "s": 2917, "text": "Method reference or double colon operator can be used to refer:" }, { "code": null, "e": 2998, "s": 2981, "text": "a static method," }, { "code": null, "e": 3021, "s": 2998, "text": "an instance method, or" }, { "code": null, "e": 3036, "s": 3021, "text": "a constructor." }, { "code": null, "e": 3073, "s": 3036, "text": "How to use method reference in Java:" }, { "code": null, "e": 6898, "s": 3073, "text": "Static methodSyntax:(ClassName::methodName)Example:SomeClass::someStaticMethodProgram:// Java code to show use of double colon operator// for static methods import java.util.*; class GFG { // static function to be called static void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the static method // using double colon operator list.forEach(GFG::someFunction); }}Output:Geeks\nFor\nGEEKS\nInstance methodSyntax:(objectOfClass::methodName)Example:System.out::printlnProgram:// Java code to show use of double colon operator// for instance methods import java.util.*; class GFG { // instance function to be called void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the instance method // using double colon operator list.forEach((new GFG())::someFunction); }}Output:Geeks\nFor\nGEEKS\nSuper methodSyntax:(super::methodName)Example:super::someSuperClassMethodProgram:// Java code to show use of double colon operator// for super methods import java.util.*;import java.util.function.*; class Test { // super function to be called String print(String str) { return (\"Hello \" + str + \"\\n\"); }} class GFG extends Test { // instance method to override super method @Override String print(String s) { // call the super method // using double colon operator Function<String, String> func = super::print; String newValue = func.apply(s); newValue += \"Bye \" + s + \"\\n\"; System.out.println(newValue); return newValue; } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the instance method // using double colon operator list.forEach(new GFG()::print); }}Output:Hello Geeks\nBye Geeks\n\nHello For\nBye For\n\nHello GEEKS\nBye GEEKS\nInstance method of an arbitrary object of a particular typeSyntax:(ClassName::methodName)Example:SomeClass::someInstanceMethodProgram:// Java code to show use of double colon operator // for instance method of arbitrary type import java.util.*; class Test { String str=null; Test(String s) { this.str=s; } // instance function to be called void someFunction() { System.out.println(this.str); } } class GFG { public static void main(String[] args) { List<Test> list = new ArrayList<Test>(); list.add(new Test(\"Geeks\")); list.add(new Test(\"For\")); list.add(new Test(\"GEEKS\")); // call the instance method // using double colon operator list.forEach(Test::someFunction); } }Output:Geeks\nFor\nGEEKS\nClass ConstructorSyntax:(ClassName::new)Example:ArrayList::newProgram:// Java code to show use of double colon operator// for class constructor import java.util.*; class GFG { // Class constructor public GFG(String s) { System.out.println(\"Hello \" + s); } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the class constructor // using double colon operator list.forEach(GFG::new); }}Output:Hello Geeks\nHello For\nHello GEEKS\n" }, { "code": null, "e": 7525, "s": 6898, "text": "Static methodSyntax:(ClassName::methodName)Example:SomeClass::someStaticMethodProgram:// Java code to show use of double colon operator// for static methods import java.util.*; class GFG { // static function to be called static void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the static method // using double colon operator list.forEach(GFG::someFunction); }}Output:Geeks\nFor\nGEEKS\n" }, { "code": null, "e": 7533, "s": 7525, "text": "Syntax:" }, { "code": null, "e": 7557, "s": 7533, "text": "(ClassName::methodName)" }, { "code": null, "e": 7566, "s": 7557, "text": "Example:" }, { "code": null, "e": 7594, "s": 7566, "text": "SomeClass::someStaticMethod" }, { "code": null, "e": 7603, "s": 7594, "text": "Program:" }, { "code": "// Java code to show use of double colon operator// for static methods import java.util.*; class GFG { // static function to be called static void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the static method // using double colon operator list.forEach(GFG::someFunction); }}", "e": 8121, "s": 7603, "text": null }, { "code": null, "e": 8138, "s": 8121, "text": "Geeks\nFor\nGEEKS\n" }, { "code": null, "e": 8770, "s": 8138, "text": "Instance methodSyntax:(objectOfClass::methodName)Example:System.out::printlnProgram:// Java code to show use of double colon operator// for instance methods import java.util.*; class GFG { // instance function to be called void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the instance method // using double colon operator list.forEach((new GFG())::someFunction); }}Output:Geeks\nFor\nGEEKS\n" }, { "code": null, "e": 8778, "s": 8770, "text": "Syntax:" }, { "code": null, "e": 8806, "s": 8778, "text": "(objectOfClass::methodName)" }, { "code": null, "e": 8815, "s": 8806, "text": "Example:" }, { "code": null, "e": 8835, "s": 8815, "text": "System.out::println" }, { "code": null, "e": 8844, "s": 8835, "text": "Program:" }, { "code": "// Java code to show use of double colon operator// for instance methods import java.util.*; class GFG { // instance function to be called void someFunction(String s) { System.out.println(s); } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the instance method // using double colon operator list.forEach((new GFG())::someFunction); }}", "e": 9369, "s": 8844, "text": null }, { "code": null, "e": 9386, "s": 9369, "text": "Geeks\nFor\nGEEKS\n" }, { "code": null, "e": 10505, "s": 9386, "text": "Super methodSyntax:(super::methodName)Example:super::someSuperClassMethodProgram:// Java code to show use of double colon operator// for super methods import java.util.*;import java.util.function.*; class Test { // super function to be called String print(String str) { return (\"Hello \" + str + \"\\n\"); }} class GFG extends Test { // instance method to override super method @Override String print(String s) { // call the super method // using double colon operator Function<String, String> func = super::print; String newValue = func.apply(s); newValue += \"Bye \" + s + \"\\n\"; System.out.println(newValue); return newValue; } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the instance method // using double colon operator list.forEach(new GFG()::print); }}Output:Hello Geeks\nBye Geeks\n\nHello For\nBye For\n\nHello GEEKS\nBye GEEKS\n" }, { "code": null, "e": 10513, "s": 10505, "text": "Syntax:" }, { "code": null, "e": 10533, "s": 10513, "text": "(super::methodName)" }, { "code": null, "e": 10542, "s": 10533, "text": "Example:" }, { "code": null, "e": 10570, "s": 10542, "text": "super::someSuperClassMethod" }, { "code": null, "e": 10579, "s": 10570, "text": "Program:" }, { "code": "// Java code to show use of double colon operator// for super methods import java.util.*;import java.util.function.*; class Test { // super function to be called String print(String str) { return (\"Hello \" + str + \"\\n\"); }} class GFG extends Test { // instance method to override super method @Override String print(String s) { // call the super method // using double colon operator Function<String, String> func = super::print; String newValue = func.apply(s); newValue += \"Bye \" + s + \"\\n\"; System.out.println(newValue); return newValue; } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the instance method // using double colon operator list.forEach(new GFG()::print); }}", "e": 11546, "s": 10579, "text": null }, { "code": null, "e": 11611, "s": 11546, "text": "Hello Geeks\nBye Geeks\n\nHello For\nBye For\n\nHello GEEKS\nBye GEEKS\n" }, { "code": null, "e": 12431, "s": 11611, "text": "Instance method of an arbitrary object of a particular typeSyntax:(ClassName::methodName)Example:SomeClass::someInstanceMethodProgram:// Java code to show use of double colon operator // for instance method of arbitrary type import java.util.*; class Test { String str=null; Test(String s) { this.str=s; } // instance function to be called void someFunction() { System.out.println(this.str); } } class GFG { public static void main(String[] args) { List<Test> list = new ArrayList<Test>(); list.add(new Test(\"Geeks\")); list.add(new Test(\"For\")); list.add(new Test(\"GEEKS\")); // call the instance method // using double colon operator list.forEach(Test::someFunction); } }Output:Geeks\nFor\nGEEKS\n" }, { "code": null, "e": 12439, "s": 12431, "text": "Syntax:" }, { "code": null, "e": 12463, "s": 12439, "text": "(ClassName::methodName)" }, { "code": null, "e": 12472, "s": 12463, "text": "Example:" }, { "code": null, "e": 12502, "s": 12472, "text": "SomeClass::someInstanceMethod" }, { "code": null, "e": 12511, "s": 12502, "text": "Program:" }, { "code": "// Java code to show use of double colon operator // for instance method of arbitrary type import java.util.*; class Test { String str=null; Test(String s) { this.str=s; } // instance function to be called void someFunction() { System.out.println(this.str); } } class GFG { public static void main(String[] args) { List<Test> list = new ArrayList<Test>(); list.add(new Test(\"Geeks\")); list.add(new Test(\"For\")); list.add(new Test(\"GEEKS\")); // call the instance method // using double colon operator list.forEach(Test::someFunction); } }", "e": 13174, "s": 12511, "text": null }, { "code": null, "e": 13191, "s": 13174, "text": "Geeks\nFor\nGEEKS\n" }, { "code": null, "e": 13822, "s": 13191, "text": "Class ConstructorSyntax:(ClassName::new)Example:ArrayList::newProgram:// Java code to show use of double colon operator// for class constructor import java.util.*; class GFG { // Class constructor public GFG(String s) { System.out.println(\"Hello \" + s); } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the class constructor // using double colon operator list.forEach(GFG::new); }}Output:Hello Geeks\nHello For\nHello GEEKS\n" }, { "code": null, "e": 13830, "s": 13822, "text": "Syntax:" }, { "code": null, "e": 13847, "s": 13830, "text": "(ClassName::new)" }, { "code": null, "e": 13856, "s": 13847, "text": "Example:" }, { "code": null, "e": 13871, "s": 13856, "text": "ArrayList::new" }, { "code": null, "e": 13880, "s": 13871, "text": "Program:" }, { "code": "// Java code to show use of double colon operator// for class constructor import java.util.*; class GFG { // Class constructor public GFG(String s) { System.out.println(\"Hello \" + s); } // Driver code public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"GEEKS\"); // call the class constructor // using double colon operator list.forEach(GFG::new); }}", "e": 14400, "s": 13880, "text": null }, { "code": null, "e": 14435, "s": 14400, "text": "Hello Geeks\nHello For\nHello GEEKS\n" }, { "code": null, "e": 14447, "s": 14435, "text": "Peipei Wang" }, { "code": null, "e": 14457, "s": 14447, "text": "richard20" }, { "code": null, "e": 14467, "s": 14457, "text": "Operators" }, { "code": null, "e": 14472, "s": 14467, "text": "Java" }, { "code": null, "e": 14477, "s": 14472, "text": "Java" }, { "code": null, "e": 14487, "s": 14477, "text": "Operators" } ]
How to Change the Number of Open File Limit in Linux?
09 Apr, 2021 If you are an active Linux user, who has to work with many files on Linux at a time then you might have definitely faced a problem regarding “Too many open files” on a Linux system. When you have reached the maximum open file limit you will get an error message displaying “Too many open files (24)” error on your screen. Why do we face such a thing? Well, Linux operating system set a limit of “open files” that a user can open at a time, Linux operating system uses this way to restrict the user from opening too many files at a time. But luckily we can modify the number of Open File Limits in Linux according to our wish using some different methods that we are going to discuss today in this article. Why does Linux Limit the number of opened files? The reason is first due to security purpose so that no software creates files endlessly till the Linux server crashes and also that the Linux Operating System needs memory to manage each open file and memory is kind of limited especially on embedded systems so there is some limitation for a number of open files in a system by a user. There are 2 types of open file Limit, are as follows: Hard Values of File Descriptors. Soft Values of File Descriptors. Hard Values of File Descriptors: Hard value limits are those file limits that can only be modified by the root user. Non-root users cannot change the value of a hard limit. We can check the hard value limit using the following command:- $ ulimit -Hn Soft Values of File Descriptors: A soft value limits are those limit that shows the current effective value for the user that can be modified by a user process at any time. Core dumps can be disabled by soft values. We can check the soft value limit using the following command:- $ ulimit -Sn ulimit is a bash built-in shell command(so you might not get the desirable result from it on other types of shell) which can be used to increase the number of open files descriptors limit for each process in Linux shell. Syntax : ulimit [options [limit]] a.) -a (Current Settings Passing):- argument that causes ulimit to display its current settings To show the current limitation use the following command: ulimit -a | grep open b.) -f (File Limits): argument limits the size of files that may be created by the shell. c.) -H and -S (Hard and Soft Limits) is already discussed above Now For editing the Limit use the following command:- ulimit -n 3000 But this value will be reset if you restart your computer or logout the user. For changing the value permanently we have to edit one of the user’s configuration files (.bashrc or .profile) or the system-wide configuration files (/etc/bashrc or /etc/profile) by adding the following command at the end of the file:- # vim .bash_profile ulimit -n 3000 Now the changes are permanent, even you restart your computer, it won’t change. Another best way to modify the open file limit is done through this PAM module called pam_limits. We have to configure it by editing the /etc/security/limits.conf file. There are 4 essential fields present in this configuration file. They are:- domain: Domain describes a specific unit to which the limit applies that can be a username, a group name (with the form @groupname syntax), or an asterisk ( * ) wildcard (wildcard limits are not applied to root).type: Type specifies whether the limit is hard or soft.item: it specifies the type of item that is being limited. This could be core (limits the size of core files), fsize (maximum file size), data (maximum data size), sizeetc.value: values that will be applied to the limit. domain: Domain describes a specific unit to which the limit applies that can be a username, a group name (with the form @groupname syntax), or an asterisk ( * ) wildcard (wildcard limits are not applied to root). type: Type specifies whether the limit is hard or soft. item: it specifies the type of item that is being limited. This could be core (limits the size of core files), fsize (maximum file size), data (maximum data size), sizeetc. value: values that will be applied to the limit. Now you can edit this configuration file to change the limit of opened files for all users, For instance, you can add the following lines below the end of the file lines: # vim /etc/security/limits.conf * hard nofile 21000 * soft nofile 16000 Now edit the file /etc/pam.d/login # vim /etc/pam.d/login session required pam_limits.so And you are done changing the open file limit. Picked How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Apr, 2021" }, { "code": null, "e": 350, "s": 28, "text": "If you are an active Linux user, who has to work with many files on Linux at a time then you might have definitely faced a problem regarding “Too many open files” on a Linux system. When you have reached the maximum open file limit you will get an error message displaying “Too many open files (24)” error on your screen." }, { "code": null, "e": 565, "s": 350, "text": "Why do we face such a thing? Well, Linux operating system set a limit of “open files” that a user can open at a time, Linux operating system uses this way to restrict the user from opening too many files at a time." }, { "code": null, "e": 734, "s": 565, "text": "But luckily we can modify the number of Open File Limits in Linux according to our wish using some different methods that we are going to discuss today in this article." }, { "code": null, "e": 1121, "s": 734, "text": "Why does Linux Limit the number of opened files? The reason is first due to security purpose so that no software creates files endlessly till the Linux server crashes and also that the Linux Operating System needs memory to manage each open file and memory is kind of limited especially on embedded systems so there is some limitation for a number of open files in a system by a user. " }, { "code": null, "e": 1175, "s": 1121, "text": "There are 2 types of open file Limit, are as follows:" }, { "code": null, "e": 1209, "s": 1175, "text": "Hard Values of File Descriptors. " }, { "code": null, "e": 1242, "s": 1209, "text": "Soft Values of File Descriptors." }, { "code": null, "e": 1415, "s": 1242, "text": "Hard Values of File Descriptors: Hard value limits are those file limits that can only be modified by the root user. Non-root users cannot change the value of a hard limit." }, { "code": null, "e": 1479, "s": 1415, "text": "We can check the hard value limit using the following command:-" }, { "code": null, "e": 1492, "s": 1479, "text": "$ ulimit -Hn" }, { "code": null, "e": 1731, "s": 1492, "text": "Soft Values of File Descriptors: A soft value limits are those limit that shows the current effective value for the user that can be modified by a user process at any time. Core dumps can be disabled by soft values. " }, { "code": null, "e": 1796, "s": 1731, "text": " We can check the soft value limit using the following command:-" }, { "code": null, "e": 1809, "s": 1796, "text": "$ ulimit -Sn" }, { "code": null, "e": 2030, "s": 1809, "text": "ulimit is a bash built-in shell command(so you might not get the desirable result from it on other types of shell) which can be used to increase the number of open files descriptors limit for each process in Linux shell." }, { "code": null, "e": 2064, "s": 2030, "text": "Syntax : ulimit [options [limit]]" }, { "code": null, "e": 2160, "s": 2064, "text": "a.) -a (Current Settings Passing):- argument that causes ulimit to display its current settings" }, { "code": null, "e": 2218, "s": 2160, "text": "To show the current limitation use the following command:" }, { "code": null, "e": 2240, "s": 2218, "text": "ulimit -a | grep open" }, { "code": null, "e": 2330, "s": 2240, "text": "b.) -f (File Limits): argument limits the size of files that may be created by the shell." }, { "code": null, "e": 2394, "s": 2330, "text": "c.) -H and -S (Hard and Soft Limits) is already discussed above" }, { "code": null, "e": 2448, "s": 2394, "text": "Now For editing the Limit use the following command:-" }, { "code": null, "e": 2465, "s": 2448, "text": " ulimit -n 3000 " }, { "code": null, "e": 2543, "s": 2465, "text": "But this value will be reset if you restart your computer or logout the user." }, { "code": null, "e": 2780, "s": 2543, "text": "For changing the value permanently we have to edit one of the user’s configuration files (.bashrc or .profile) or the system-wide configuration files (/etc/bashrc or /etc/profile) by adding the following command at the end of the file:-" }, { "code": null, "e": 2800, "s": 2780, "text": "# vim .bash_profile" }, { "code": null, "e": 2815, "s": 2800, "text": "ulimit -n 3000" }, { "code": null, "e": 2895, "s": 2815, "text": "Now the changes are permanent, even you restart your computer, it won’t change." }, { "code": null, "e": 3064, "s": 2895, "text": "Another best way to modify the open file limit is done through this PAM module called pam_limits. We have to configure it by editing the /etc/security/limits.conf file." }, { "code": null, "e": 3140, "s": 3064, "text": "There are 4 essential fields present in this configuration file. They are:-" }, { "code": null, "e": 3629, "s": 3140, "text": "domain: Domain describes a specific unit to which the limit applies that can be a username, a group name (with the form @groupname syntax), or an asterisk ( * ) wildcard (wildcard limits are not applied to root).type: Type specifies whether the limit is hard or soft.item: it specifies the type of item that is being limited. This could be core (limits the size of core files), fsize (maximum file size), data (maximum data size), sizeetc.value: values that will be applied to the limit." }, { "code": null, "e": 3842, "s": 3629, "text": "domain: Domain describes a specific unit to which the limit applies that can be a username, a group name (with the form @groupname syntax), or an asterisk ( * ) wildcard (wildcard limits are not applied to root)." }, { "code": null, "e": 3898, "s": 3842, "text": "type: Type specifies whether the limit is hard or soft." }, { "code": null, "e": 4071, "s": 3898, "text": "item: it specifies the type of item that is being limited. This could be core (limits the size of core files), fsize (maximum file size), data (maximum data size), sizeetc." }, { "code": null, "e": 4121, "s": 4071, "text": "value: values that will be applied to the limit." }, { "code": null, "e": 4292, "s": 4121, "text": "Now you can edit this configuration file to change the limit of opened files for all users, For instance, you can add the following lines below the end of the file lines:" }, { "code": null, "e": 4324, "s": 4292, "text": "# vim /etc/security/limits.conf" }, { "code": null, "e": 4354, "s": 4324, "text": "* hard nofile 21000" }, { "code": null, "e": 4384, "s": 4354, "text": "* soft nofile 16000" }, { "code": null, "e": 4419, "s": 4384, "text": "Now edit the file /etc/pam.d/login" }, { "code": null, "e": 4442, "s": 4419, "text": "# vim /etc/pam.d/login" }, { "code": null, "e": 4473, "s": 4442, "text": "session required pam_limits.so" }, { "code": null, "e": 4520, "s": 4473, "text": "And you are done changing the open file limit." }, { "code": null, "e": 4527, "s": 4520, "text": "Picked" }, { "code": null, "e": 4534, "s": 4527, "text": "How To" }, { "code": null, "e": 4545, "s": 4534, "text": "Linux-Unix" } ]
Pafy – Getting Dislike Count of the Video
20 Jul, 2020 In this article we will see how we can get the dislike count of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. A YouTube video has a like and dislike count meter, but video owner can turn off this function any time. We can get the pafy object with the help of new method, below is the command to get the pafy object for given video video = pafy.new(url) The video url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform. In order to do this we use dislikes attribute with the pafy object of video Syntax : video.dislikes Argument : It takes no argument Return : It returns integer Below is the implementation # importing pafyimport pafy # url of video url = "https://www.youtube.com / watch?v = vG2PNdI8axo" # getting videovideo = pafy.new(url) # getting dislikes of the videovalue = video.dislikes # printing the valueprint(value) Output : 17 Another example # importing pafyimport pafy # url of video url = "https://www.youtube.com / watch?v = i6rhnSoK_gc" # getting videovideo = pafy.new(url) # getting dislikes of the videovalue = video.dislikes # printing the valueprint(value) Output : 2388 Python-Pafy 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 | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jul, 2020" }, { "code": null, "e": 390, "s": 28, "text": "In this article we will see how we can get the dislike count of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. A YouTube video has a like and dislike count meter, but video owner can turn off this function any time." }, { "code": null, "e": 506, "s": 390, "text": "We can get the pafy object with the help of new method, below is the command to get the pafy object for given video" }, { "code": null, "e": 528, "s": 506, "text": "video = pafy.new(url)" }, { "code": null, "e": 696, "s": 528, "text": "The video url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform." }, { "code": null, "e": 772, "s": 696, "text": "In order to do this we use dislikes attribute with the pafy object of video" }, { "code": null, "e": 796, "s": 772, "text": "Syntax : video.dislikes" }, { "code": null, "e": 828, "s": 796, "text": "Argument : It takes no argument" }, { "code": null, "e": 856, "s": 828, "text": "Return : It returns integer" }, { "code": null, "e": 884, "s": 856, "text": "Below is the implementation" }, { "code": "# importing pafyimport pafy # url of video url = \"https://www.youtube.com / watch?v = vG2PNdI8axo\" # getting videovideo = pafy.new(url) # getting dislikes of the videovalue = video.dislikes # printing the valueprint(value)", "e": 1119, "s": 884, "text": null }, { "code": null, "e": 1128, "s": 1119, "text": "Output :" }, { "code": null, "e": 1132, "s": 1128, "text": "17\n" }, { "code": null, "e": 1148, "s": 1132, "text": "Another example" }, { "code": "# importing pafyimport pafy # url of video url = \"https://www.youtube.com / watch?v = i6rhnSoK_gc\" # getting videovideo = pafy.new(url) # getting dislikes of the videovalue = video.dislikes # printing the valueprint(value)", "e": 1381, "s": 1148, "text": null }, { "code": null, "e": 1390, "s": 1381, "text": "Output :" }, { "code": null, "e": 1396, "s": 1390, "text": "2388\n" }, { "code": null, "e": 1408, "s": 1396, "text": "Python-Pafy" }, { "code": null, "e": 1415, "s": 1408, "text": "Python" }, { "code": null, "e": 1513, "s": 1415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1545, "s": 1513, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1572, "s": 1545, "text": "Python Classes and Objects" }, { "code": null, "e": 1603, "s": 1572, "text": "Python | os.path.join() method" }, { "code": null, "e": 1624, "s": 1603, "text": "Python OOPs Concepts" }, { "code": null, "e": 1680, "s": 1624, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1703, "s": 1680, "text": "Introduction To PYTHON" }, { "code": null, "e": 1745, "s": 1703, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1787, "s": 1745, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1826, "s": 1787, "text": "Python | datetime.timedelta() function" } ]
Python | Check possible bijection between sequence of characters and digits
20 Jun, 2019 Given a string ‘char_seq'(sequence of characters) and a positive integer ‘dig_seq'(sequence of digits), Write a Python program to find possible bijection or one-one onto relationship between ‘char_seq’ and ‘dig_seq’ such that each character matches to one and only one digit. Examples: Input : char_seq = 'bxdyxb' dig_seq = 123421 Output : True Input : char_seq = 'bxdyxb' dig_seq = 123321 Output : False Method #1 : Using zip method This method simply zips the ‘char_seq’ and ‘dig_seq’ and checks if corresponding digits and characters matches or not. # Python3 program to Check possible bijection # between sequence of characters and digits def is_bijection(char_seq, dig_seq): z = zip(str(char_seq), str(dig_seq)) res = all( (z1[0] == z2[0]) == (z1[1] == z2[1]) for z1 in z for z2 in z) return res # Driver codechar_seq = 'bxdyxb'dig_seq = 123421print(is_bijection(char_seq, dig_seq)) True Method #2 : Using itertools.groupby method This method uses the same approach with a slight difference, it uses itertools.groupby to match characters with digits. # Python3 program to Check possible bijection # between sequence of characters and digitsimport itertools def is_bijection(char_seq, dig_seq): z = sorted(zip(str(char_seq), str(dig_seq))) res = all(gx == gy for k, g in itertools.groupby(z, key = lambda res: res[0]) for gx in g for gy in g) return res # Driver codechar_seq = 'bxdyxb'dig_seq = 123421print(is_bijection(char_seq, dig_seq)) True Python Python Programs 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 | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2019" }, { "code": null, "e": 304, "s": 28, "text": "Given a string ‘char_seq'(sequence of characters) and a positive integer ‘dig_seq'(sequence of digits), Write a Python program to find possible bijection or one-one onto relationship between ‘char_seq’ and ‘dig_seq’ such that each character matches to one and only one digit." }, { "code": null, "e": 314, "s": 304, "text": "Examples:" }, { "code": null, "e": 451, "s": 314, "text": "Input : char_seq = 'bxdyxb'\n dig_seq = 123421\nOutput : True\n\nInput : char_seq = 'bxdyxb'\n dig_seq = 123321\nOutput : False\n" }, { "code": null, "e": 481, "s": 451, "text": " Method #1 : Using zip method" }, { "code": null, "e": 600, "s": 481, "text": "This method simply zips the ‘char_seq’ and ‘dig_seq’ and checks if corresponding digits and characters matches or not." }, { "code": "# Python3 program to Check possible bijection # between sequence of characters and digits def is_bijection(char_seq, dig_seq): z = zip(str(char_seq), str(dig_seq)) res = all( (z1[0] == z2[0]) == (z1[1] == z2[1]) for z1 in z for z2 in z) return res # Driver codechar_seq = 'bxdyxb'dig_seq = 123421print(is_bijection(char_seq, dig_seq))", "e": 959, "s": 600, "text": null }, { "code": null, "e": 965, "s": 959, "text": "True\n" }, { "code": null, "e": 1009, "s": 965, "text": " Method #2 : Using itertools.groupby method" }, { "code": null, "e": 1129, "s": 1009, "text": "This method uses the same approach with a slight difference, it uses itertools.groupby to match characters with digits." }, { "code": "# Python3 program to Check possible bijection # between sequence of characters and digitsimport itertools def is_bijection(char_seq, dig_seq): z = sorted(zip(str(char_seq), str(dig_seq))) res = all(gx == gy for k, g in itertools.groupby(z, key = lambda res: res[0]) for gx in g for gy in g) return res # Driver codechar_seq = 'bxdyxb'dig_seq = 123421print(is_bijection(char_seq, dig_seq))", "e": 1557, "s": 1129, "text": null }, { "code": null, "e": 1563, "s": 1557, "text": "True\n" }, { "code": null, "e": 1570, "s": 1563, "text": "Python" }, { "code": null, "e": 1586, "s": 1570, "text": "Python Programs" }, { "code": null, "e": 1684, "s": 1586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1716, "s": 1684, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1743, "s": 1716, "text": "Python Classes and Objects" }, { "code": null, "e": 1774, "s": 1743, "text": "Python | os.path.join() method" }, { "code": null, "e": 1795, "s": 1774, "text": "Python OOPs Concepts" }, { "code": null, "e": 1851, "s": 1795, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1873, "s": 1851, "text": "Defaultdict in Python" }, { "code": null, "e": 1912, "s": 1873, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1950, "s": 1912, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1999, "s": 1950, "text": "Python | Convert string dictionary to dictionary" } ]
Transparent window in Tkinter
19 Nov, 2020 Prerequisite: Python GUI – tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. To create a transparent window, we will use the attributes() method. Syntax: root.attributes('-alpha',transparency value) To create a transparent background, we need to use the -alpha argument in the attributes() method. The alpha is Used for transparency. If the transparency value is 0.0 it means fully transparent, 1.0 means fully opaque The range is [0.0,1.0]. This isn’t supported on all systems, Tkinter always uses 1.0. Note that in this release, this attribute must be given as -alpha. Below is a program that creates a normal Tkinter window. Python3 # Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Execute tkinterroot.mainloop() Output: Non-transparent Window Now, the below program creates a transparent window using tkinter module. Python3 # Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Create transparent windowroot.attributes('-alpha',0.5) # Execute tkinterroot.mainloop() Output: Transparent Window abhigoya Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Nov, 2020" }, { "code": null, "e": 63, "s": 28, "text": "Prerequisite: Python GUI – tkinter" }, { "code": null, "e": 288, "s": 63, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python." }, { "code": null, "e": 357, "s": 288, "text": "To create a transparent window, we will use the attributes() method." }, { "code": null, "e": 365, "s": 357, "text": "Syntax:" }, { "code": null, "e": 412, "s": 365, "text": "root.attributes('-alpha',transparency value)\n\n" }, { "code": null, "e": 547, "s": 412, "text": "To create a transparent background, we need to use the -alpha argument in the attributes() method. The alpha is Used for transparency." }, { "code": null, "e": 785, "s": 547, "text": "If the transparency value is 0.0 it means fully transparent, 1.0 means fully opaque The range is [0.0,1.0]. This isn’t supported on all systems, Tkinter always uses 1.0. Note that in this release, this attribute must be given as -alpha." }, { "code": null, "e": 842, "s": 785, "text": "Below is a program that creates a normal Tkinter window." }, { "code": null, "e": 850, "s": 842, "text": "Python3" }, { "code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Execute tkinterroot.mainloop()", "e": 985, "s": 850, "text": null }, { "code": null, "e": 993, "s": 985, "text": "Output:" }, { "code": null, "e": 1016, "s": 993, "text": "Non-transparent Window" }, { "code": null, "e": 1090, "s": 1016, "text": "Now, the below program creates a transparent window using tkinter module." }, { "code": null, "e": 1098, "s": 1090, "text": "Python3" }, { "code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Create transparent windowroot.attributes('-alpha',0.5) # Execute tkinterroot.mainloop()", "e": 1290, "s": 1098, "text": null }, { "code": null, "e": 1298, "s": 1290, "text": "Output:" }, { "code": null, "e": 1319, "s": 1300, "text": "Transparent Window" }, { "code": null, "e": 1330, "s": 1321, "text": "abhigoya" }, { "code": null, "e": 1345, "s": 1330, "text": "Python-tkinter" }, { "code": null, "e": 1352, "s": 1345, "text": "Python" } ]
Reversing a queue using recursion
13 Jun, 2022 Given a queue, write a recursive function to reverse it. Standard operations allowed : enqueue(x) : Add an item x to rear of queue. dequeue() : Remove an item from front of queue. empty() : Checks if a queue is empty or not.Examples : Input : Q = [5, 24, 9, 6, 8, 4, 1, 8, 3, 6] Output : Q = [6, 3, 8, 1, 4, 8, 6, 9, 24, 5] Explanation : Output queue is the reverse of the input queue. Input : Q = [8, 7, 2, 5, 1] Output : Q = [1, 5, 2, 7, 8] Recursive Algorithm : The pop element from the queue if the queue has elements otherwise return empty queue.Call reverseQueue function for the remaining queue.Push the popped element in the resultant reversed queue. The pop element from the queue if the queue has elements otherwise return empty queue. Call reverseQueue function for the remaining queue. Push the popped element in the resultant reversed queue. Pseudo Code : Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. queue reverseFunction(queue) { if (queue is empty) return queue; else { data = queue.front() queue.pop() queue = reverseFunction(queue); q.push(data); return queue; } } C++ Java Python3 C# Javascript // C++ code for reversing a queue#include <bits/stdc++.h>using namespace std; // Utility function to print the queuevoid printQueue(queue<long long int> Queue){ while (!Queue.empty()) { cout << Queue.front() << " "; Queue.pop(); }} // Recursive function to reverse the queuevoid reverseQueue(queue<long long int>& q){ // Base case if (q.empty()) return; // Dequeue current item (from front) long long int data = q.front(); q.pop(); // Reverse remaining queue reverseQueue(q); // Enqueue current item (to rear) q.push(data);} // Driver codeint main(){ queue<long long int> Queue; Queue.push(56); Queue.push(27); Queue.push(30); Queue.push(45); Queue.push(85); Queue.push(92); Queue.push(58); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); printQueue(Queue);} // Java program to reverse a Queue by recursionimport java.util.LinkedList;import java.util.Queue;import java.util.Stack; // Java program to reverse a queue recursivelypublic class Queue_reverse { static Queue<Integer> queue; // Utility function to print the queue static void Print() { while (!queue.isEmpty()) { System.out.print(queue.peek() + " "); queue.remove(); } } // Recurrsive function to reverse the queuestatic Queue<Integer> reverseQueue(Queue<Integer> q){ // Base case if (q.isEmpty()) return q; // Dequeue current item (from front) int data = q.peek(); q.remove(); // Reverse remaining queue q = reverseQueue(q); // Enqueue current item (to rear) q.add(data); return q;} // Driver codepublic static void main(String args[]){ queue = new LinkedList<Integer>(); queue.add(56); queue.add(27); queue.add(30); queue.add(45); queue.add(85); queue.add(92); queue.add(58); queue.add(80); queue.add(90); queue.add(100); queue = reverseQueue(queue); Print();}} from queue import Queue def reverse_queue(queue: Queue): # Base case if queue.empty(): return # Dequeue current item (from front) item = queue.queue[0] queue.get() # Reverse remaining queue reverse_queue(queue) # Enqueue current item (to rear) queue.put(item) def print_queue(queue: Queue): while not queue.empty(): print(queue.queue[0], end=" ") queue.get() print() # Driver Codeif __name__ == "__main__": q = Queue() q.put(56) q.put(27) q.put(30) q.put(45) q.put(85) q.put(92) q.put(58) q.put(80) q.put(90) q.put(100) reverse_queue(q) print_queue(q) // C# code for reversing a queueusing System;using System.Collections.Generic; class GFG{ // Utility function // to print the queue static void printQueue(Queue<long> queue) { while (queue.Count != 0) { Console.Write(queue.Peek() + " "); queue.Dequeue(); } } // Recursive function // to reverse the queue static void reverseQueue(ref Queue<long> q) { // Base case if (q.Count == 0) return; // Dequeue current // item (from front) long data = q.Peek(); q.Dequeue(); // Reverse remaining queue reverseQueue(ref q); // Enqueue current // item (to rear) q.Enqueue(data); } // Driver code static void Main() { Queue<long> queue = new Queue<long>(); queue.Enqueue(56); queue.Enqueue(27); queue.Enqueue(30); queue.Enqueue(45); queue.Enqueue(85); queue.Enqueue(92); queue.Enqueue(58); queue.Enqueue(80); queue.Enqueue(90); queue.Enqueue(100); reverseQueue(ref queue); printQueue(queue); }} // This code is contributed by// Manish Shaw(manishshaw1) <script> // Javascript code for reversing a queue // Utility function // to print the queue function printQueue(queue) { while (queue.length != 0) { document.write(queue[0] + " "); queue.shift(); } } // Recursive function // to reverse the queue function reverseQueue(q) { // Base case if (q.length == 0) return; // Dequeue current // item (from front) let data = q[0]; q.shift(); // Reverse remaining queue reverseQueue(q); // Enqueue current // item (to rear) q.push(data); } let queue = []; queue.push(56); queue.push(27); queue.push(30); queue.push(45); queue.push(85); queue.push(92); queue.push(58); queue.push(80); queue.push(90); queue.push(100); reverseQueue(queue); printQueue(queue); // This code is contributed by divyeshrabadiya07.</script> 100 90 80 58 92 85 45 30 27 56 Time Complexity: O(n). Auxiliary Space: O(n), since recursion uses stack internallyVideo: Reversing a queue using recursion | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersReversing a queue using recursion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4tirwGyMtUw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> manishshaw1 ParulShandilya shindesharad71 divyeshrabadiya07 technophpfij cpp-queue java-queue Queue Recursion Technical Scripter Recursion Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 289, "s": 52, "text": "Given a queue, write a recursive function to reverse it. Standard operations allowed : enqueue(x) : Add an item x to rear of queue. dequeue() : Remove an item from front of queue. empty() : Checks if a queue is empty or not.Examples : " }, { "code": null, "e": 499, "s": 289, "text": "Input : Q = [5, 24, 9, 6, 8, 4, 1, 8, 3, 6]\nOutput : Q = [6, 3, 8, 1, 4, 8, 6, 9, 24, 5]\n\nExplanation : Output queue is the reverse of the input queue.\n\nInput : Q = [8, 7, 2, 5, 1]\nOutput : Q = [1, 5, 2, 7, 8]" }, { "code": null, "e": 523, "s": 499, "text": "Recursive Algorithm : " }, { "code": null, "e": 717, "s": 523, "text": "The pop element from the queue if the queue has elements otherwise return empty queue.Call reverseQueue function for the remaining queue.Push the popped element in the resultant reversed queue." }, { "code": null, "e": 804, "s": 717, "text": "The pop element from the queue if the queue has elements otherwise return empty queue." }, { "code": null, "e": 856, "s": 804, "text": "Call reverseQueue function for the remaining queue." }, { "code": null, "e": 913, "s": 856, "text": "Push the popped element in the resultant reversed queue." }, { "code": null, "e": 931, "s": 915, "text": "Pseudo Code : " }, { "code": null, "e": 940, "s": 931, "text": "Chapters" }, { "code": null, "e": 967, "s": 940, "text": "descriptions off, selected" }, { "code": null, "e": 1017, "s": 967, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1040, "s": 1017, "text": "captions off, selected" }, { "code": null, "e": 1048, "s": 1040, "text": "English" }, { "code": null, "e": 1072, "s": 1048, "text": "This is a modal window." }, { "code": null, "e": 1141, "s": 1072, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1163, "s": 1141, "text": "End of dialog window." }, { "code": null, "e": 1386, "s": 1163, "text": "queue reverseFunction(queue)\n{\n if (queue is empty)\n return queue;\n else {\n data = queue.front()\n queue.pop()\n queue = reverseFunction(queue);\n q.push(data);\n return queue;\n }\n}" }, { "code": null, "e": 1394, "s": 1390, "text": "C++" }, { "code": null, "e": 1399, "s": 1394, "text": "Java" }, { "code": null, "e": 1407, "s": 1399, "text": "Python3" }, { "code": null, "e": 1410, "s": 1407, "text": "C#" }, { "code": null, "e": 1421, "s": 1410, "text": "Javascript" }, { "code": "// C++ code for reversing a queue#include <bits/stdc++.h>using namespace std; // Utility function to print the queuevoid printQueue(queue<long long int> Queue){ while (!Queue.empty()) { cout << Queue.front() << \" \"; Queue.pop(); }} // Recursive function to reverse the queuevoid reverseQueue(queue<long long int>& q){ // Base case if (q.empty()) return; // Dequeue current item (from front) long long int data = q.front(); q.pop(); // Reverse remaining queue reverseQueue(q); // Enqueue current item (to rear) q.push(data);} // Driver codeint main(){ queue<long long int> Queue; Queue.push(56); Queue.push(27); Queue.push(30); Queue.push(45); Queue.push(85); Queue.push(92); Queue.push(58); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); printQueue(Queue);}", "e": 2301, "s": 1421, "text": null }, { "code": "// Java program to reverse a Queue by recursionimport java.util.LinkedList;import java.util.Queue;import java.util.Stack; // Java program to reverse a queue recursivelypublic class Queue_reverse { static Queue<Integer> queue; // Utility function to print the queue static void Print() { while (!queue.isEmpty()) { System.out.print(queue.peek() + \" \"); queue.remove(); } } // Recurrsive function to reverse the queuestatic Queue<Integer> reverseQueue(Queue<Integer> q){ // Base case if (q.isEmpty()) return q; // Dequeue current item (from front) int data = q.peek(); q.remove(); // Reverse remaining queue q = reverseQueue(q); // Enqueue current item (to rear) q.add(data); return q;} // Driver codepublic static void main(String args[]){ queue = new LinkedList<Integer>(); queue.add(56); queue.add(27); queue.add(30); queue.add(45); queue.add(85); queue.add(92); queue.add(58); queue.add(80); queue.add(90); queue.add(100); queue = reverseQueue(queue); Print();}}", "e": 3422, "s": 2301, "text": null }, { "code": "from queue import Queue def reverse_queue(queue: Queue): # Base case if queue.empty(): return # Dequeue current item (from front) item = queue.queue[0] queue.get() # Reverse remaining queue reverse_queue(queue) # Enqueue current item (to rear) queue.put(item) def print_queue(queue: Queue): while not queue.empty(): print(queue.queue[0], end=\" \") queue.get() print() # Driver Codeif __name__ == \"__main__\": q = Queue() q.put(56) q.put(27) q.put(30) q.put(45) q.put(85) q.put(92) q.put(58) q.put(80) q.put(90) q.put(100) reverse_queue(q) print_queue(q)", "e": 4074, "s": 3422, "text": null }, { "code": "// C# code for reversing a queueusing System;using System.Collections.Generic; class GFG{ // Utility function // to print the queue static void printQueue(Queue<long> queue) { while (queue.Count != 0) { Console.Write(queue.Peek() + \" \"); queue.Dequeue(); } } // Recursive function // to reverse the queue static void reverseQueue(ref Queue<long> q) { // Base case if (q.Count == 0) return; // Dequeue current // item (from front) long data = q.Peek(); q.Dequeue(); // Reverse remaining queue reverseQueue(ref q); // Enqueue current // item (to rear) q.Enqueue(data); } // Driver code static void Main() { Queue<long> queue = new Queue<long>(); queue.Enqueue(56); queue.Enqueue(27); queue.Enqueue(30); queue.Enqueue(45); queue.Enqueue(85); queue.Enqueue(92); queue.Enqueue(58); queue.Enqueue(80); queue.Enqueue(90); queue.Enqueue(100); reverseQueue(ref queue); printQueue(queue); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 5307, "s": 4074, "text": null }, { "code": "<script> // Javascript code for reversing a queue // Utility function // to print the queue function printQueue(queue) { while (queue.length != 0) { document.write(queue[0] + \" \"); queue.shift(); } } // Recursive function // to reverse the queue function reverseQueue(q) { // Base case if (q.length == 0) return; // Dequeue current // item (from front) let data = q[0]; q.shift(); // Reverse remaining queue reverseQueue(q); // Enqueue current // item (to rear) q.push(data); } let queue = []; queue.push(56); queue.push(27); queue.push(30); queue.push(45); queue.push(85); queue.push(92); queue.push(58); queue.push(80); queue.push(90); queue.push(100); reverseQueue(queue); printQueue(queue); // This code is contributed by divyeshrabadiya07.</script>", "e": 6301, "s": 5307, "text": null }, { "code": null, "e": 6332, "s": 6301, "text": "100 90 80 58 92 85 45 30 27 56" }, { "code": null, "e": 6358, "s": 6334, "text": "Time Complexity: O(n). " }, { "code": null, "e": 6427, "s": 6358, "text": "Auxiliary Space: O(n), since recursion uses stack internallyVideo: " }, { "code": null, "e": 7311, "s": 6427, "text": "Reversing a queue using recursion | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersReversing a queue using recursion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:21•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4tirwGyMtUw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 7325, "s": 7313, "text": "manishshaw1" }, { "code": null, "e": 7340, "s": 7325, "text": "ParulShandilya" }, { "code": null, "e": 7355, "s": 7340, "text": "shindesharad71" }, { "code": null, "e": 7373, "s": 7355, "text": "divyeshrabadiya07" }, { "code": null, "e": 7386, "s": 7373, "text": "technophpfij" }, { "code": null, "e": 7396, "s": 7386, "text": "cpp-queue" }, { "code": null, "e": 7407, "s": 7396, "text": "java-queue" }, { "code": null, "e": 7413, "s": 7407, "text": "Queue" }, { "code": null, "e": 7423, "s": 7413, "text": "Recursion" }, { "code": null, "e": 7442, "s": 7423, "text": "Technical Scripter" }, { "code": null, "e": 7452, "s": 7442, "text": "Recursion" }, { "code": null, "e": 7458, "s": 7452, "text": "Queue" } ]
Stream of() method in Java
08 Oct, 2018 Stream of(T t) returns a sequential Stream containing a single element.Syntax : static Stream of(T t) Parameters: This method accepts a mandatory parameter t which is the single element in the Stream. Return Value: Stream of(T t) returns a sequential Stream containing the single specified element. Example : // Java code for Stream of(T t)// to get a sequential Stream// containing a single element. import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an Stream having single element only Stream stream = Stream.of("Geeks"); // Displaying the Stream having single element stream.forEach(System.out::println); }} Geeks Stream of(T... values) returns a sequential ordered stream whose elements are the specified values. Syntax : static Stream of(T... values) Parameters: This method accepts a mandatory parameter values which are the elements of the new stream. Return Value : Stream of(T... values) returns a sequential ordered stream whose elements are the specified values. Example: // Java code for Stream of(T... values)// to get a sequential ordered stream whose// elements are the specified values. import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an Stream Stream stream = Stream.of("Geeks", "for", "Geeks"); // Displaying the sequential ordered stream stream.forEach(System.out::println); }} Geeks for Geeks Java - util package Java-Functions java-stream Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2018" }, { "code": null, "e": 108, "s": 28, "text": "Stream of(T t) returns a sequential Stream containing a single element.Syntax :" }, { "code": null, "e": 131, "s": 108, "text": "static Stream of(T t)\n" }, { "code": null, "e": 230, "s": 131, "text": "Parameters: This method accepts a mandatory parameter t which is the single element in the Stream." }, { "code": null, "e": 328, "s": 230, "text": "Return Value: Stream of(T t) returns a sequential Stream containing the single specified element." }, { "code": null, "e": 338, "s": 328, "text": "Example :" }, { "code": "// Java code for Stream of(T t)// to get a sequential Stream// containing a single element. import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an Stream having single element only Stream stream = Stream.of(\"Geeks\"); // Displaying the Stream having single element stream.forEach(System.out::println); }}", "e": 767, "s": 338, "text": null }, { "code": null, "e": 774, "s": 767, "text": "Geeks\n" }, { "code": null, "e": 874, "s": 774, "text": "Stream of(T... values) returns a sequential ordered stream whose elements are the specified values." }, { "code": null, "e": 883, "s": 874, "text": "Syntax :" }, { "code": null, "e": 914, "s": 883, "text": "static Stream of(T... values)\n" }, { "code": null, "e": 1017, "s": 914, "text": "Parameters: This method accepts a mandatory parameter values which are the elements of the new stream." }, { "code": null, "e": 1132, "s": 1017, "text": "Return Value : Stream of(T... values) returns a sequential ordered stream whose elements are the specified values." }, { "code": null, "e": 1141, "s": 1132, "text": "Example:" }, { "code": "// Java code for Stream of(T... values)// to get a sequential ordered stream whose// elements are the specified values. import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an Stream Stream stream = Stream.of(\"Geeks\", \"for\", \"Geeks\"); // Displaying the sequential ordered stream stream.forEach(System.out::println); }}", "e": 1584, "s": 1141, "text": null }, { "code": null, "e": 1601, "s": 1584, "text": "Geeks\nfor\nGeeks\n" }, { "code": null, "e": 1621, "s": 1601, "text": "Java - util package" }, { "code": null, "e": 1636, "s": 1621, "text": "Java-Functions" }, { "code": null, "e": 1648, "s": 1636, "text": "java-stream" }, { "code": null, "e": 1653, "s": 1648, "text": "Java" }, { "code": null, "e": 1658, "s": 1653, "text": "Java" } ]
Tailwind CSS Float
23 Mar, 2022 This class accepts more than one value in tailwind CSS. It is the alternative to the CSS float property. The float class defines the flow of content for controlling the wrapping of content around an element. Float Classes: float-right float-left float-none float-right: This class is used to make the element float on the right side of the container. Syntax: <element class="float-right">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS float Class</b> <div class="mx-10"> <img class="float-right p-2" src="https://media.geeksforgeeks.org/wp-content/uploads/20190807114330/GFG115.png"> <p class="text-justify ">How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor.It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course.</p> </center></body> </html> Output: float-left: This class is used to make the element float on the left side of the container. Syntax: <element class="float-left"">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS float Class</b> <div class="mx-10"> <img class="float-left p-2" src="https://media.geeksforgeeks.org/wp-content/uploads/20190807114330/GFG115.png"> <p class="text-justify ">How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor.It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course.</p> </center></body> </html> Output: float-none: This class is used to make the element float at the default place. We are using the center tag so the image is placed at the center. Syntax: <element class="float-none">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS float Class</b> <div class="mx-10"> <img class="float-none p-2" src="https://media.geeksforgeeks.org/wp-content/uploads/20190807114330/GFG115.png"> <p class="text-justify ">How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor.It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course.</p> </center></body> </html> Output: Tailwind CSS Tailwind-Layout Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2022" }, { "code": null, "e": 237, "s": 28, "text": "This class accepts more than one value in tailwind CSS. It is the alternative to the CSS float property. The float class defines the flow of content for controlling the wrapping of content around an element. " }, { "code": null, "e": 252, "s": 237, "text": "Float Classes:" }, { "code": null, "e": 264, "s": 252, "text": "float-right" }, { "code": null, "e": 276, "s": 264, "text": "float-left " }, { "code": null, "e": 288, "s": 276, "text": "float-none " }, { "code": null, "e": 382, "s": 288, "text": "float-right: This class is used to make the element float on the right side of the container." }, { "code": null, "e": 390, "s": 382, "text": "Syntax:" }, { "code": null, "e": 433, "s": 390, "text": "<element class=\"float-right\">...</element>" }, { "code": null, "e": 442, "s": 433, "text": "Example:" }, { "code": null, "e": 447, "s": 442, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS float Class</b> <div class=\"mx-10\"> <img class=\"float-right p-2\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190807114330/GFG115.png\"> <p class=\"text-justify \">How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor.It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course.</p> </center></body> </html>", "e": 1780, "s": 447, "text": null }, { "code": null, "e": 1788, "s": 1780, "text": "Output:" }, { "code": null, "e": 1880, "s": 1788, "text": "float-left: This class is used to make the element float on the left side of the container." }, { "code": null, "e": 1888, "s": 1880, "text": "Syntax:" }, { "code": null, "e": 1931, "s": 1888, "text": "<element class=\"float-left\"\">...</element>" }, { "code": null, "e": 1941, "s": 1931, "text": "Example: " }, { "code": null, "e": 1946, "s": 1941, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS float Class</b> <div class=\"mx-10\"> <img class=\"float-left p-2\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190807114330/GFG115.png\"> <p class=\"text-justify \">How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor.It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course.</p> </center></body> </html>", "e": 3281, "s": 1946, "text": null }, { "code": null, "e": 3289, "s": 3281, "text": "Output:" }, { "code": null, "e": 3434, "s": 3289, "text": "float-none: This class is used to make the element float at the default place. We are using the center tag so the image is placed at the center." }, { "code": null, "e": 3442, "s": 3434, "text": "Syntax:" }, { "code": null, "e": 3484, "s": 3442, "text": "<element class=\"float-none\">...</element>" }, { "code": null, "e": 3493, "s": 3484, "text": "Example:" }, { "code": null, "e": 3498, "s": 3493, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS float Class</b> <div class=\"mx-10\"> <img class=\"float-none p-2\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190807114330/GFG115.png\"> <p class=\"text-justify \">How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor.It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course.</p> </center></body> </html>", "e": 4830, "s": 3498, "text": null }, { "code": null, "e": 4838, "s": 4830, "text": "Output:" }, { "code": null, "e": 4851, "s": 4838, "text": "Tailwind CSS" }, { "code": null, "e": 4867, "s": 4851, "text": "Tailwind-Layout" }, { "code": null, "e": 4884, "s": 4867, "text": "Web Technologies" }, { "code": null, "e": 4982, "s": 4884, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5015, "s": 4982, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5077, "s": 5015, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5138, "s": 5077, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5188, "s": 5138, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5231, "s": 5188, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 5303, "s": 5231, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5343, "s": 5303, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5367, "s": 5343, "text": "REST API (Introduction)" }, { "code": null, "e": 5400, "s": 5367, "text": "Node.js fs.readFileSync() Method" } ]
Check if the given two numbers are friendly pair or not
23 Jun, 2022 Given two positive integer N, M. The task is to check if N and M are friendly pair or not. In number theory, friendly pairs are two numbers with a common abundancy index, the ratio between the sum of divisors of a number and the number itself i.e ?(n)/n. S o, two number n and m are friendly number if ?(n)/n = ?(m)/m. where ?(n) is the sum of divisors of n. Examples: Input : n = 6, m = 28 Output : Yes Explanation: Divisor of 6 are 1, 2, 3, 6. Divisor of 28 are 1, 2, 4, 7, 14, 28. Sum of divisor of 6 and 28 are 12 and 56 respectively. Abundancy index of 6 and 28 are 2. So they are friendly pair. Input : n = 18, m = 26 Output : No The idea is to find the sum of divisor of n and m. And to check if the abundancy index of n and m, we will find the Greatest Common Divisors of n and m with their sum of divisors. And check if the reduced form of abundancy index of n and m are equal by checking if their numerator and denominator are equal or not. To find the reduced form, we will divide numerator and denominator by GCD.Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // Check if the given two number// are friendly pair or not.#include <bits/stdc++.h>using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to check if the given two// number are friendly pair or not.bool checkFriendly(int n, int m){ // Finding the sum of factors of n and m int sumFactors_n = sumofFactors(n); int sumFactors_m = sumofFactors(m); // finding gcd of n and sum of its factors. int gcd_n = gcd(n, sumFactors_n); // finding gcd of m and sum of its factors. int gcd_m = gcd(m, sumFactors_m); // checking is numerator and denominator of // abundancy index of both number are equal // or not. if (n / gcd_n == m / gcd_m && sumFactors_n / gcd_n == sumFactors_m / gcd_m) return true; else return false;} // Driver codeint main(){ int n = 6, m = 28; checkFriendly(n, m) ? (cout << "Yes\n") : (cout << "No\n"); return 0;} // Java code to check if the given two number// are friendly pair or not.class GFG { // Returns sum of all factors of n. static int sumofFactors(int n) { // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res; } // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Function to check if the given two // number are friendly pair or not. static boolean checkFriendly(int n, int m) { // Finding the sum of factors of n and m int sumFactors_n = sumofFactors(n); int sumFactors_m = sumofFactors(m); // finding gcd of n and sum of its factors. int gcd_n = gcd(n, sumFactors_n); // finding gcd of m and sum of its factors. int gcd_m = gcd(m, sumFactors_m); // checking is numerator and denominator of // abundancy index of both number are equal // or not. if (n / gcd_n == m / gcd_m && sumFactors_n / gcd_n == sumFactors_m / gcd_m) return true; else return false; } //driver code public static void main (String[] args) { int n = 6, m = 28; if(checkFriendly(n, m)) System.out.print("Yes\n"); else System.out.print("No\n"); }} // This code is contributed by Anant Agarwal. # Check if the given two number# are friendly pair or not.import math # Returns sum of all factors of n.def sumofFactors(n): # Traversing through all prime factors. res = 1 for i in range(2, int(math.sqrt(n)) + 1): count = 0; curr_sum = 1; curr_term = 1 while (n % i == 0): count += 1 # THE BELOW STATEMENT MAKES # IT BETTER THAN ABOVE METHOD # AS WE REDUCE VALUE OF n. n = n // i curr_term *= i curr_sum += curr_term res *= curr_sum # This condition is to handle # the case when n is a prime # number greater than 2. if (n >= 2): res *= (1 + n) return res # Function to return gcd of a and bdef gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Function to check if the given two# number are friendly pair or not.def checkFriendly(n, m): # Finding the sum of factors of n and m sumFactors_n = sumofFactors(n) sumFactors_m = sumofFactors(m) # Finding gcd of n and sum of its factors. gcd_n = gcd(n, sumFactors_n) # Finding gcd of m and sum of its factors. gcd_m = gcd(m, sumFactors_m) # checking is numerator and denominator # of abundancy index of both number are # equal or not. if (n // gcd_n == m // gcd_m and sumFactors_n // gcd_n == sumFactors_m // gcd_m): return True else: return False # Driver coden = 6; m = 28if(checkFriendly(n, m)): print("Yes")else: print("No") # This code is contributed by Anant Agarwal. // C# code to check if the// given two number are// friendly pair or notusing System; class GFG { // Returns sum of all //factors of n. static int sumofFactors(int n) { // Traversing through all // prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res; } // Function to return gcd // of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Function to check if the // given two number are // friendly pair or not static bool checkFriendly(int n, int m) { // Finding the sum of factors // of n and m int sumFactors_n = sumofFactors(n); int sumFactors_m = sumofFactors(m); // finding gcd of n and // sum of its factors. int gcd_n = gcd(n, sumFactors_n); // finding gcd of m and sum // of its factors. int gcd_m = gcd(m, sumFactors_m); // checking is numerator and // denominator of abundancy // index of both number are // equal or not if (n / gcd_n == m / gcd_m && sumFactors_n / gcd_n == sumFactors_m / gcd_m) return true; else return false; } // Driver code public static void Main (String[] args) { int n = 6, m = 28; if(checkFriendly(n, m)) Console.Write("Yes\n"); else Console.Write("No\n"); }} // This code is contributed by parshar... <?php// PHP program to check if the given// two number are friendly pair or not. // Returns sum of all factors of n.function sumofFactors( $n){ // Traversing through all // prime factors. $res = 1; for ($i = 2; $i <= sqrt($n); $i++) { $count = 0; $curr_sum = 1; $curr_term = 1; while ($n % $i == 0) { $count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. $n = $n / $i; $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if ($n >= 2) $res *= (1 + $n); return $res;} // Function to return// gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Function to check if the given two// number are friendly pair or not.function checkFriendly($n, $m){ // Finding the sum of // factors of n and m $sumFactors_n = sumofFactors($n); $sumFactors_m = sumofFactors($m); // finding gcd of n and // sum of its factors. $gcd_n = gcd($n, $sumFactors_n); // finding gcd of m and // sum of its factors. $gcd_m = gcd($m, $sumFactors_m); // checking is numerator // and denominator of // abundancy index of // both number are equal // or not. if ($n / $gcd_n == $m / $gcd_m and $sumFactors_n / $gcd_n == $sumFactors_m / $gcd_m) return true; else return false;} // Driver code $n = 6; $m = 28; if(checkFriendly($n, $m)) echo "Yes" ; else echo "No"; // This code is contributed by anuj_67.?> <script> // JavaScript program to check if the given two number// are friendly pair or not. // Returns sum of all factors of n. function sumofFactors(n) { // Traversing through all prime factors. let res = 1; for (let i = 2; i <= Math.sqrt(n); i++) { let count = 0, curr_sum = 1; let curr_term = 1; while (n % i == 0) { count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res; } // Function to return gcd of a and b function gcd(a, b) { if (a == 0) return b; return gcd(b % a, a); } // Function to check if the given two // number are friendly pair or not. function checkFriendly(n, m) { // Finding the sum of factors of n and m let sumFactors_n = sumofFactors(n); let sumFactors_m = sumofFactors(m); // finding gcd of n and sum of its factors. let gcd_n = gcd(n, sumFactors_n); // finding gcd of m and sum of its factors. let gcd_m = gcd(m, sumFactors_m); // checking is numerator and denominator of // abundancy index of both number are equal // or not. if (n / gcd_n == m / gcd_m && sumFactors_n / gcd_n == sumFactors_m / gcd_m) return true; else return false; } // Driver Code let n = 6, m = 28; if(checkFriendly(n, m)) document.write("Yes\n"); else document.write("No\n"); // This code is contributed by avijitmondal1998.</script> Output Yes Time Complexity: O(√n log n) Auxiliary Space: O(1) Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above parashar vt_m nidhi_biet avijitmondal1998 sumitgumber28 codewithmini divisors GCD-LCM number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Fizz Buzz Implementation Median of two sorted arrays of same size Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms Product of Array except itself
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 146, "s": 54, "text": "Given two positive integer N, M. The task is to check if N and M are friendly pair or not. " }, { "code": null, "e": 414, "s": 146, "text": "In number theory, friendly pairs are two numbers with a common abundancy index, the ratio between the sum of divisors of a number and the number itself i.e ?(n)/n. S o, two number n and m are friendly number if ?(n)/n = ?(m)/m. where ?(n) is the sum of divisors of n." }, { "code": null, "e": 426, "s": 414, "text": "Examples: " }, { "code": null, "e": 695, "s": 426, "text": "Input : n = 6, m = 28\nOutput : Yes\nExplanation:\nDivisor of 6 are 1, 2, 3, 6.\nDivisor of 28 are 1, 2, 4, 7, 14, 28.\nSum of divisor of 6 and 28 are 12 and 56\nrespectively. Abundancy index of 6 and 28 \nare 2. So they are friendly pair.\n\nInput : n = 18, m = 26\nOutput : No" }, { "code": null, "e": 1131, "s": 697, "text": "The idea is to find the sum of divisor of n and m. And to check if the abundancy index of n and m, we will find the Greatest Common Divisors of n and m with their sum of divisors. And check if the reduced form of abundancy index of n and m are equal by checking if their numerator and denominator are equal or not. To find the reduced form, we will divide numerator and denominator by GCD.Below is the implementation of above idea : " }, { "code": null, "e": 1135, "s": 1131, "text": "C++" }, { "code": null, "e": 1140, "s": 1135, "text": "Java" }, { "code": null, "e": 1148, "s": 1140, "text": "Python3" }, { "code": null, "e": 1151, "s": 1148, "text": "C#" }, { "code": null, "e": 1155, "s": 1151, "text": "PHP" }, { "code": null, "e": 1166, "s": 1155, "text": "Javascript" }, { "code": "// Check if the given two number// are friendly pair or not.#include <bits/stdc++.h>using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to check if the given two// number are friendly pair or not.bool checkFriendly(int n, int m){ // Finding the sum of factors of n and m int sumFactors_n = sumofFactors(n); int sumFactors_m = sumofFactors(m); // finding gcd of n and sum of its factors. int gcd_n = gcd(n, sumFactors_n); // finding gcd of m and sum of its factors. int gcd_m = gcd(m, sumFactors_m); // checking is numerator and denominator of // abundancy index of both number are equal // or not. if (n / gcd_n == m / gcd_m && sumFactors_n / gcd_n == sumFactors_m / gcd_m) return true; else return false;} // Driver codeint main(){ int n = 6, m = 28; checkFriendly(n, m) ? (cout << \"Yes\\n\") : (cout << \"No\\n\"); return 0;}", "e": 2851, "s": 1166, "text": null }, { "code": "// Java code to check if the given two number// are friendly pair or not.class GFG { // Returns sum of all factors of n. static int sumofFactors(int n) { // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res; } // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Function to check if the given two // number are friendly pair or not. static boolean checkFriendly(int n, int m) { // Finding the sum of factors of n and m int sumFactors_n = sumofFactors(n); int sumFactors_m = sumofFactors(m); // finding gcd of n and sum of its factors. int gcd_n = gcd(n, sumFactors_n); // finding gcd of m and sum of its factors. int gcd_m = gcd(m, sumFactors_m); // checking is numerator and denominator of // abundancy index of both number are equal // or not. if (n / gcd_n == m / gcd_m && sumFactors_n / gcd_n == sumFactors_m / gcd_m) return true; else return false; } //driver code public static void main (String[] args) { int n = 6, m = 28; if(checkFriendly(n, m)) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); }} // This code is contributed by Anant Agarwal.", "e": 4951, "s": 2851, "text": null }, { "code": "# Check if the given two number# are friendly pair or not.import math # Returns sum of all factors of n.def sumofFactors(n): # Traversing through all prime factors. res = 1 for i in range(2, int(math.sqrt(n)) + 1): count = 0; curr_sum = 1; curr_term = 1 while (n % i == 0): count += 1 # THE BELOW STATEMENT MAKES # IT BETTER THAN ABOVE METHOD # AS WE REDUCE VALUE OF n. n = n // i curr_term *= i curr_sum += curr_term res *= curr_sum # This condition is to handle # the case when n is a prime # number greater than 2. if (n >= 2): res *= (1 + n) return res # Function to return gcd of a and bdef gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Function to check if the given two# number are friendly pair or not.def checkFriendly(n, m): # Finding the sum of factors of n and m sumFactors_n = sumofFactors(n) sumFactors_m = sumofFactors(m) # Finding gcd of n and sum of its factors. gcd_n = gcd(n, sumFactors_n) # Finding gcd of m and sum of its factors. gcd_m = gcd(m, sumFactors_m) # checking is numerator and denominator # of abundancy index of both number are # equal or not. if (n // gcd_n == m // gcd_m and sumFactors_n // gcd_n == sumFactors_m // gcd_m): return True else: return False # Driver coden = 6; m = 28if(checkFriendly(n, m)): print(\"Yes\")else: print(\"No\") # This code is contributed by Anant Agarwal.", "e": 6512, "s": 4951, "text": null }, { "code": "// C# code to check if the// given two number are// friendly pair or notusing System; class GFG { // Returns sum of all //factors of n. static int sumofFactors(int n) { // Traversing through all // prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res; } // Function to return gcd // of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Function to check if the // given two number are // friendly pair or not static bool checkFriendly(int n, int m) { // Finding the sum of factors // of n and m int sumFactors_n = sumofFactors(n); int sumFactors_m = sumofFactors(m); // finding gcd of n and // sum of its factors. int gcd_n = gcd(n, sumFactors_n); // finding gcd of m and sum // of its factors. int gcd_m = gcd(m, sumFactors_m); // checking is numerator and // denominator of abundancy // index of both number are // equal or not if (n / gcd_n == m / gcd_m && sumFactors_n / gcd_n == sumFactors_m / gcd_m) return true; else return false; } // Driver code public static void Main (String[] args) { int n = 6, m = 28; if(checkFriendly(n, m)) Console.Write(\"Yes\\n\"); else Console.Write(\"No\\n\"); }} // This code is contributed by parshar...", "e": 8708, "s": 6512, "text": null }, { "code": "<?php// PHP program to check if the given// two number are friendly pair or not. // Returns sum of all factors of n.function sumofFactors( $n){ // Traversing through all // prime factors. $res = 1; for ($i = 2; $i <= sqrt($n); $i++) { $count = 0; $curr_sum = 1; $curr_term = 1; while ($n % $i == 0) { $count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. $n = $n / $i; $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if ($n >= 2) $res *= (1 + $n); return $res;} // Function to return// gcd of a and bfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Function to check if the given two// number are friendly pair or not.function checkFriendly($n, $m){ // Finding the sum of // factors of n and m $sumFactors_n = sumofFactors($n); $sumFactors_m = sumofFactors($m); // finding gcd of n and // sum of its factors. $gcd_n = gcd($n, $sumFactors_n); // finding gcd of m and // sum of its factors. $gcd_m = gcd($m, $sumFactors_m); // checking is numerator // and denominator of // abundancy index of // both number are equal // or not. if ($n / $gcd_n == $m / $gcd_m and $sumFactors_n / $gcd_n == $sumFactors_m / $gcd_m) return true; else return false;} // Driver code $n = 6; $m = 28; if(checkFriendly($n, $m)) echo \"Yes\" ; else echo \"No\"; // This code is contributed by anuj_67.?>", "e": 10461, "s": 8708, "text": null }, { "code": "<script> // JavaScript program to check if the given two number// are friendly pair or not. // Returns sum of all factors of n. function sumofFactors(n) { // Traversing through all prime factors. let res = 1; for (let i = 2; i <= Math.sqrt(n); i++) { let count = 0, curr_sum = 1; let curr_term = 1; while (n % i == 0) { count++; // THE BELOW STATEMENT MAKES // IT BETTER THAN ABOVE METHOD // AS WE REDUCE VALUE OF n. n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res; } // Function to return gcd of a and b function gcd(a, b) { if (a == 0) return b; return gcd(b % a, a); } // Function to check if the given two // number are friendly pair or not. function checkFriendly(n, m) { // Finding the sum of factors of n and m let sumFactors_n = sumofFactors(n); let sumFactors_m = sumofFactors(m); // finding gcd of n and sum of its factors. let gcd_n = gcd(n, sumFactors_n); // finding gcd of m and sum of its factors. let gcd_m = gcd(m, sumFactors_m); // checking is numerator and denominator of // abundancy index of both number are equal // or not. if (n / gcd_n == m / gcd_m && sumFactors_n / gcd_n == sumFactors_m / gcd_m) return true; else return false; } // Driver Code let n = 6, m = 28; if(checkFriendly(n, m)) document.write(\"Yes\\n\"); else document.write(\"No\\n\"); // This code is contributed by avijitmondal1998.</script>", "e": 12501, "s": 10461, "text": null }, { "code": null, "e": 12510, "s": 12501, "text": "Output " }, { "code": null, "e": 12514, "s": 12510, "text": "Yes" }, { "code": null, "e": 12565, "s": 12514, "text": "Time Complexity: O(√n log n) Auxiliary Space: O(1)" }, { "code": null, "e": 12832, "s": 12565, "text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 12841, "s": 12832, "text": "parashar" }, { "code": null, "e": 12846, "s": 12841, "text": "vt_m" }, { "code": null, "e": 12857, "s": 12846, "text": "nidhi_biet" }, { "code": null, "e": 12874, "s": 12857, "text": "avijitmondal1998" }, { "code": null, "e": 12888, "s": 12874, "text": "sumitgumber28" }, { "code": null, "e": 12901, "s": 12888, "text": "codewithmini" }, { "code": null, "e": 12910, "s": 12901, "text": "divisors" }, { "code": null, "e": 12918, "s": 12910, "text": "GCD-LCM" }, { "code": null, "e": 12932, "s": 12918, "text": "number-theory" }, { "code": null, "e": 12945, "s": 12932, "text": "Mathematical" }, { "code": null, "e": 12959, "s": 12945, "text": "number-theory" }, { "code": null, "e": 12972, "s": 12959, "text": "Mathematical" }, { "code": null, "e": 13070, "s": 12972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13102, "s": 13070, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 13148, "s": 13102, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 13192, "s": 13148, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 13234, "s": 13192, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 13266, "s": 13234, "text": "Check if a number is Palindrome" }, { "code": null, "e": 13301, "s": 13266, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 13326, "s": 13301, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 13367, "s": 13326, "text": "Median of two sorted arrays of same size" }, { "code": null, "e": 13429, "s": 13367, "text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms" } ]
Split a Numeric String into Fibonacci Sequence
12 Oct, 2021 Given a numeric string S representing a large number, the task is to form a Fibonacci Sequence of at least length 3 from the given string. If such a split is not possible, print -1. Examples: Input: S = “5712” Output: 5 7 12 Explanation: Since 5 + 7 = 12, the splits {5}, {7}, {12} forms a Fibonacci sequence. Input: S = “11235813′′ Output: 1 1 2 3 5 8 13 Approach: To solve the problem, the idea is to use Backtracking to find a sequence that follows the conditions of the Fibonacci Sequence. Follow the steps below to solve the problem: Initialize a vector seq[] to store the Fibonacci sequence.Initialize a variable pos which points to the current index of the string S, initially 0.Iterate over the indices [pos, length – 1]: Add the number S[pos: i] to the Fibonacci sequence seq if the length of seq is less than 2 or the current number is equal to the sum of the last two numbers of seq. Recur for the index i + 1 and proceed.If the last added number S[pos: i] does not form a Fibonacci sequence and returns false after recursion, then remove it from the seq.Otherwise, end the loop and return true as the Fibonacci sequence is formed.If pos exceeds the length of S, then: If the length of the sequence seq is greater than or equal to 3, then a Fibonacci sequence is found, hence return true.Otherwise, the Fibonacci sequence is not possible and hence returns false.Finally, if the length of seq is greater than or equal to 3, then print the numbers in seq as the required Fibonacci sequence or, otherwise print -1. Initialize a vector seq[] to store the Fibonacci sequence. Initialize a variable pos which points to the current index of the string S, initially 0. Iterate over the indices [pos, length – 1]: Add the number S[pos: i] to the Fibonacci sequence seq if the length of seq is less than 2 or the current number is equal to the sum of the last two numbers of seq. Recur for the index i + 1 and proceed.If the last added number S[pos: i] does not form a Fibonacci sequence and returns false after recursion, then remove it from the seq.Otherwise, end the loop and return true as the Fibonacci sequence is formed. Add the number S[pos: i] to the Fibonacci sequence seq if the length of seq is less than 2 or the current number is equal to the sum of the last two numbers of seq. Recur for the index i + 1 and proceed. If the last added number S[pos: i] does not form a Fibonacci sequence and returns false after recursion, then remove it from the seq. Otherwise, end the loop and return true as the Fibonacci sequence is formed. If pos exceeds the length of S, then: If the length of the sequence seq is greater than or equal to 3, then a Fibonacci sequence is found, hence return true.Otherwise, the Fibonacci sequence is not possible and hence returns false. If the length of the sequence seq is greater than or equal to 3, then a Fibonacci sequence is found, hence return true. Otherwise, the Fibonacci sequence is not possible and hence returns false. Finally, if the length of seq is greater than or equal to 3, then print the numbers in seq as the required Fibonacci sequence or, otherwise print -1. Below is the illustration of the recursive structure where only one branch is extended to get the result: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program of the above approach#include <bits/stdc++.h>using namespace std; #define LL long long // Function that returns true if// Fibonacci sequence is foundbool splitIntoFibonacciHelper(int pos, string S, vector<int>& seq){ // Base condition: // If pos is equal to length of S // and seq length is greater than 3 if (pos == S.length() and (seq.size() >= 3)) { // Return true return true; } // Stores current number LL num = 0; for (int i = pos; i < S.length(); i++) { // Add current digit to num num = num * 10 + (S[i] - '0'); // Avoid integer overflow if (num > INT_MAX) break; // Avoid leading zeros if (S[pos] == '0' and i > pos) break; // If current number is greater // than last two number of seq if (seq.size() > 2 and (num > ((LL)seq.back() + (LL)seq[seq.size() - 2]))) break; // If seq length is less // 2 or current number is // is equal to the last // two of the seq if (seq.size() < 2 or (num == ((LL)seq.back() + (LL)seq[seq.size() - 2]))) { // Add to the seq seq.push_back(num); // Recur for i+1 if (splitIntoFibonacciHelper(i + 1, S, seq)) return true; // Remove last added number seq.pop_back(); } } // If no sequence is found return false;} // Function that prints the Fibonacci// sequence from the split of string Svoid splitIntoFibonacci(string S){ // Initialize a vector to // store the sequence vector<int> seq; // Call helper function splitIntoFibonacciHelper(0, S, seq); // If sequence length is // greater than 3 if (seq.size() >= 3) { // Print the sequence for (int i : seq) cout << i << " "; } // If no sequence is found else { // Print -1 cout << -1; }} // Driver Codeint main(){ // Given String string S = "11235813"; // Function Call splitIntoFibonacci(S); return 0;} // Java program of the above approachimport java.util.*; class GFG{ // Function that returns true if// Fibonacci sequence is foundstatic boolean splitIntoFibonacciHelper(int pos, String S, ArrayList<Long> seq){ // Base condition: // If pos is equal to length of S // and seq length is greater than 3 if (pos == S.length() && (seq.size() >= 3)) { // Return true return true; } // Stores current number long num = 0; for(int i = pos; i < S.length(); i++) { // Add current digit to num num = num * 10 + (S.charAt(i) - '0'); // Avoid integer overflow if (num > Integer.MAX_VALUE) break; // Avoid leading zeros if (S.charAt(pos) == '0' && i > pos) break; // If current number is greater // than last two number of seq if (seq.size() > 2 && (num > ((long)seq.get(seq.size() - 1) + (long)seq.get(seq.size() - 2)))) break; // If seq length is less // 2 or current number is // is equal to the last // two of the seq if (seq.size() < 2 || (num == ((long)seq.get(seq.size() - 1) + (long)seq.get(seq.size() - 2)))) { // Add to the seq seq.add(num); // Recur for i+1 if (splitIntoFibonacciHelper(i + 1, S, seq)) return true; // Remove last added number seq.remove(seq.size() - 1); } } // If no sequence is found return false;} // Function that prints the Fibonacci// sequence from the split of string Sstatic void splitIntoFibonacci(String S){ // Initialize a vector to // store the sequence ArrayList<Long> seq = new ArrayList<>(); // Call helper function splitIntoFibonacciHelper(0, S, seq); // If sequence length is // greater than 3 if (seq.size() >= 3) { // Print the sequence for (int i = 0; i < seq.size(); i++) System.out.print(seq.get(i) + " "); } // If no sequence is found else { // Print -1 System.out.print("-1"); }} // Driver codepublic static void main(String[] args){ // Given String String S = "11235813"; // Function Call splitIntoFibonacci(S);}} // This code is contributed by offbeat # Python3 program of the above approachimport sys # Function that returns true if# Fibonacci sequence is founddef splitIntoFibonacciHelper(pos, S, seq): # Base condition: # If pos is equal to length of S # and seq length is greater than 3 if (pos == len(S) and (len(seq) >= 3)): # Return true return True # Stores current number num = 0 for i in range(pos, len(S)): # Add current digit to num num = num * 10 + (ord(S[i]) - ord('0')) # Avoid integer overflow if (num > sys.maxsize): break # Avoid leading zeros if (ord(S[pos]) == ord('0') and i > pos): break # If current number is greater # than last two number of seq if (len(seq) > 2 and (num > (seq[-1] + seq[len(seq) - 2]))): break # If seq length is less # 2 or current number is # is equal to the last # two of the seq if (len(seq) < 2 or (num == (seq[-1] + seq[len(seq) - 2]))): # Add to the seq seq.append(num) # Recur for i+1 if (splitIntoFibonacciHelper( i + 1, S, seq)): return True # Remove last added number seq.pop() # If no sequence is found return False # Function that prints the Fibonacci# sequence from the split of string Sdef splitIntoFibonacci(S): # Initialize a vector to # store the sequence seq = [] # Call helper function splitIntoFibonacciHelper(0, S, seq) # If sequence length is # greater than 3 if (len(seq) >= 3): # Print the sequence for i in seq: print(i, end = ' ') # If no sequence is found else: # Print -1 print(-1, end = '') # Driver Codeif __name__=='__main__': # Given String S = "11235813" # Function Call splitIntoFibonacci(S) # This code is contributed by pratham76 // C# program of the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function that returns true if// Fibonacci sequence is foundstatic bool splitIntoFibonacciHelper(int pos, string S, ArrayList seq){ // Base condition: // If pos is equal to length of S // and seq length is greater than 3 if (pos == S.Length && (seq.Count >= 3)) { // Return true return true; } // Stores current number long num = 0; for(int i = pos; i < S.Length; i++) { // Add current digit to num num = num * 10 + (S[i] - '0'); // Avoid integer overflow if (num > Int64.MaxValue) break; // Avoid leading zeros if (S[pos] == '0' && i > pos) break; // If current number is greater // than last two number of seq if (seq.Count> 2 && (num > ((long)seq[seq.Count - 1] + (long)seq[seq.Count - 2]))) break; // If seq length is less // 2 or current number is // is equal to the last // two of the seq if (seq.Count < 2 || (num == ((long)seq[seq.Count - 1] + (long)seq[seq.Count - 2]))) { // Add to the seq seq.Add(num); // Recur for i+1 if (splitIntoFibonacciHelper(i + 1, S, seq)) return true; // Remove last added number seq.Remove(seq.Count - 1); } } // If no sequence is found return false;} // Function that prints the Fibonacci// sequence from the split of string Sstatic void splitIntoFibonacci(string S){ // Initialize a vector to // store the sequence ArrayList seq = new ArrayList(); // Call helper function splitIntoFibonacciHelper(0, S, seq); // If sequence length is // greater than 3 if (seq.Count >= 3) { // Print the sequence for(int i = 0; i < seq.Count; i++) Console.Write(seq[i] + " "); } // If no sequence is found else { // Print -1 Console.Write("-1"); }} // Driver Codepublic static void Main(string[] args){ // Given String string S = "11235813"; // Function call splitIntoFibonacci(S);}} // This code is contributed by rutvik_56 <script> // Javascript program of the above approach // Function that returns true if // Fibonacci sequence is found function splitIntoFibonacciHelper(pos, S, seq) { // Base condition: // If pos is equal to length of S // and seq length is greater than 3 if (pos == S.length && (seq.length >= 3)) { // Return true return true; } // Stores current number let num = 0; for(let i = pos; i < S.length; i++) { // Add current digit to num num = num * 10 + (S[i] - '0'); // Avoid integer overflow if (num > Number.MAX_VALUE) break; // Avoid leading zeros if (S[pos] == '0' && i > pos) break; // If current number is greater // than last two number of seq if (seq.length> 2 && (num > (seq[seq.length - 1] + seq[seq.length - 2]))) break; // If seq length is less // 2 or current number is // is equal to the last // two of the seq if (seq.length < 2 || (num == (seq[seq.length - 1] + seq[seq.length - 2]))) { // Add to the seq seq.push(num); // Recur for i+1 if (splitIntoFibonacciHelper(i + 1, S, seq)) return true; // Remove last added number seq.pop(); } } // If no sequence is found return false; } // Function that prints the Fibonacci // sequence from the split of string S function splitIntoFibonacci(S) { // Initialize a vector to // store the sequence let seq = []; // Call helper function splitIntoFibonacciHelper(0, S, seq); // If sequence length is // greater than 3 if (seq.length >= 3) { // Print the sequence for(let i = 0; i < seq.length; i++) document.write(seq[i] + " "); } // If no sequence is found else { // Print -1 document.write("-1"); } } // Given String let S = "11235813"; // Function call splitIntoFibonacci(S); // This code is contributed by suresh07.</script> 1 1 2 3 5 8 13 Time Complexity: O(N2) Space Complexity: O(N) offbeat rutvik_56 pratham76 suresh07 Fibonacci Algorithms Backtracking Divide and Conquer Greedy Mathematical Recursion Strings Strings Greedy Mathematical Recursion Divide and Conquer Fibonacci Backtracking Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples Find if there is a path between two vertices in an undirected graph Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) N Queen Problem | Backtracking-3 The Knight's tour problem | Backtracking-1 Backtracking | Introduction
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Oct, 2021" }, { "code": null, "e": 236, "s": 54, "text": "Given a numeric string S representing a large number, the task is to form a Fibonacci Sequence of at least length 3 from the given string. If such a split is not possible, print -1." }, { "code": null, "e": 248, "s": 236, "text": "Examples: " }, { "code": null, "e": 366, "s": 248, "text": "Input: S = “5712” Output: 5 7 12 Explanation: Since 5 + 7 = 12, the splits {5}, {7}, {12} forms a Fibonacci sequence." }, { "code": null, "e": 413, "s": 366, "text": "Input: S = “11235813′′ Output: 1 1 2 3 5 8 13 " }, { "code": null, "e": 552, "s": 413, "text": "Approach: To solve the problem, the idea is to use Backtracking to find a sequence that follows the conditions of the Fibonacci Sequence. " }, { "code": null, "e": 599, "s": 552, "text": "Follow the steps below to solve the problem: " }, { "code": null, "e": 1583, "s": 599, "text": "Initialize a vector seq[] to store the Fibonacci sequence.Initialize a variable pos which points to the current index of the string S, initially 0.Iterate over the indices [pos, length – 1]: Add the number S[pos: i] to the Fibonacci sequence seq if the length of seq is less than 2 or the current number is equal to the sum of the last two numbers of seq. Recur for the index i + 1 and proceed.If the last added number S[pos: i] does not form a Fibonacci sequence and returns false after recursion, then remove it from the seq.Otherwise, end the loop and return true as the Fibonacci sequence is formed.If pos exceeds the length of S, then: If the length of the sequence seq is greater than or equal to 3, then a Fibonacci sequence is found, hence return true.Otherwise, the Fibonacci sequence is not possible and hence returns false.Finally, if the length of seq is greater than or equal to 3, then print the numbers in seq as the required Fibonacci sequence or, otherwise print -1." }, { "code": null, "e": 1642, "s": 1583, "text": "Initialize a vector seq[] to store the Fibonacci sequence." }, { "code": null, "e": 1732, "s": 1642, "text": "Initialize a variable pos which points to the current index of the string S, initially 0." }, { "code": null, "e": 2189, "s": 1732, "text": "Iterate over the indices [pos, length – 1]: Add the number S[pos: i] to the Fibonacci sequence seq if the length of seq is less than 2 or the current number is equal to the sum of the last two numbers of seq. Recur for the index i + 1 and proceed.If the last added number S[pos: i] does not form a Fibonacci sequence and returns false after recursion, then remove it from the seq.Otherwise, end the loop and return true as the Fibonacci sequence is formed." }, { "code": null, "e": 2393, "s": 2189, "text": "Add the number S[pos: i] to the Fibonacci sequence seq if the length of seq is less than 2 or the current number is equal to the sum of the last two numbers of seq. Recur for the index i + 1 and proceed." }, { "code": null, "e": 2527, "s": 2393, "text": "If the last added number S[pos: i] does not form a Fibonacci sequence and returns false after recursion, then remove it from the seq." }, { "code": null, "e": 2604, "s": 2527, "text": "Otherwise, end the loop and return true as the Fibonacci sequence is formed." }, { "code": null, "e": 2836, "s": 2604, "text": "If pos exceeds the length of S, then: If the length of the sequence seq is greater than or equal to 3, then a Fibonacci sequence is found, hence return true.Otherwise, the Fibonacci sequence is not possible and hence returns false." }, { "code": null, "e": 2956, "s": 2836, "text": "If the length of the sequence seq is greater than or equal to 3, then a Fibonacci sequence is found, hence return true." }, { "code": null, "e": 3031, "s": 2956, "text": "Otherwise, the Fibonacci sequence is not possible and hence returns false." }, { "code": null, "e": 3181, "s": 3031, "text": "Finally, if the length of seq is greater than or equal to 3, then print the numbers in seq as the required Fibonacci sequence or, otherwise print -1." }, { "code": null, "e": 3289, "s": 3181, "text": "Below is the illustration of the recursive structure where only one branch is extended to get the result: " }, { "code": null, "e": 3341, "s": 3289, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 3345, "s": 3341, "text": "C++" }, { "code": null, "e": 3350, "s": 3345, "text": "Java" }, { "code": null, "e": 3358, "s": 3350, "text": "Python3" }, { "code": null, "e": 3361, "s": 3358, "text": "C#" }, { "code": null, "e": 3372, "s": 3361, "text": "Javascript" }, { "code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; #define LL long long // Function that returns true if// Fibonacci sequence is foundbool splitIntoFibonacciHelper(int pos, string S, vector<int>& seq){ // Base condition: // If pos is equal to length of S // and seq length is greater than 3 if (pos == S.length() and (seq.size() >= 3)) { // Return true return true; } // Stores current number LL num = 0; for (int i = pos; i < S.length(); i++) { // Add current digit to num num = num * 10 + (S[i] - '0'); // Avoid integer overflow if (num > INT_MAX) break; // Avoid leading zeros if (S[pos] == '0' and i > pos) break; // If current number is greater // than last two number of seq if (seq.size() > 2 and (num > ((LL)seq.back() + (LL)seq[seq.size() - 2]))) break; // If seq length is less // 2 or current number is // is equal to the last // two of the seq if (seq.size() < 2 or (num == ((LL)seq.back() + (LL)seq[seq.size() - 2]))) { // Add to the seq seq.push_back(num); // Recur for i+1 if (splitIntoFibonacciHelper(i + 1, S, seq)) return true; // Remove last added number seq.pop_back(); } } // If no sequence is found return false;} // Function that prints the Fibonacci// sequence from the split of string Svoid splitIntoFibonacci(string S){ // Initialize a vector to // store the sequence vector<int> seq; // Call helper function splitIntoFibonacciHelper(0, S, seq); // If sequence length is // greater than 3 if (seq.size() >= 3) { // Print the sequence for (int i : seq) cout << i << \" \"; } // If no sequence is found else { // Print -1 cout << -1; }} // Driver Codeint main(){ // Given String string S = \"11235813\"; // Function Call splitIntoFibonacci(S); return 0;}", "e": 5718, "s": 3372, "text": null }, { "code": "// Java program of the above approachimport java.util.*; class GFG{ // Function that returns true if// Fibonacci sequence is foundstatic boolean splitIntoFibonacciHelper(int pos, String S, ArrayList<Long> seq){ // Base condition: // If pos is equal to length of S // and seq length is greater than 3 if (pos == S.length() && (seq.size() >= 3)) { // Return true return true; } // Stores current number long num = 0; for(int i = pos; i < S.length(); i++) { // Add current digit to num num = num * 10 + (S.charAt(i) - '0'); // Avoid integer overflow if (num > Integer.MAX_VALUE) break; // Avoid leading zeros if (S.charAt(pos) == '0' && i > pos) break; // If current number is greater // than last two number of seq if (seq.size() > 2 && (num > ((long)seq.get(seq.size() - 1) + (long)seq.get(seq.size() - 2)))) break; // If seq length is less // 2 or current number is // is equal to the last // two of the seq if (seq.size() < 2 || (num == ((long)seq.get(seq.size() - 1) + (long)seq.get(seq.size() - 2)))) { // Add to the seq seq.add(num); // Recur for i+1 if (splitIntoFibonacciHelper(i + 1, S, seq)) return true; // Remove last added number seq.remove(seq.size() - 1); } } // If no sequence is found return false;} // Function that prints the Fibonacci// sequence from the split of string Sstatic void splitIntoFibonacci(String S){ // Initialize a vector to // store the sequence ArrayList<Long> seq = new ArrayList<>(); // Call helper function splitIntoFibonacciHelper(0, S, seq); // If sequence length is // greater than 3 if (seq.size() >= 3) { // Print the sequence for (int i = 0; i < seq.size(); i++) System.out.print(seq.get(i) + \" \"); } // If no sequence is found else { // Print -1 System.out.print(\"-1\"); }} // Driver codepublic static void main(String[] args){ // Given String String S = \"11235813\"; // Function Call splitIntoFibonacci(S);}} // This code is contributed by offbeat", "e": 8218, "s": 5718, "text": null }, { "code": "# Python3 program of the above approachimport sys # Function that returns true if# Fibonacci sequence is founddef splitIntoFibonacciHelper(pos, S, seq): # Base condition: # If pos is equal to length of S # and seq length is greater than 3 if (pos == len(S) and (len(seq) >= 3)): # Return true return True # Stores current number num = 0 for i in range(pos, len(S)): # Add current digit to num num = num * 10 + (ord(S[i]) - ord('0')) # Avoid integer overflow if (num > sys.maxsize): break # Avoid leading zeros if (ord(S[pos]) == ord('0') and i > pos): break # If current number is greater # than last two number of seq if (len(seq) > 2 and (num > (seq[-1] + seq[len(seq) - 2]))): break # If seq length is less # 2 or current number is # is equal to the last # two of the seq if (len(seq) < 2 or (num == (seq[-1] + seq[len(seq) - 2]))): # Add to the seq seq.append(num) # Recur for i+1 if (splitIntoFibonacciHelper( i + 1, S, seq)): return True # Remove last added number seq.pop() # If no sequence is found return False # Function that prints the Fibonacci# sequence from the split of string Sdef splitIntoFibonacci(S): # Initialize a vector to # store the sequence seq = [] # Call helper function splitIntoFibonacciHelper(0, S, seq) # If sequence length is # greater than 3 if (len(seq) >= 3): # Print the sequence for i in seq: print(i, end = ' ') # If no sequence is found else: # Print -1 print(-1, end = '') # Driver Codeif __name__=='__main__': # Given String S = \"11235813\" # Function Call splitIntoFibonacci(S) # This code is contributed by pratham76", "e": 10262, "s": 8218, "text": null }, { "code": "// C# program of the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function that returns true if// Fibonacci sequence is foundstatic bool splitIntoFibonacciHelper(int pos, string S, ArrayList seq){ // Base condition: // If pos is equal to length of S // and seq length is greater than 3 if (pos == S.Length && (seq.Count >= 3)) { // Return true return true; } // Stores current number long num = 0; for(int i = pos; i < S.Length; i++) { // Add current digit to num num = num * 10 + (S[i] - '0'); // Avoid integer overflow if (num > Int64.MaxValue) break; // Avoid leading zeros if (S[pos] == '0' && i > pos) break; // If current number is greater // than last two number of seq if (seq.Count> 2 && (num > ((long)seq[seq.Count - 1] + (long)seq[seq.Count - 2]))) break; // If seq length is less // 2 or current number is // is equal to the last // two of the seq if (seq.Count < 2 || (num == ((long)seq[seq.Count - 1] + (long)seq[seq.Count - 2]))) { // Add to the seq seq.Add(num); // Recur for i+1 if (splitIntoFibonacciHelper(i + 1, S, seq)) return true; // Remove last added number seq.Remove(seq.Count - 1); } } // If no sequence is found return false;} // Function that prints the Fibonacci// sequence from the split of string Sstatic void splitIntoFibonacci(string S){ // Initialize a vector to // store the sequence ArrayList seq = new ArrayList(); // Call helper function splitIntoFibonacciHelper(0, S, seq); // If sequence length is // greater than 3 if (seq.Count >= 3) { // Print the sequence for(int i = 0; i < seq.Count; i++) Console.Write(seq[i] + \" \"); } // If no sequence is found else { // Print -1 Console.Write(\"-1\"); }} // Driver Codepublic static void Main(string[] args){ // Given String string S = \"11235813\"; // Function call splitIntoFibonacci(S);}} // This code is contributed by rutvik_56", "e": 12751, "s": 10262, "text": null }, { "code": "<script> // Javascript program of the above approach // Function that returns true if // Fibonacci sequence is found function splitIntoFibonacciHelper(pos, S, seq) { // Base condition: // If pos is equal to length of S // and seq length is greater than 3 if (pos == S.length && (seq.length >= 3)) { // Return true return true; } // Stores current number let num = 0; for(let i = pos; i < S.length; i++) { // Add current digit to num num = num * 10 + (S[i] - '0'); // Avoid integer overflow if (num > Number.MAX_VALUE) break; // Avoid leading zeros if (S[pos] == '0' && i > pos) break; // If current number is greater // than last two number of seq if (seq.length> 2 && (num > (seq[seq.length - 1] + seq[seq.length - 2]))) break; // If seq length is less // 2 or current number is // is equal to the last // two of the seq if (seq.length < 2 || (num == (seq[seq.length - 1] + seq[seq.length - 2]))) { // Add to the seq seq.push(num); // Recur for i+1 if (splitIntoFibonacciHelper(i + 1, S, seq)) return true; // Remove last added number seq.pop(); } } // If no sequence is found return false; } // Function that prints the Fibonacci // sequence from the split of string S function splitIntoFibonacci(S) { // Initialize a vector to // store the sequence let seq = []; // Call helper function splitIntoFibonacciHelper(0, S, seq); // If sequence length is // greater than 3 if (seq.length >= 3) { // Print the sequence for(let i = 0; i < seq.length; i++) document.write(seq[i] + \" \"); } // If no sequence is found else { // Print -1 document.write(\"-1\"); } } // Given String let S = \"11235813\"; // Function call splitIntoFibonacci(S); // This code is contributed by suresh07.</script>", "e": 15186, "s": 12751, "text": null }, { "code": null, "e": 15201, "s": 15186, "text": "1 1 2 3 5 8 13" }, { "code": null, "e": 15250, "s": 15203, "text": "Time Complexity: O(N2) Space Complexity: O(N) " }, { "code": null, "e": 15258, "s": 15250, "text": "offbeat" }, { "code": null, "e": 15268, "s": 15258, "text": "rutvik_56" }, { "code": null, "e": 15278, "s": 15268, "text": "pratham76" }, { "code": null, "e": 15287, "s": 15278, "text": "suresh07" }, { "code": null, "e": 15297, "s": 15287, "text": "Fibonacci" }, { "code": null, "e": 15308, "s": 15297, "text": "Algorithms" }, { "code": null, "e": 15321, "s": 15308, "text": "Backtracking" }, { "code": null, "e": 15340, "s": 15321, "text": "Divide and Conquer" }, { "code": null, "e": 15347, "s": 15340, "text": "Greedy" }, { "code": null, "e": 15360, "s": 15347, "text": "Mathematical" }, { "code": null, "e": 15370, "s": 15360, "text": "Recursion" }, { "code": null, "e": 15378, "s": 15370, "text": "Strings" }, { "code": null, "e": 15386, "s": 15378, "text": "Strings" }, { "code": null, "e": 15393, "s": 15386, "text": "Greedy" }, { "code": null, "e": 15406, "s": 15393, "text": "Mathematical" }, { "code": null, "e": 15416, "s": 15406, "text": "Recursion" }, { "code": null, "e": 15435, "s": 15416, "text": "Divide and Conquer" }, { "code": null, "e": 15445, "s": 15435, "text": "Fibonacci" }, { "code": null, "e": 15458, "s": 15445, "text": "Backtracking" }, { "code": null, "e": 15469, "s": 15458, "text": "Algorithms" }, { "code": null, "e": 15567, "s": 15469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15592, "s": 15567, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 15641, "s": 15592, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 15679, "s": 15641, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 15730, "s": 15679, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 15798, "s": 15730, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 15858, "s": 15798, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 15943, "s": 15858, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 15976, "s": 15943, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 16019, "s": 15976, "text": "The Knight's tour problem | Backtracking-1" } ]
Preorder Traversal of N-ary Tree Without Recursion
22 Jun, 2021 Given an n-ary tree, print preorder traversal of it. Example : Preorder traversal of below tree is A B K N M J F D G E C H I L The idea is to use stack like iterative preorder traversal of binary tree.1) Create an empty stack to store nodes. 2) Push the root node to the stack. 3) Run a loop while the stack is not empty ....a) Pop the top node from stack. ....b) Print the popped node. ....c) Store all the children of popped node onto the stack. We must store children from right to left so that leftmost node is popped first. 4) If stack is empty then we are done. C++ Java Python3 C# Javascript // C++ program to traverse an N-ary tree// without recursion#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node { char key; vector<Node*> child;}; // Utility function to create a new tree nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; return temp;} // Function to traverse tree without recursionvoid traverse_tree(struct Node* root){ // Stack to store the nodes stack<Node*> nodes; // push the current node onto the stack nodes.push(root); // loop while the stack is not empty while (!nodes.empty()) { // store the current node and pop it from the stack Node* curr = nodes.top(); nodes.pop(); // current node has been travarsed if(curr != NULL) { cout << curr->key << " "; // store all the childrent of current node from // right to left. vector<Node*>::iterator it = curr->child.end(); while (it != curr->child.begin()) { it--; nodes.push(*it); } } }}// Driver programint main(){ /* Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * / \ | | * N M O L */ Node* root = newNode('A'); (root->child).push_back(newNode('B')); (root->child).push_back(newNode('F')); (root->child).push_back(newNode('D')); (root->child).push_back(newNode('E')); (root->child[0]->child).push_back(newNode('K')); (root->child[0]->child).push_back(newNode('J')); (root->child[2]->child).push_back(newNode('G')); (root->child[3]->child).push_back(newNode('C')); (root->child[3]->child).push_back(newNode('H')); (root->child[3]->child).push_back(newNode('I')); (root->child[0]->child[0]->child).push_back(newNode('N')); (root->child[0]->child[0]->child).push_back(newNode('M')); (root->child[3]->child[0]->child).push_back(newNode('O')); (root->child[3]->child[2]->child).push_back(newNode('L')); traverse_tree(root); return 0;} // Java program to traverse an N-ary tree// without recursionimport java.util.ArrayList;import java.util.Stack; class GFG{ // Structure of a node of// an n-ary treestatic class Node{ char key; ArrayList<Node> child; public Node(char key) { this.key = key; child = new ArrayList<>(); }}; // Function to traverse tree without recursionstatic void traverse_tree(Node root){ // Stack to store the nodes Stack<Node> nodes = new Stack<>(); // push the current node onto the stack nodes.push(root); // Loop while the stack is not empty while (!nodes.isEmpty()) { // Store the current node and pop // it from the stack Node curr = nodes.pop(); // Current node has been travarsed if (curr != null) { System.out.print(curr.key + " "); // Store all the childrent of // current node from right to left. for(int i = curr.child.size() - 1; i >= 0; i--) { nodes.add(curr.child.get(i)); } } }} // Driver codepublic static void main(String[] args){ /* Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * / \ | | * N M O L */ Node root = new Node('A'); (root.child).add(new Node('B')); (root.child).add(new Node('F')); (root.child).add(new Node('D')); (root.child).add(new Node('E')); (root.child.get(0).child).add(new Node('K')); (root.child.get(0).child).add(new Node('J')); (root.child.get(2).child).add(new Node('G')); (root.child.get(3).child).add(new Node('C')); (root.child.get(3).child).add(new Node('H')); (root.child.get(3).child).add(new Node('I')); (root.child.get(0).child.get(0).child).add(new Node('N')); (root.child.get(0).child.get(0).child).add(new Node('M')); (root.child.get(3).child.get(0).child).add(new Node('O')); (root.child.get(3).child.get(2).child).add(new Node('L')); traverse_tree(root);}} // This code is contributed by sanjeev2552 # Python3 program to find height of# full binary tree# using preorder class newNode(): def __init__(self, key): self.key = key # all children are stored in a list self.child =[] # Function to traverse tree without recursiondef traverse_tree(root): # Stack to store the nodes nodes=[] # push the current node onto the stack nodes.append(root) # loop while the stack is not empty while (len(nodes)): # store the current node and pop it from the stack curr = nodes[0] nodes.pop(0) # current node has been travarsed print(curr.key,end=" ") # store all the childrent of current node from # right to left. for it in range(len(curr.child)-1,-1,-1): nodes.insert(0,curr.child[it]) # Driver program to test above functionsif __name__ == '__main__': """ Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * / \ | | * N M O L """ root = newNode('A') (root.child).append(newNode('B')) (root.child).append(newNode('F')) (root.child).append(newNode('D')) (root.child).append(newNode('E')) (root.child[0].child).append(newNode('K')) (root.child[0].child).append(newNode('J')) (root.child[2].child).append(newNode('G')) (root.child[3].child).append(newNode('C')) (root.child[3].child).append(newNode('H')) (root.child[3].child).append(newNode('I')) (root.child[0].child[0].child).append(newNode('N')) (root.child[0].child[0].child).append(newNode('M')) (root.child[3].child[0].child).append(newNode('O')) (root.child[3].child[2].child).append(newNode('L')) traverse_tree(root) # This code is contributed by SHUBHAMSINGH10 // C# program to traverse an N-ary tree// without recursionusing System;using System.Collections.Generic; public class GFG{ // Structure of a node of// an n-ary treepublic class Node{ public char key; public List<Node> child; public Node(char key) { this.key = key; child = new List<Node>(); }}; // Function to traverse tree without recursionstatic void traverse_tree(Node root){ // Stack to store the nodes Stack<Node> nodes = new Stack<Node>(); // push the current node onto the stack nodes.Push(root); // Loop while the stack is not empty while (nodes.Count!=0) { // Store the current node and pop // it from the stack Node curr = nodes.Pop(); // Current node has been travarsed if (curr != null) { Console.Write(curr.key + " "); // Store all the childrent of // current node from right to left. for(int i = curr.child.Count - 1; i >= 0; i--) { nodes.Push(curr.child[i]); } } }} // Driver codepublic static void Main(String[] args){ /* Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * / \ | | * N M O L */ Node root = new Node('A'); (root.child).Add(new Node('B')); (root.child).Add(new Node('F')); (root.child).Add(new Node('D')); (root.child).Add(new Node('E')); (root.child[0].child).Add(new Node('K')); (root.child[0].child).Add(new Node('J')); (root.child[2].child).Add(new Node('G')); (root.child[3].child).Add(new Node('C')); (root.child[3].child).Add(new Node('H')); (root.child[3].child).Add(new Node('I')); (root.child[0].child[0].child).Add(new Node('N')); (root.child[0].child[0].child).Add(new Node('M')); (root.child[3].child[0].child).Add(new Node('O')); (root.child[3].child[2].child).Add(new Node('L')); traverse_tree(root);}} // This code contributed by shikhasingrajput <script> // Javascript program to traverse an N-ary tree// without recursion // Structure of a node of// an n-ary treeclass Node{ constructor(key) { this.key = key; this.child = []; }}; // Function to traverse tree without recursionfunction traverse_tree(root){ // Stack to store the nodes var nodes = []; // Push the current node onto the stack nodes.push(root); // Loop while the stack is not empty while (nodes.length != 0) { // Store the current node and pop // it from the stack var curr = nodes.pop(); // Current node has been travarsed if (curr != null) { document.write(curr.key + " "); // Store all the childrent of // current node from right to left. for(var i = curr.child.length - 1; i >= 0; i--) { nodes.push(curr.child[i]); } } }} // Driver code/* Let us create below tree* A* / / \ \* B F D E* / \ | /|\* K J G C H I* / \ | |* N M O L*/var root = new Node('A');(root.child).push(new Node('B'));(root.child).push(new Node('F'));(root.child).push(new Node('D'));(root.child).push(new Node('E'));(root.child[0].child).push(new Node('K'));(root.child[0].child).push(new Node('J'));(root.child[2].child).push(new Node('G'));(root.child[3].child).push(new Node('C'));(root.child[3].child).push(new Node('H'));(root.child[3].child).push(new Node('I'));(root.child[0].child[0].child).push(new Node('N'));(root.child[0].child[0].child).push(new Node('M'));(root.child[3].child[0].child).push(new Node('O'));(root.child[3].child[2].child).push(new Node('L')); traverse_tree(root); // This code is contributed by rutvik_56 </script> A B K N M J F D G E C O H I L SHUBHAMSINGH10 Enigma341 sanjeev2552 shikhasingrajput rutvik_56 n-ary-tree Preorder Traversal Tree Traversals Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2021" }, { "code": null, "e": 105, "s": 52, "text": "Given an n-ary tree, print preorder traversal of it." }, { "code": null, "e": 117, "s": 105, "text": "Example : " }, { "code": null, "e": 183, "s": 117, "text": "Preorder traversal of below tree is A B K N M J F D G E C H I L " }, { "code": null, "e": 624, "s": 183, "text": "The idea is to use stack like iterative preorder traversal of binary tree.1) Create an empty stack to store nodes. 2) Push the root node to the stack. 3) Run a loop while the stack is not empty ....a) Pop the top node from stack. ....b) Print the popped node. ....c) Store all the children of popped node onto the stack. We must store children from right to left so that leftmost node is popped first. 4) If stack is empty then we are done." }, { "code": null, "e": 628, "s": 624, "text": "C++" }, { "code": null, "e": 633, "s": 628, "text": "Java" }, { "code": null, "e": 641, "s": 633, "text": "Python3" }, { "code": null, "e": 644, "s": 641, "text": "C#" }, { "code": null, "e": 655, "s": 644, "text": "Javascript" }, { "code": "// C++ program to traverse an N-ary tree// without recursion#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node { char key; vector<Node*> child;}; // Utility function to create a new tree nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; return temp;} // Function to traverse tree without recursionvoid traverse_tree(struct Node* root){ // Stack to store the nodes stack<Node*> nodes; // push the current node onto the stack nodes.push(root); // loop while the stack is not empty while (!nodes.empty()) { // store the current node and pop it from the stack Node* curr = nodes.top(); nodes.pop(); // current node has been travarsed if(curr != NULL) { cout << curr->key << \" \"; // store all the childrent of current node from // right to left. vector<Node*>::iterator it = curr->child.end(); while (it != curr->child.begin()) { it--; nodes.push(*it); } } }}// Driver programint main(){ /* Let us create below tree * A * / / \\ \\ * B F D E * / \\ | /|\\ * K J G C H I * / \\ | | * N M O L */ Node* root = newNode('A'); (root->child).push_back(newNode('B')); (root->child).push_back(newNode('F')); (root->child).push_back(newNode('D')); (root->child).push_back(newNode('E')); (root->child[0]->child).push_back(newNode('K')); (root->child[0]->child).push_back(newNode('J')); (root->child[2]->child).push_back(newNode('G')); (root->child[3]->child).push_back(newNode('C')); (root->child[3]->child).push_back(newNode('H')); (root->child[3]->child).push_back(newNode('I')); (root->child[0]->child[0]->child).push_back(newNode('N')); (root->child[0]->child[0]->child).push_back(newNode('M')); (root->child[3]->child[0]->child).push_back(newNode('O')); (root->child[3]->child[2]->child).push_back(newNode('L')); traverse_tree(root); return 0;}", "e": 2746, "s": 655, "text": null }, { "code": "// Java program to traverse an N-ary tree// without recursionimport java.util.ArrayList;import java.util.Stack; class GFG{ // Structure of a node of// an n-ary treestatic class Node{ char key; ArrayList<Node> child; public Node(char key) { this.key = key; child = new ArrayList<>(); }}; // Function to traverse tree without recursionstatic void traverse_tree(Node root){ // Stack to store the nodes Stack<Node> nodes = new Stack<>(); // push the current node onto the stack nodes.push(root); // Loop while the stack is not empty while (!nodes.isEmpty()) { // Store the current node and pop // it from the stack Node curr = nodes.pop(); // Current node has been travarsed if (curr != null) { System.out.print(curr.key + \" \"); // Store all the childrent of // current node from right to left. for(int i = curr.child.size() - 1; i >= 0; i--) { nodes.add(curr.child.get(i)); } } }} // Driver codepublic static void main(String[] args){ /* Let us create below tree * A * / / \\ \\ * B F D E * / \\ | /|\\ * K J G C H I * / \\ | | * N M O L */ Node root = new Node('A'); (root.child).add(new Node('B')); (root.child).add(new Node('F')); (root.child).add(new Node('D')); (root.child).add(new Node('E')); (root.child.get(0).child).add(new Node('K')); (root.child.get(0).child).add(new Node('J')); (root.child.get(2).child).add(new Node('G')); (root.child.get(3).child).add(new Node('C')); (root.child.get(3).child).add(new Node('H')); (root.child.get(3).child).add(new Node('I')); (root.child.get(0).child.get(0).child).add(new Node('N')); (root.child.get(0).child.get(0).child).add(new Node('M')); (root.child.get(3).child.get(0).child).add(new Node('O')); (root.child.get(3).child.get(2).child).add(new Node('L')); traverse_tree(root);}} // This code is contributed by sanjeev2552", "e": 4877, "s": 2746, "text": null }, { "code": "# Python3 program to find height of# full binary tree# using preorder class newNode(): def __init__(self, key): self.key = key # all children are stored in a list self.child =[] # Function to traverse tree without recursiondef traverse_tree(root): # Stack to store the nodes nodes=[] # push the current node onto the stack nodes.append(root) # loop while the stack is not empty while (len(nodes)): # store the current node and pop it from the stack curr = nodes[0] nodes.pop(0) # current node has been travarsed print(curr.key,end=\" \") # store all the childrent of current node from # right to left. for it in range(len(curr.child)-1,-1,-1): nodes.insert(0,curr.child[it]) # Driver program to test above functionsif __name__ == '__main__': \"\"\" Let us create below tree * A * / / \\ \\ * B F D E * / \\ | /|\\ * K J G C H I * / \\ | | * N M O L \"\"\" root = newNode('A') (root.child).append(newNode('B')) (root.child).append(newNode('F')) (root.child).append(newNode('D')) (root.child).append(newNode('E')) (root.child[0].child).append(newNode('K')) (root.child[0].child).append(newNode('J')) (root.child[2].child).append(newNode('G')) (root.child[3].child).append(newNode('C')) (root.child[3].child).append(newNode('H')) (root.child[3].child).append(newNode('I')) (root.child[0].child[0].child).append(newNode('N')) (root.child[0].child[0].child).append(newNode('M')) (root.child[3].child[0].child).append(newNode('O')) (root.child[3].child[2].child).append(newNode('L')) traverse_tree(root) # This code is contributed by SHUBHAMSINGH10", "e": 6708, "s": 4877, "text": null }, { "code": "// C# program to traverse an N-ary tree// without recursionusing System;using System.Collections.Generic; public class GFG{ // Structure of a node of// an n-ary treepublic class Node{ public char key; public List<Node> child; public Node(char key) { this.key = key; child = new List<Node>(); }}; // Function to traverse tree without recursionstatic void traverse_tree(Node root){ // Stack to store the nodes Stack<Node> nodes = new Stack<Node>(); // push the current node onto the stack nodes.Push(root); // Loop while the stack is not empty while (nodes.Count!=0) { // Store the current node and pop // it from the stack Node curr = nodes.Pop(); // Current node has been travarsed if (curr != null) { Console.Write(curr.key + \" \"); // Store all the childrent of // current node from right to left. for(int i = curr.child.Count - 1; i >= 0; i--) { nodes.Push(curr.child[i]); } } }} // Driver codepublic static void Main(String[] args){ /* Let us create below tree * A * / / \\ \\ * B F D E * / \\ | /|\\ * K J G C H I * / \\ | | * N M O L */ Node root = new Node('A'); (root.child).Add(new Node('B')); (root.child).Add(new Node('F')); (root.child).Add(new Node('D')); (root.child).Add(new Node('E')); (root.child[0].child).Add(new Node('K')); (root.child[0].child).Add(new Node('J')); (root.child[2].child).Add(new Node('G')); (root.child[3].child).Add(new Node('C')); (root.child[3].child).Add(new Node('H')); (root.child[3].child).Add(new Node('I')); (root.child[0].child[0].child).Add(new Node('N')); (root.child[0].child[0].child).Add(new Node('M')); (root.child[3].child[0].child).Add(new Node('O')); (root.child[3].child[2].child).Add(new Node('L')); traverse_tree(root);}} // This code contributed by shikhasingrajput", "e": 8789, "s": 6708, "text": null }, { "code": "<script> // Javascript program to traverse an N-ary tree// without recursion // Structure of a node of// an n-ary treeclass Node{ constructor(key) { this.key = key; this.child = []; }}; // Function to traverse tree without recursionfunction traverse_tree(root){ // Stack to store the nodes var nodes = []; // Push the current node onto the stack nodes.push(root); // Loop while the stack is not empty while (nodes.length != 0) { // Store the current node and pop // it from the stack var curr = nodes.pop(); // Current node has been travarsed if (curr != null) { document.write(curr.key + \" \"); // Store all the childrent of // current node from right to left. for(var i = curr.child.length - 1; i >= 0; i--) { nodes.push(curr.child[i]); } } }} // Driver code/* Let us create below tree* A* / / \\ \\* B F D E* / \\ | /|\\* K J G C H I* / \\ | |* N M O L*/var root = new Node('A');(root.child).push(new Node('B'));(root.child).push(new Node('F'));(root.child).push(new Node('D'));(root.child).push(new Node('E'));(root.child[0].child).push(new Node('K'));(root.child[0].child).push(new Node('J'));(root.child[2].child).push(new Node('G'));(root.child[3].child).push(new Node('C'));(root.child[3].child).push(new Node('H'));(root.child[3].child).push(new Node('I'));(root.child[0].child[0].child).push(new Node('N'));(root.child[0].child[0].child).push(new Node('M'));(root.child[3].child[0].child).push(new Node('O'));(root.child[3].child[2].child).push(new Node('L')); traverse_tree(root); // This code is contributed by rutvik_56 </script>", "e": 10617, "s": 8789, "text": null }, { "code": null, "e": 10647, "s": 10617, "text": "A B K N M J F D G E C O H I L" }, { "code": null, "e": 10664, "s": 10649, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 10674, "s": 10664, "text": "Enigma341" }, { "code": null, "e": 10686, "s": 10674, "text": "sanjeev2552" }, { "code": null, "e": 10703, "s": 10686, "text": "shikhasingrajput" }, { "code": null, "e": 10713, "s": 10703, "text": "rutvik_56" }, { "code": null, "e": 10724, "s": 10713, "text": "n-ary-tree" }, { "code": null, "e": 10743, "s": 10724, "text": "Preorder Traversal" }, { "code": null, "e": 10759, "s": 10743, "text": "Tree Traversals" }, { "code": null, "e": 10764, "s": 10759, "text": "Tree" }, { "code": null, "e": 10769, "s": 10764, "text": "Tree" } ]
Split a column in 2 columns using comma as separator - MySQL
For this, you can use substring_index() in MySQL. Let us create a table − mysql> create table demo79 -> ( -> fullname varchar(50) -> ); Query OK, 0 rows affected (0.64 Insert some records into the table with the help of insert command − mysql> insert into demo79 values("John,Smith"); Query OK, 1 row affected (0.09 mysql> insert into demo79 values("David,Miller"); Query OK, 1 row affected (0.11 mysql> insert into demo79 values("Chris,Brown"); Query OK, 1 row affected (0.07 Display records from the table using select statement − mysql> select *from demo79; This will produce the following output − +--------------+ | fullname | +--------------+| John,Smith | | David,Miller || Chris,Brown | +--------------+3 rows in set (0.00 sec) +--------------+ | David,Miller | +--------------+ Following is the query to split a column in 2 columns using comma as separator − mysql> select -> fullname, -> substring_index(fullname, ',', 1) First_Name, -> substring_index(fullname, ',', -1) Last_Name -> from demo79; This will produce the following output − | fullname | First_Name | Last_Name |+--------------+------------+-----------+ | John,Smith | John | Smith || David,Miller | David | Miller | | Chris,Brown | Chris | Brown |+--------------+------------+-----------+ 3 rows in set (0.00 sec) | fullname | First_Name | Last_Name | | John,Smith | John | Smith | | Chris,Brown | Chris | Brown | 3 rows in set (0.00 sec)
[ { "code": null, "e": 1261, "s": 1187, "text": "For this, you can use substring_index() in MySQL. Let us create a table −" }, { "code": null, "e": 1364, "s": 1261, "text": "mysql> create table demo79\n -> (\n -> fullname varchar(50)\n -> );\nQuery OK, 0 rows affected (0.64" }, { "code": null, "e": 1433, "s": 1364, "text": "Insert some records into the table with the help of insert command −" }, { "code": null, "e": 1675, "s": 1433, "text": "mysql> insert into demo79 values(\"John,Smith\");\nQuery OK, 1 row affected (0.09\n\nmysql> insert into demo79 values(\"David,Miller\");\nQuery OK, 1 row affected (0.11\n\nmysql> insert into demo79 values(\"Chris,Brown\");\nQuery OK, 1 row affected (0.07" }, { "code": null, "e": 1731, "s": 1675, "text": "Display records from the table using select statement −" }, { "code": null, "e": 1759, "s": 1731, "text": "mysql> select *from demo79;" }, { "code": null, "e": 1800, "s": 1759, "text": "This will produce the following output −" }, { "code": null, "e": 1941, "s": 1800, "text": "+--------------+\n| fullname |\n+--------------+| John,Smith |\n| David,Miller || Chris,Brown |\n+--------------+3 rows in set (0.00 sec)" }, { "code": null, "e": 1958, "s": 1941, "text": "+--------------+" }, { "code": null, "e": 1975, "s": 1958, "text": "| David,Miller |" }, { "code": null, "e": 1992, "s": 1975, "text": "+--------------+" }, { "code": null, "e": 2073, "s": 1992, "text": "Following is the query to split a column in 2 columns using comma as separator −" }, { "code": null, "e": 2225, "s": 2073, "text": "mysql> select\n -> fullname,\n -> substring_index(fullname, ',', 1) First_Name,\n -> substring_index(fullname, ',', -1) Last_Name\n -> from demo79;" }, { "code": null, "e": 2266, "s": 2225, "text": "This will produce the following output −" }, { "code": null, "e": 2540, "s": 2266, "text": "| fullname | First_Name | Last_Name |+--------------+------------+-----------+\n| John,Smith | John | Smith || David,Miller | David | Miller |\n| Chris,Brown | Chris | Brown |+--------------+------------+-----------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2582, "s": 2540, "text": "| fullname | First_Name | Last_Name |" }, { "code": null, "e": 2624, "s": 2582, "text": "| John,Smith | John | Smith |" }, { "code": null, "e": 2666, "s": 2624, "text": "| Chris,Brown | Chris | Brown |" }, { "code": null, "e": 2691, "s": 2666, "text": "3 rows in set (0.00 sec)" } ]
Some Basic Theorems on Trees
14 Feb, 2022 Tree:- A connected graph without any circuit is called a Tree. In other words, a tree is an undirected graph G that satisfies any of the following equivalent conditions: Any two vertices in G can be connected by a unique simple path. G is acyclic, and a simple cycle is formed if any edge is added to G. G is connected and has no cycles. G is connected but would become disconnected if any single edge is removed from G. G is connected and the 3-vertex complete graph K3 is not a minor of G. For Example: This Graph is a Tree: This Graph is not a Tree: Some theorems related to trees are: Theorem 1: Prove that for a tree (T), there is one and only one path between every pair of vertices in a tree. Proof: Since tree (T) is a connected graph, there exist at least one path between every pair of vertices in a tree (T). Now, suppose between two vertices a and b of the tree (T) there exist two paths. The union of these two paths will contain a circuit and tree (T) cannot be a tree. Hence the above statement is proved. Proof: Since tree (T) is a connected graph, there exist at least one path between every pair of vertices in a tree (T). Now, suppose between two vertices a and b of the tree (T) there exist two paths. The union of these two paths will contain a circuit and tree (T) cannot be a tree. Hence the above statement is proved. Figure 3: Tree(T) Theorem 2: If in a graph G there is one and only one path between every pair of vertices than graph G is a tree. Proof: There is the existence of a path between every pair of vertices so we assume that graph G is connected. A circuit in a graph implies that there is at least one pair of vertices a and b, such that there are two distinct paths between a and b. Since G has one and only one path between every pair of vertices. G cannot have any circuit. Hence graph G is a tree. Proof: There is the existence of a path between every pair of vertices so we assume that graph G is connected. A circuit in a graph implies that there is at least one pair of vertices a and b, such that there are two distinct paths between a and b. Since G has one and only one path between every pair of vertices. G cannot have any circuit. Hence graph G is a tree. Figure 4: Given graph G Theorem 3: Prove that a tree with n vertices has (n-1) edges. Proof: Let n be the number of vertices in a tree (T). If n=1, then the number of edges=0. If n=2 then the number of edges=1. If n=3 then the number of edges=2. Hence, the statement (or result) is true for n=1, 2, 3. Let the statement be true for n=m. Now we want to prove that it is true for n=m+1. Let be the edge connecting vertices say Vi and Vj. Since G is a tree, then there exists only one path between vertices Vi and Vj. Hence if we delete edge e it will be disconnected graph into two components G1 and G2 say. These components have less than m+1 vertices and there is no circuit and hence each component G1 and G2 have m1 and m2 vertices. Proof: Let n be the number of vertices in a tree (T). If n=1, then the number of edges=0. If n=2 then the number of edges=1. If n=3 then the number of edges=2. Hence, the statement (or result) is true for n=1, 2, 3. Let the statement be true for n=m. Now we want to prove that it is true for n=m+1. Let be the edge connecting vertices say Vi and Vj. Since G is a tree, then there exists only one path between vertices Vi and Vj. Hence if we delete edge e it will be disconnected graph into two components G1 and G2 say. These components have less than m+1 vertices and there is no circuit and hence each component G1 and G2 have m1 and m2 vertices. Now, the total no. of edges = (m1-1) + (m2-1) +1 = (m1+m2)-1 = m+1-1 = m. Hence for n=m+1 vertices there are m edges in a tree (T). By the mathematical induction the graph exactly has n-1 edges. Figure 5: Given a tree T Theorem 4: Prove that any connected graph G with n vertices and (n-1) edges is a tree. Proof: We know that the minimum number of edges required to make a graph of n vertices connected is (n-1) edges. We can observe that removal of one edge from the graph G will make it disconnected. Thus a connected graph of n vertices and (n-1) edges cannot have a circuit. Hence a graph G is a tree. Proof: We know that the minimum number of edges required to make a graph of n vertices connected is (n-1) edges. We can observe that removal of one edge from the graph G will make it disconnected. Thus a connected graph of n vertices and (n-1) edges cannot have a circuit. Hence a graph G is a tree. Figure 6: Graph G Theorem 5: Prove that a graph with n vertices, (n-1) edges and no circuit is a connected graph. Proof: Let the graph G is disconnected then there exist at least two components G1 and G2 say. Each of the component is circuit-less as G is circuit-less. Now to make a graph G connected we need to add one edge e between the vertices Vi and Vj, where Vi is the vertex of G1 and Vj is the vertex of component G2. Now the number of edges in G = (n – 1)+1 =n. Proof: Let the graph G is disconnected then there exist at least two components G1 and G2 say. Each of the component is circuit-less as G is circuit-less. Now to make a graph G connected we need to add one edge e between the vertices Vi and Vj, where Vi is the vertex of G1 and Vj is the vertex of component G2. Now the number of edges in G = (n – 1)+1 =n. Figure 7: Disconnected Graph Now, G is connected graph and circuit-less with n vertices and n edges, which is impossible because the connected circuit-less graph is a tree and tree with n vertices has (n-1) edges. So the graph G with n vertices, (n-1) edges and without circuit is connected. Hence the given statement is proved. Now, G is connected graph and circuit-less with n vertices and n edges, which is impossible because the connected circuit-less graph is a tree and tree with n vertices has (n-1) edges. So the graph G with n vertices, (n-1) edges and without circuit is connected. Hence the given statement is proved. Figure 8:Connected graph G Theorem 6: A graph G is a tree if and only if it is minimally connected. Proof: Let the graph G is minimally connected, i.e; removal of one edge make it disconnected. Therefore, there is no circuit. Hence graph G is a tree. Conversely, let the graph G is a tree i.e; there exists one and only one path between every pair of vertices and we know that removal of one edge from the path makes the graph disconnected. Hence graph G is minimally connected. Proof: Let the graph G is minimally connected, i.e; removal of one edge make it disconnected. Therefore, there is no circuit. Hence graph G is a tree. Conversely, let the graph G is a tree i.e; there exists one and only one path between every pair of vertices and we know that removal of one edge from the path makes the graph disconnected. Hence graph G is minimally connected. Figure 9: Minimally Connected Graph Theorem 7: Every tree with at-least two vertices has at-least two pendant vertices. Proof: Let the number of vertices in a given tree T is n and n>=2. Therefore the number of edges in a tree T=n-1 using above theorems. Proof: Let the number of vertices in a given tree T is n and n>=2. Therefore the number of edges in a tree T=n-1 using above theorems. summation of (deg(Vi)) = 2*e = 2*(n-1) =2n-2 The degree sum is to be divided among n vertices. Since a tree T is a connected graph, it cannot have a vertex of degree zero. Each vertex contributes at-least one to the above sum. Thus there must be at least two vertices of degree 1. Hence every tree with at-least two vertices have at-least two pendant vertices. Figure 10: Here a, b and d are pendant vertices of the given graph Theorem 8: Show that every tree has either one or two centres. Proof: We will use one observation that the maximum distance max d(v, w) from a given vertex v to any other vertex w occurs only when w is pendant vertex. Now, let T is a tree with n vertices (n>=2) T must have at least two pendant vertices. Delete all pendant vertices from T, then resulting graph T’ is still a tree. Again delete pendant vertices from T’ so that resulting T” is still a tree with same centers. Note that all vertices that T had as centers will still remain centers in T’–>T”–>T”’–>.... continue this process until the remaining tree has either one vertex or one edge. So in the end, if one vertex is there this implies tree T has one center. If one edge is there then tree T has two centers. Proof: We will use one observation that the maximum distance max d(v, w) from a given vertex v to any other vertex w occurs only when w is pendant vertex. Now, let T is a tree with n vertices (n>=2) T must have at least two pendant vertices. Delete all pendant vertices from T, then resulting graph T’ is still a tree. Again delete pendant vertices from T’ so that resulting T” is still a tree with same centers. Note that all vertices that T had as centers will still remain centers in T’–>T”–>T”’–>.... continue this process until the remaining tree has either one vertex or one edge. So in the end, if one vertex is there this implies tree T has one center. If one edge is there then tree T has two centers. Theorem 9: Prove the maximum number of vertices at level ‘L’ in a binary tree is , where L>=0. Proof: The given theorem is proved with the help of mathematical induction. At level 0 (L=0), there is only one vertex at level (L=1), there is only vertices. Now we assume that statement is true for the level (L-1). Therefore, maximum number of vertices on the level (L-1) is . Since we know that each vertex in a binary tree has the maximum of 2 vertices in next level, therefore the number of vertices on the level L is twice that of the level L-1. Hence at level L, the number of vertices is:- Proof: The given theorem is proved with the help of mathematical induction. At level 0 (L=0), there is only one vertex at level (L=1), there is only vertices. Now we assume that statement is true for the level (L-1). Therefore, maximum number of vertices on the level (L-1) is . Since we know that each vertex in a binary tree has the maximum of 2 vertices in next level, therefore the number of vertices on the level L is twice that of the level L-1. Hence at level L, the number of vertices is:- * = . jarretchng02 clintra arorakashish0911 Binary Tree Data Structures-Graph Trees Advanced Data Structure Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree) Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Segment Tree | Set 2 (Range Minimum Query) Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Introduction to Data Structures Introduction to Tree Data Structure
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Feb, 2022" }, { "code": null, "e": 226, "s": 54, "text": "Tree:- A connected graph without any circuit is called a Tree. In other words, a tree is an undirected graph G that satisfies any of the following equivalent conditions: " }, { "code": null, "e": 290, "s": 226, "text": "Any two vertices in G can be connected by a unique simple path." }, { "code": null, "e": 360, "s": 290, "text": "G is acyclic, and a simple cycle is formed if any edge is added to G." }, { "code": null, "e": 394, "s": 360, "text": "G is connected and has no cycles." }, { "code": null, "e": 477, "s": 394, "text": "G is connected but would become disconnected if any single edge is removed from G." }, { "code": null, "e": 548, "s": 477, "text": "G is connected and the 3-vertex complete graph K3 is not a minor of G." }, { "code": null, "e": 563, "s": 548, "text": "For Example: " }, { "code": null, "e": 587, "s": 563, "text": "This Graph is a Tree: " }, { "code": null, "e": 615, "s": 587, "text": "This Graph is not a Tree: " }, { "code": null, "e": 652, "s": 615, "text": "Some theorems related to trees are: " }, { "code": null, "e": 1088, "s": 654, "text": "Theorem 1: Prove that for a tree (T), there is one and only one path between every pair of vertices in a tree. Proof: Since tree (T) is a connected graph, there exist at least one path between every pair of vertices in a tree (T). Now, suppose between two vertices a and b of the tree (T) there exist two paths. The union of these two paths will contain a circuit and tree (T) cannot be a tree. Hence the above statement is proved. " }, { "code": null, "e": 1410, "s": 1088, "text": "Proof: Since tree (T) is a connected graph, there exist at least one path between every pair of vertices in a tree (T). Now, suppose between two vertices a and b of the tree (T) there exist two paths. The union of these two paths will contain a circuit and tree (T) cannot be a tree. Hence the above statement is proved. " }, { "code": null, "e": 1430, "s": 1412, "text": "Figure 3: Tree(T)" }, { "code": null, "e": 1912, "s": 1430, "text": "Theorem 2: If in a graph G there is one and only one path between every pair of vertices than graph G is a tree. Proof: There is the existence of a path between every pair of vertices so we assume that graph G is connected. A circuit in a graph implies that there is at least one pair of vertices a and b, such that there are two distinct paths between a and b. Since G has one and only one path between every pair of vertices. G cannot have any circuit. Hence graph G is a tree. " }, { "code": null, "e": 2280, "s": 1912, "text": "Proof: There is the existence of a path between every pair of vertices so we assume that graph G is connected. A circuit in a graph implies that there is at least one pair of vertices a and b, such that there are two distinct paths between a and b. Since G has one and only one path between every pair of vertices. G cannot have any circuit. Hence graph G is a tree. " }, { "code": null, "e": 2306, "s": 2282, "text": "Figure 4: Given graph G" }, { "code": null, "e": 3019, "s": 2306, "text": "Theorem 3: Prove that a tree with n vertices has (n-1) edges. Proof: Let n be the number of vertices in a tree (T). If n=1, then the number of edges=0. If n=2 then the number of edges=1. If n=3 then the number of edges=2. Hence, the statement (or result) is true for n=1, 2, 3. Let the statement be true for n=m. Now we want to prove that it is true for n=m+1. Let be the edge connecting vertices say Vi and Vj. Since G is a tree, then there exists only one path between vertices Vi and Vj. Hence if we delete edge e it will be disconnected graph into two components G1 and G2 say. These components have less than m+1 vertices and there is no circuit and hence each component G1 and G2 have m1 and m2 vertices. " }, { "code": null, "e": 3180, "s": 3019, "text": "Proof: Let n be the number of vertices in a tree (T). If n=1, then the number of edges=0. If n=2 then the number of edges=1. If n=3 then the number of edges=2. " }, { "code": null, "e": 3237, "s": 3180, "text": "Hence, the statement (or result) is true for n=1, 2, 3. " }, { "code": null, "e": 3321, "s": 3237, "text": "Let the statement be true for n=m. Now we want to prove that it is true for n=m+1. " }, { "code": null, "e": 3673, "s": 3321, "text": "Let be the edge connecting vertices say Vi and Vj. Since G is a tree, then there exists only one path between vertices Vi and Vj. Hence if we delete edge e it will be disconnected graph into two components G1 and G2 say. These components have less than m+1 vertices and there is no circuit and hence each component G1 and G2 have m1 and m2 vertices. " }, { "code": null, "e": 3831, "s": 3673, "text": "Now, the total no. of edges = (m1-1) + (m2-1) +1\n = (m1+m2)-1\n = m+1-1\n = m." }, { "code": null, "e": 3954, "s": 3831, "text": "Hence for n=m+1 vertices there are m edges in a tree (T). By the mathematical induction the graph exactly has n-1 edges. " }, { "code": null, "e": 3981, "s": 3956, "text": "Figure 5: Given a tree T" }, { "code": null, "e": 4370, "s": 3981, "text": "Theorem 4: Prove that any connected graph G with n vertices and (n-1) edges is a tree. Proof: We know that the minimum number of edges required to make a graph of n vertices connected is (n-1) edges. We can observe that removal of one edge from the graph G will make it disconnected. Thus a connected graph of n vertices and (n-1) edges cannot have a circuit. Hence a graph G is a tree. " }, { "code": null, "e": 4671, "s": 4370, "text": "Proof: We know that the minimum number of edges required to make a graph of n vertices connected is (n-1) edges. We can observe that removal of one edge from the graph G will make it disconnected. Thus a connected graph of n vertices and (n-1) edges cannot have a circuit. Hence a graph G is a tree. " }, { "code": null, "e": 4691, "s": 4673, "text": "Figure 6: Graph G" }, { "code": null, "e": 5146, "s": 4691, "text": "Theorem 5: Prove that a graph with n vertices, (n-1) edges and no circuit is a connected graph. Proof: Let the graph G is disconnected then there exist at least two components G1 and G2 say. Each of the component is circuit-less as G is circuit-less. Now to make a graph G connected we need to add one edge e between the vertices Vi and Vj, where Vi is the vertex of G1 and Vj is the vertex of component G2. Now the number of edges in G = (n – 1)+1 =n. " }, { "code": null, "e": 5504, "s": 5146, "text": "Proof: Let the graph G is disconnected then there exist at least two components G1 and G2 say. Each of the component is circuit-less as G is circuit-less. Now to make a graph G connected we need to add one edge e between the vertices Vi and Vj, where Vi is the vertex of G1 and Vj is the vertex of component G2. Now the number of edges in G = (n – 1)+1 =n. " }, { "code": null, "e": 5535, "s": 5506, "text": "Figure 7: Disconnected Graph" }, { "code": null, "e": 5837, "s": 5535, "text": "Now, G is connected graph and circuit-less with n vertices and n edges, which is impossible because the connected circuit-less graph is a tree and tree with n vertices has (n-1) edges. So the graph G with n vertices, (n-1) edges and without circuit is connected. Hence the given statement is proved. " }, { "code": null, "e": 6138, "s": 5837, "text": "Now, G is connected graph and circuit-less with n vertices and n edges, which is impossible because the connected circuit-less graph is a tree and tree with n vertices has (n-1) edges. So the graph G with n vertices, (n-1) edges and without circuit is connected. Hence the given statement is proved. " }, { "code": null, "e": 6167, "s": 6140, "text": "Figure 8:Connected graph G" }, { "code": null, "e": 6621, "s": 6167, "text": "Theorem 6: A graph G is a tree if and only if it is minimally connected. Proof: Let the graph G is minimally connected, i.e; removal of one edge make it disconnected. Therefore, there is no circuit. Hence graph G is a tree. Conversely, let the graph G is a tree i.e; there exists one and only one path between every pair of vertices and we know that removal of one edge from the path makes the graph disconnected. Hence graph G is minimally connected. " }, { "code": null, "e": 7001, "s": 6621, "text": "Proof: Let the graph G is minimally connected, i.e; removal of one edge make it disconnected. Therefore, there is no circuit. Hence graph G is a tree. Conversely, let the graph G is a tree i.e; there exists one and only one path between every pair of vertices and we know that removal of one edge from the path makes the graph disconnected. Hence graph G is minimally connected. " }, { "code": null, "e": 7039, "s": 7003, "text": "Figure 9: Minimally Connected Graph" }, { "code": null, "e": 7260, "s": 7039, "text": "Theorem 7: Every tree with at-least two vertices has at-least two pendant vertices. Proof: Let the number of vertices in a given tree T is n and n>=2. Therefore the number of edges in a tree T=n-1 using above theorems. " }, { "code": null, "e": 7396, "s": 7260, "text": "Proof: Let the number of vertices in a given tree T is n and n>=2. Therefore the number of edges in a tree T=n-1 using above theorems. " }, { "code": null, "e": 7489, "s": 7398, "text": "summation of (deg(Vi)) = 2*e\n = 2*(n-1)\n =2n-2" }, { "code": null, "e": 7807, "s": 7489, "text": "The degree sum is to be divided among n vertices. Since a tree T is a connected graph, it cannot have a vertex of degree zero. Each vertex contributes at-least one to the above sum. Thus there must be at least two vertices of degree 1. Hence every tree with at-least two vertices have at-least two pendant vertices. " }, { "code": null, "e": 7876, "s": 7809, "text": "Figure 10: Here a, b and d are pendant vertices of the given graph" }, { "code": null, "e": 8650, "s": 7876, "text": "Theorem 8: Show that every tree has either one or two centres. Proof: We will use one observation that the maximum distance max d(v, w) from a given vertex v to any other vertex w occurs only when w is pendant vertex. Now, let T is a tree with n vertices (n>=2) T must have at least two pendant vertices. Delete all pendant vertices from T, then resulting graph T’ is still a tree. Again delete pendant vertices from T’ so that resulting T” is still a tree with same centers. Note that all vertices that T had as centers will still remain centers in T’–>T”–>T”’–>.... continue this process until the remaining tree has either one vertex or one edge. So in the end, if one vertex is there this implies tree T has one center. If one edge is there then tree T has two centers." }, { "code": null, "e": 8806, "s": 8650, "text": "Proof: We will use one observation that the maximum distance max d(v, w) from a given vertex v to any other vertex w occurs only when w is pendant vertex. " }, { "code": null, "e": 8851, "s": 8806, "text": "Now, let T is a tree with n vertices (n>=2) " }, { "code": null, "e": 9066, "s": 8851, "text": "T must have at least two pendant vertices. Delete all pendant vertices from T, then resulting graph T’ is still a tree. Again delete pendant vertices from T’ so that resulting T” is still a tree with same centers. " }, { "code": null, "e": 9159, "s": 9066, "text": "Note that all vertices that T had as centers will still remain centers in T’–>T”–>T”’–>.... " }, { "code": null, "e": 9365, "s": 9159, "text": "continue this process until the remaining tree has either one vertex or one edge. So in the end, if one vertex is there this implies tree T has one center. If one edge is there then tree T has two centers." }, { "code": null, "e": 9960, "s": 9365, "text": "Theorem 9: Prove the maximum number of vertices at level ‘L’ in a binary tree is , where L>=0. Proof: The given theorem is proved with the help of mathematical induction. At level 0 (L=0), there is only one vertex at level (L=1), there is only vertices. Now we assume that statement is true for the level (L-1). Therefore, maximum number of vertices on the level (L-1) is . Since we know that each vertex in a binary tree has the maximum of 2 vertices in next level, therefore the number of vertices on the level L is twice that of the level L-1. Hence at level L, the number of vertices is:- " }, { "code": null, "e": 10120, "s": 9960, "text": "Proof: The given theorem is proved with the help of mathematical induction. At level 0 (L=0), there is only one vertex at level (L=1), there is only vertices. " }, { "code": null, "e": 10179, "s": 10120, "text": "Now we assume that statement is true for the level (L-1). " }, { "code": null, "e": 10415, "s": 10179, "text": "Therefore, maximum number of vertices on the level (L-1) is . Since we know that each vertex in a binary tree has the maximum of 2 vertices in next level, therefore the number of vertices on the level L is twice that of the level L-1. " }, { "code": null, "e": 10463, "s": 10415, "text": "Hence at level L, the number of vertices is:- " }, { "code": null, "e": 10469, "s": 10463, "text": "* = ." }, { "code": null, "e": 10484, "s": 10471, "text": "jarretchng02" }, { "code": null, "e": 10492, "s": 10484, "text": "clintra" }, { "code": null, "e": 10509, "s": 10492, "text": "arorakashish0911" }, { "code": null, "e": 10521, "s": 10509, "text": "Binary Tree" }, { "code": null, "e": 10543, "s": 10521, "text": "Data Structures-Graph" }, { "code": null, "e": 10549, "s": 10543, "text": "Trees" }, { "code": null, "e": 10573, "s": 10549, "text": "Advanced Data Structure" }, { "code": null, "e": 10578, "s": 10573, "text": "Tree" }, { "code": null, "e": 10583, "s": 10578, "text": "Tree" }, { "code": null, "e": 10681, "s": 10583, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10761, "s": 10681, "text": "Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)" }, { "code": null, "e": 10790, "s": 10761, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 10832, "s": 10790, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 10878, "s": 10832, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 10921, "s": 10878, "text": "Segment Tree | Set 2 (Range Minimum Query)" }, { "code": null, "e": 10971, "s": 10921, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 11006, "s": 10971, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 11040, "s": 11006, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 11072, "s": 11040, "text": "Introduction to Data Structures" } ]
Prime Number of Set Bits in Binary Representation | Set 2
24 May, 2021 Given two integers ‘L’ and ‘R’, we need to write a program that finds the count of numbers having the prime number of set bits in their binary representation in the range [L, R]. Examples: Input : 6 10 Output : 4 6 -> 110 (2 set bits, 2 is prime) 7 -> 111 (3 set bits, 3 is prime) 9 -> 1001 (2 set bits , 2 is prime) 10->1010 (2 set bits , 2 is prime) Input : 10 15 Output : 5 10 -> 1010(2 number of set bits) 11 -> 1011(3 number of set bits) 12 -> 1100(2 number of set bits) 13 -> 1101(3 number of set bits) 14 -> 1110(3 number of set bits) 15 -> 1111(4 number of set bits) Hence total count is 5 For each number in the range [L, R], we calculate the number of set bits. Using Sieve of Eratosthenes we generate a prime array up to the last number in the range (i.e. R). If the number of set bits is prime, we increase the count of the numbers and print it. C++ Java Python C# PHP Javascript // C++ code to find count of numbers// having prime number of set bits// in their binary representation in// the range [L, R]#include<bits/stdc++.h>using namespace std;#include <cmath> // Function to create an array of prime// numbers upto number 'n'vector<int> SieveOfEratosthenes(int n){ // Create a boolean array "prime[0..n]" // and initialize all entries it as false. // A value in prime[i] will finally be // true if i is Not a prime, else false. bool prime[n + 1]; memset(prime, false, sizeof(prime)); for(int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == false) // Update all multiples of p for (int i = p * 2; i < n + 1; i += p) prime[i] = true; } vector<int> lis; // Append all the prime numbers to the list for (int p = 2; p <=n; p++) if (prime[p] == false) lis.push_back(p); return lis;} // Utility function to count// the number of set bitsint setBits(int n){ return __builtin_popcount (n);} // Driver codeint main (){ int x = 4, y = 8; int count = 0; // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. vector<int> primeArr = SieveOfEratosthenes(ceil(log2(y))); for(int i = x; i < y + 1; i++) { int temp = setBits(i); for(int j=0;j< primeArr.size();j++) {if (temp == primeArr[j]) {count += 1; break; } } } cout << count << endl; return 0;} // This code is contributed by mits // Java code to find count of numbers having// prime number of set bits in their binary // representation in the range[L, R]import java.util.*;import java.lang.Math; class GFG{ // function to create an array of prime// numbers upto number 'n'static ArrayList<Integer> SieveOfEratosthenes(int n){ // Create a boolean array "prime[0..n]" and initialize // all entries it as false. A value in prime[i] will // finally be true if i is Not a prime, else false. boolean[] prime = new boolean[n + 1]; for(int p = 2; p * p <= n;p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == false) // Update all multiples of p for (int i = p * 2; i < n + 1; i += p) prime[i] = true; } ArrayList<Integer> lis = new ArrayList<Integer>(); // append all the prime numbers to the list for (int p = 2; p <=n; p++) if (prime[p] == false) lis.add(p); return lis;} // utility function to count the number of set bitsstatic int setBits(int n){ return Integer.bitCount(n);}public static int log2(int x){ return (int) (Math.log(x) / Math.log(2) + 1e-10);} // Driver codepublic static void main (String[] args){ int x = 4, y = 8; int count = 0; ArrayList<Integer> primeArr = new ArrayList<Integer>(); // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. primeArr = SieveOfEratosthenes((int)Math.ceil(log2(y))); for(int i = x; i < y + 1; i++) { int temp = setBits(i); if(primeArr.contains(temp)) count += 1; } System.out.println(count);}} // This code is contributed by mits. # Python code to find count of numbers having prime number# of set bits in their binary representation in the range# [L, R] # Function to create an array of prime# numbers upto number 'n'import math as m def SieveOfEratosthenes(n): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n+1)] p = 2 while(p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n+1, p): prime[i] = False p += 1 lis = [] # Append all the prime numbers to the list for p in range(2, n+1): if prime[p]: lis.append(p) return lis # Utility function to count the number of set bitsdef setBits(n): return bin(n)[2:].count('1') # Driver programif __name__ == "__main__": x, y = [4, 8] count = 0 # Here prime numbers are checked till the maximum # number of bits possible because that the maximum # bit sum possible is the number of bits itself. primeArr = SieveOfEratosthenes(int(m.ceil(m.log(y,2)))) for i in range(x, y+1): temp = setBits(i) if temp in primeArr: count += 1 print(count) // C# code to find count of numbers having prime number// of set bits in their binary representation in the range// [L, R]using System;using System.Linq;using System.Collections;class GFG{ // Function to create an array of prime// numbers upto number 'n'static ArrayList SieveOfEratosthenes(int n){ // Create a boolean array "prime[0..n]" and initialize // all entries it as false. A value in prime[i] will // finally be true if i is Not a prime, else false. bool[] prime = new bool[n+1]; for(int p=2;p * p <= n;p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == false) // Update all multiples of p for (int i=p * 2;i<n+1;i+=p) prime[i] = true; } ArrayList lis = new ArrayList(); // append all the prime numbers to the list for (int p=2;p<=n;p++) if (prime[p]==false) lis.Add(p); return lis;} // Utility function to count the number of set bitsstatic int setBits(int n){ return (int)Convert.ToString(n, 2).Count(c => c == '1');} // Driver programpublic static void Main () { int x=4, y=8; int count = 0; ArrayList primeArr=new ArrayList(); // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. primeArr = SieveOfEratosthenes(Convert.ToInt32(Math.Ceiling(Math.Log(y,2.0)))); for(int i=x;i<y+1;i++){ int temp = setBits(i); if(primeArr.Contains(temp)) count += 1; } Console.WriteLine(count);}}// This code is contributed by mits <?php// PHP code to find count of numbers having prime number// of set bits in their binary representation in the range// [L, R] // Function to create an array of prime// numbers upto number 'n'function SieveOfEratosthenes($n){ // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. $prime = array_fill(0,$n+1,true); for($p = 2;$p * $p <= $n;$p++) { // If prime[p] is not changed, then it is a prime if ($prime[$p] == true) // Update all multiples of p for($i=$p * 2;$i<$n+1;$i+=$p) $prime[$i] = false; } $lis = array(); // Append all the prime numbers to the list for($p=2;$p<=$n;$p++) if ($prime[$p]) array_push($lis,$p); return $lis;} // Utility function to count the number of set bitsfunction setBits($n){ $cnt=0; while($n){if($n&1)$cnt++;$n>>=1;}; return $cnt;} // Driver program $x = 4; $y = 8; $count = 0; // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. $primeArr = SieveOfEratosthenes(ceil(log($y,2))); for ($i=$x;$i<$y+1;$i++) { $temp = setBits($i); if(in_array($temp, $primeArr)) $count += 1; } print($count); // This code is contributed by mits?> <script>// Javascript code to find count of numbers having prime number// of set bits in their binary representation in the range// [L, R] // Function to create an array of prime// numbers upto number 'n'function SieveOfEratosthenes(n){ // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. let prime = new Array(n+1).fill(true); for(let p = 2;p * p <= n;p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) // Update all multiples of p for(let i=p * 2;i<n+1;i+=p) prime[i] = false; } let lis = new Array(); // Append all the prime numbers to the list for(let p=2;p<=n;p++) if (prime[p]) lis.push(p); return lis;} // Utility function to count the number of set bitsfunction setBits(n){ let cnt=0; while(n){if(n&1)cnt++;n>>=1;}; return cnt;} // Driver program let x = 4; let y = 8; let count = 0; // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. let primeArr = SieveOfEratosthenes(Math.ceil(Math.log(y,2))); for (let i=x;i<y+1;i++) { let temp = setBits(i); if(primeArr.includes(temp)) count += 1; } document.write(count); // This code is contributed by gfgking</script> Output: 3 This article is contributed by Saisankar Gochhayat and Harshit Sidhwa. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar deepankkansal gfgking Amazon binary-representation Prime Number sieve Mathematical Amazon Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 May, 2021" }, { "code": null, "e": 231, "s": 52, "text": "Given two integers ‘L’ and ‘R’, we need to write a program that finds the count of numbers having the prime number of set bits in their binary representation in the range [L, R]." }, { "code": null, "e": 243, "s": 231, "text": "Examples: " }, { "code": null, "e": 654, "s": 243, "text": "Input : 6 10\nOutput : 4\n6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n9 -> 1001 (2 set bits , 2 is prime)\n10->1010 (2 set bits , 2 is prime)\n\nInput : 10 15\nOutput : 5\n10 -> 1010(2 number of set bits)\n11 -> 1011(3 number of set bits)\n12 -> 1100(2 number of set bits)\n13 -> 1101(3 number of set bits)\n14 -> 1110(3 number of set bits)\n15 -> 1111(4 number of set bits)\nHence total count is 5 " }, { "code": null, "e": 916, "s": 654, "text": "For each number in the range [L, R], we calculate the number of set bits. Using Sieve of Eratosthenes we generate a prime array up to the last number in the range (i.e. R). If the number of set bits is prime, we increase the count of the numbers and print it. " }, { "code": null, "e": 920, "s": 916, "text": "C++" }, { "code": null, "e": 925, "s": 920, "text": "Java" }, { "code": null, "e": 932, "s": 925, "text": "Python" }, { "code": null, "e": 935, "s": 932, "text": "C#" }, { "code": null, "e": 939, "s": 935, "text": "PHP" }, { "code": null, "e": 950, "s": 939, "text": "Javascript" }, { "code": "// C++ code to find count of numbers// having prime number of set bits// in their binary representation in// the range [L, R]#include<bits/stdc++.h>using namespace std;#include <cmath> // Function to create an array of prime// numbers upto number 'n'vector<int> SieveOfEratosthenes(int n){ // Create a boolean array \"prime[0..n]\" // and initialize all entries it as false. // A value in prime[i] will finally be // true if i is Not a prime, else false. bool prime[n + 1]; memset(prime, false, sizeof(prime)); for(int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == false) // Update all multiples of p for (int i = p * 2; i < n + 1; i += p) prime[i] = true; } vector<int> lis; // Append all the prime numbers to the list for (int p = 2; p <=n; p++) if (prime[p] == false) lis.push_back(p); return lis;} // Utility function to count// the number of set bitsint setBits(int n){ return __builtin_popcount (n);} // Driver codeint main (){ int x = 4, y = 8; int count = 0; // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. vector<int> primeArr = SieveOfEratosthenes(ceil(log2(y))); for(int i = x; i < y + 1; i++) { int temp = setBits(i); for(int j=0;j< primeArr.size();j++) {if (temp == primeArr[j]) {count += 1; break; } } } cout << count << endl; return 0;} // This code is contributed by mits", "e": 2621, "s": 950, "text": null }, { "code": "// Java code to find count of numbers having// prime number of set bits in their binary // representation in the range[L, R]import java.util.*;import java.lang.Math; class GFG{ // function to create an array of prime// numbers upto number 'n'static ArrayList<Integer> SieveOfEratosthenes(int n){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as false. A value in prime[i] will // finally be true if i is Not a prime, else false. boolean[] prime = new boolean[n + 1]; for(int p = 2; p * p <= n;p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == false) // Update all multiples of p for (int i = p * 2; i < n + 1; i += p) prime[i] = true; } ArrayList<Integer> lis = new ArrayList<Integer>(); // append all the prime numbers to the list for (int p = 2; p <=n; p++) if (prime[p] == false) lis.add(p); return lis;} // utility function to count the number of set bitsstatic int setBits(int n){ return Integer.bitCount(n);}public static int log2(int x){ return (int) (Math.log(x) / Math.log(2) + 1e-10);} // Driver codepublic static void main (String[] args){ int x = 4, y = 8; int count = 0; ArrayList<Integer> primeArr = new ArrayList<Integer>(); // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. primeArr = SieveOfEratosthenes((int)Math.ceil(log2(y))); for(int i = x; i < y + 1; i++) { int temp = setBits(i); if(primeArr.contains(temp)) count += 1; } System.out.println(count);}} // This code is contributed by mits.", "e": 4370, "s": 2621, "text": null }, { "code": "# Python code to find count of numbers having prime number# of set bits in their binary representation in the range# [L, R] # Function to create an array of prime# numbers upto number 'n'import math as m def SieveOfEratosthenes(n): # Create a boolean array \"prime[0..n]\" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n+1)] p = 2 while(p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n+1, p): prime[i] = False p += 1 lis = [] # Append all the prime numbers to the list for p in range(2, n+1): if prime[p]: lis.append(p) return lis # Utility function to count the number of set bitsdef setBits(n): return bin(n)[2:].count('1') # Driver programif __name__ == \"__main__\": x, y = [4, 8] count = 0 # Here prime numbers are checked till the maximum # number of bits possible because that the maximum # bit sum possible is the number of bits itself. primeArr = SieveOfEratosthenes(int(m.ceil(m.log(y,2)))) for i in range(x, y+1): temp = setBits(i) if temp in primeArr: count += 1 print(count)", "e": 5722, "s": 4370, "text": null }, { "code": "// C# code to find count of numbers having prime number// of set bits in their binary representation in the range// [L, R]using System;using System.Linq;using System.Collections;class GFG{ // Function to create an array of prime// numbers upto number 'n'static ArrayList SieveOfEratosthenes(int n){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as false. A value in prime[i] will // finally be true if i is Not a prime, else false. bool[] prime = new bool[n+1]; for(int p=2;p * p <= n;p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == false) // Update all multiples of p for (int i=p * 2;i<n+1;i+=p) prime[i] = true; } ArrayList lis = new ArrayList(); // append all the prime numbers to the list for (int p=2;p<=n;p++) if (prime[p]==false) lis.Add(p); return lis;} // Utility function to count the number of set bitsstatic int setBits(int n){ return (int)Convert.ToString(n, 2).Count(c => c == '1');} // Driver programpublic static void Main () { int x=4, y=8; int count = 0; ArrayList primeArr=new ArrayList(); // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. primeArr = SieveOfEratosthenes(Convert.ToInt32(Math.Ceiling(Math.Log(y,2.0)))); for(int i=x;i<y+1;i++){ int temp = setBits(i); if(primeArr.Contains(temp)) count += 1; } Console.WriteLine(count);}}// This code is contributed by mits", "e": 7349, "s": 5722, "text": null }, { "code": "<?php// PHP code to find count of numbers having prime number// of set bits in their binary representation in the range// [L, R] // Function to create an array of prime// numbers upto number 'n'function SieveOfEratosthenes($n){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. $prime = array_fill(0,$n+1,true); for($p = 2;$p * $p <= $n;$p++) { // If prime[p] is not changed, then it is a prime if ($prime[$p] == true) // Update all multiples of p for($i=$p * 2;$i<$n+1;$i+=$p) $prime[$i] = false; } $lis = array(); // Append all the prime numbers to the list for($p=2;$p<=$n;$p++) if ($prime[$p]) array_push($lis,$p); return $lis;} // Utility function to count the number of set bitsfunction setBits($n){ $cnt=0; while($n){if($n&1)$cnt++;$n>>=1;}; return $cnt;} // Driver program $x = 4; $y = 8; $count = 0; // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. $primeArr = SieveOfEratosthenes(ceil(log($y,2))); for ($i=$x;$i<$y+1;$i++) { $temp = setBits($i); if(in_array($temp, $primeArr)) $count += 1; } print($count); // This code is contributed by mits?>", "e": 8810, "s": 7349, "text": null }, { "code": "<script>// Javascript code to find count of numbers having prime number// of set bits in their binary representation in the range// [L, R] // Function to create an array of prime// numbers upto number 'n'function SieveOfEratosthenes(n){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. let prime = new Array(n+1).fill(true); for(let p = 2;p * p <= n;p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) // Update all multiples of p for(let i=p * 2;i<n+1;i+=p) prime[i] = false; } let lis = new Array(); // Append all the prime numbers to the list for(let p=2;p<=n;p++) if (prime[p]) lis.push(p); return lis;} // Utility function to count the number of set bitsfunction setBits(n){ let cnt=0; while(n){if(n&1)cnt++;n>>=1;}; return cnt;} // Driver program let x = 4; let y = 8; let count = 0; // Here prime numbers are checked till the maximum // number of bits possible because that the maximum // bit sum possible is the number of bits itself. let primeArr = SieveOfEratosthenes(Math.ceil(Math.log(y,2))); for (let i=x;i<y+1;i++) { let temp = setBits(i); if(primeArr.includes(temp)) count += 1; } document.write(count); // This code is contributed by gfgking</script>", "e": 10307, "s": 8810, "text": null }, { "code": null, "e": 10317, "s": 10307, "text": "Output: " }, { "code": null, "e": 10319, "s": 10317, "text": "3" }, { "code": null, "e": 10765, "s": 10319, "text": "This article is contributed by Saisankar Gochhayat and Harshit Sidhwa. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 10778, "s": 10765, "text": "Mithun Kumar" }, { "code": null, "e": 10792, "s": 10778, "text": "deepankkansal" }, { "code": null, "e": 10800, "s": 10792, "text": "gfgking" }, { "code": null, "e": 10807, "s": 10800, "text": "Amazon" }, { "code": null, "e": 10829, "s": 10807, "text": "binary-representation" }, { "code": null, "e": 10842, "s": 10829, "text": "Prime Number" }, { "code": null, "e": 10848, "s": 10842, "text": "sieve" }, { "code": null, "e": 10861, "s": 10848, "text": "Mathematical" }, { "code": null, "e": 10868, "s": 10861, "text": "Amazon" }, { "code": null, "e": 10881, "s": 10868, "text": "Mathematical" }, { "code": null, "e": 10894, "s": 10881, "text": "Prime Number" }, { "code": null, "e": 10900, "s": 10894, "text": "sieve" } ]
How to get negative result using modulo operator in JavaScript ?
26 Aug, 2021 The %(modulo) operator in JavaScript gives the remainder obtained by dividing two numbers. There is a difference between %(modulo) and remainder operator. When remainder or %(modulo) is calculated on positive numbers then both behave similar but when negative numbers are used then both behave differently.The JavaScript %(modulo) behaves like remainder operation and gives the remainder and as the number is negative therefore remainder also comes out to be negative.Let’s understand and compare %(modulo) and remainder operation results clarity. Examples of Modulo Operator: For Positive Numbers: Input: a = 21, b = 4 Output: 1 Explanation: modulo = 21 % 4 modulo = 21 - 4 * 5 modulo = 21 - 20 = 1 Other Explanation: The number 21 can be written in terms of 4 as 21 = 5 * 4 + 1 So, here '1' is the result. For Negative Numbers: Input: a = -23, b = 4 Output: 1 Explanation: modulo = -23 % 4 modulo = -23 + 4 * 6 modulo = -23 + 24 = 1 Other Explanation: The number -23 can be written in terms of 4 as -23 = (-6) * 4 + 1 So, here '1' is the result. Examples of Remainder operator: Remainder operator uses the formula: Remainder = a - (a / b) * b Note: Result of (a / b) is first converted into Integer Value. For Positive Numbers: Input: a = 21, b = 4 Output: 1 Explanation: Remainder = 21 - (21 / 4) * 4 Remainder = 21 - 5 * 4 Remainder = 21 - 20 = 1 For Negative Numbers: Input: a = -23, b = 4 Output: -3 Explanation: Remainder = -23 -( -23 / 4) * 4 Remainder = -23 -(-5) * 4 Remainder = -23 + 20 = -3 So, from the above comparison, it is clear that both the remainder and modulo operations are different. The JavaScript %(modulo) operator is nothing but the remainder operator, that’s why it gives negative results on negative numbers. Number.prototype: The prototype constructor allows adding new properties and methods to JavaScript numbers such that all numbers get this property and can access method by default.Therefore, We will use Number.prototype to create a mod function which will return modulo of two numbers.Syntax:Number.prototype.mod = function(a) { // Calculate return this % a; } Below Programs illustrate the %(modulo) operator in JavaScript:Example 1: This example uses modulo operator (%) to perform operation.<script> // JavaScript code to perform modulo (%)// operation on positive numbers // mod() functionNumber.prototype.mod = function(a) { // Calculate return this % a;} // Driver codevar x = 21;var b = 4; // Call mod() functionvar result = x.mod(b); // Print resultdocument.write("The outcome is: " + result);</script> Output:The outcome is: 1 Example 2:<script> // JavaScript code to perform modulo (%)// operation on negative numbers // Use mod() functionNumber.prototype.mod = function(a) { // Calculate return this % a;} // Driver codevar x = -21;var b = 4; // Call mod()var result = x.mod(b); // Print resultdocument.write("The outcome is: " + result);</script> Output:The outcome is: -1 Therefore, it is clear that why JavaScript %(modulo) gives negative result. Syntax: Number.prototype.mod = function(a) { // Calculate return this % a; } Below Programs illustrate the %(modulo) operator in JavaScript: Example 1: This example uses modulo operator (%) to perform operation. <script> // JavaScript code to perform modulo (%)// operation on positive numbers // mod() functionNumber.prototype.mod = function(a) { // Calculate return this % a;} // Driver codevar x = 21;var b = 4; // Call mod() functionvar result = x.mod(b); // Print resultdocument.write("The outcome is: " + result);</script> Output: The outcome is: 1 Example 2: <script> // JavaScript code to perform modulo (%)// operation on negative numbers // Use mod() functionNumber.prototype.mod = function(a) { // Calculate return this % a;} // Driver codevar x = -21;var b = 4; // Call mod()var result = x.mod(b); // Print resultdocument.write("The outcome is: " + result);</script> Output: The outcome is: -1 Therefore, it is clear that why JavaScript %(modulo) gives negative result. Making changes in JavaScript %(modulo) to work as a mod operator: To perform modulo operator (%) like actual modulo rather than calculating the remainder. We will use the following formula.Suppose numbers are a and b then calculate mod = a % bSyntax:Number.prototype.mod = function(b) { // Calculate return ((this % b) + b) % b; } In the above formula we are calculating modulo from remainder using modular property (a + b) mod c = (a mod c + b mod c) mod c.Below Program illustrates the above approach:Example:<script> // JavaScript implementation of above approach // Use mod() functionNumber.prototype.mod = function(b) { // Calculate return ((this % b) + b) % b;} // Driver codevar x = -21;var b = 4; // Call mod() functionvar result = x.mod(b); // Print resultdocument.write("The outcome is: " + result + "</br>"); x = -33;b = 5; // Call mod() functionresult = x.mod(b); // Print resultdocument.write("The outcome is: " + result);</script> Output:The outcome is: 3 The outcome is: 2 Syntax: Number.prototype.mod = function(b) { // Calculate return ((this % b) + b) % b; } In the above formula we are calculating modulo from remainder using modular property (a + b) mod c = (a mod c + b mod c) mod c. Below Program illustrates the above approach: Example: <script> // JavaScript implementation of above approach // Use mod() functionNumber.prototype.mod = function(b) { // Calculate return ((this % b) + b) % b;} // Driver codevar x = -21;var b = 4; // Call mod() functionvar result = x.mod(b); // Print resultdocument.write("The outcome is: " + result + "</br>"); x = -33;b = 5; // Call mod() functionresult = x.mod(b); // Print resultdocument.write("The outcome is: " + result);</script> Output: The outcome is: 3 The outcome is: 2 ashkanheidaryfazel javascript-operators Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Roadmap to Learn JavaScript For Beginners Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Aug, 2021" }, { "code": null, "e": 601, "s": 53, "text": "The %(modulo) operator in JavaScript gives the remainder obtained by dividing two numbers. There is a difference between %(modulo) and remainder operator. When remainder or %(modulo) is calculated on positive numbers then both behave similar but when negative numbers are used then both behave differently.The JavaScript %(modulo) behaves like remainder operation and gives the remainder and as the number is negative therefore remainder also comes out to be negative.Let’s understand and compare %(modulo) and remainder operation results clarity." }, { "code": null, "e": 630, "s": 601, "text": "Examples of Modulo Operator:" }, { "code": null, "e": 1106, "s": 630, "text": "For Positive Numbers:\nInput: a = 21, b = 4\nOutput: 1\nExplanation: \nmodulo = 21 % 4\nmodulo = 21 - 4 * 5\nmodulo = 21 - 20 = 1 \nOther Explanation:\nThe number 21 can be written in terms of 4 as\n21 = 5 * 4 + 1\nSo, here '1' is the result.\n\nFor Negative Numbers:\nInput: a = -23, b = 4\nOutput: 1\nExplanation: \nmodulo = -23 % 4\nmodulo = -23 + 4 * 6\nmodulo = -23 + 24 = 1\nOther Explanation:\nThe number -23 can be written in terms of 4 as\n-23 = (-6) * 4 + 1\nSo, here '1' is the result.\n" }, { "code": null, "e": 1138, "s": 1106, "text": "Examples of Remainder operator:" }, { "code": null, "e": 1571, "s": 1138, "text": "Remainder operator uses the formula:\nRemainder = a - (a / b) * b\n\nNote: Result of (a / b) is first converted into Integer Value.\n\nFor Positive Numbers:\nInput: a = 21, b = 4\nOutput: 1\nExplanation: \nRemainder = 21 - (21 / 4) * 4 \nRemainder = 21 - 5 * 4 \nRemainder = 21 - 20 = 1\n\nFor Negative Numbers:\nInput: a = -23, b = 4\nOutput: -3\nExplanation: \nRemainder = -23 -( -23 / 4) * 4\nRemainder = -23 -(-5) * 4\nRemainder = -23 + 20 = -3\n" }, { "code": null, "e": 1806, "s": 1571, "text": "So, from the above comparison, it is clear that both the remainder and modulo operations are different. The JavaScript %(modulo) operator is nothing but the remainder operator, that’s why it gives negative results on negative numbers." }, { "code": null, "e": 3207, "s": 1806, "text": "Number.prototype: The prototype constructor allows adding new properties and methods to JavaScript numbers such that all numbers get this property and can access method by default.Therefore, We will use Number.prototype to create a mod function which will return modulo of two numbers.Syntax:Number.prototype.mod = function(a) {\n // Calculate\n return this % a;\n}\nBelow Programs illustrate the %(modulo) operator in JavaScript:Example 1: This example uses modulo operator (%) to perform operation.<script> // JavaScript code to perform modulo (%)// operation on positive numbers // mod() functionNumber.prototype.mod = function(a) { // Calculate return this % a;} // Driver codevar x = 21;var b = 4; // Call mod() functionvar result = x.mod(b); // Print resultdocument.write(\"The outcome is: \" + result);</script> Output:The outcome is: 1\nExample 2:<script> // JavaScript code to perform modulo (%)// operation on negative numbers // Use mod() functionNumber.prototype.mod = function(a) { // Calculate return this % a;} // Driver codevar x = -21;var b = 4; // Call mod()var result = x.mod(b); // Print resultdocument.write(\"The outcome is: \" + result);</script> Output:The outcome is: -1\nTherefore, it is clear that why JavaScript %(modulo) gives negative result." }, { "code": null, "e": 3215, "s": 3207, "text": "Syntax:" }, { "code": null, "e": 3293, "s": 3215, "text": "Number.prototype.mod = function(a) {\n // Calculate\n return this % a;\n}\n" }, { "code": null, "e": 3357, "s": 3293, "text": "Below Programs illustrate the %(modulo) operator in JavaScript:" }, { "code": null, "e": 3428, "s": 3357, "text": "Example 1: This example uses modulo operator (%) to perform operation." }, { "code": "<script> // JavaScript code to perform modulo (%)// operation on positive numbers // mod() functionNumber.prototype.mod = function(a) { // Calculate return this % a;} // Driver codevar x = 21;var b = 4; // Call mod() functionvar result = x.mod(b); // Print resultdocument.write(\"The outcome is: \" + result);</script> ", "e": 3818, "s": 3428, "text": null }, { "code": null, "e": 3826, "s": 3818, "text": "Output:" }, { "code": null, "e": 3845, "s": 3826, "text": "The outcome is: 1\n" }, { "code": null, "e": 3856, "s": 3845, "text": "Example 2:" }, { "code": "<script> // JavaScript code to perform modulo (%)// operation on negative numbers // Use mod() functionNumber.prototype.mod = function(a) { // Calculate return this % a;} // Driver codevar x = -21;var b = 4; // Call mod()var result = x.mod(b); // Print resultdocument.write(\"The outcome is: \" + result);</script> ", "e": 4230, "s": 3856, "text": null }, { "code": null, "e": 4238, "s": 4230, "text": "Output:" }, { "code": null, "e": 4258, "s": 4238, "text": "The outcome is: -1\n" }, { "code": null, "e": 4334, "s": 4258, "text": "Therefore, it is clear that why JavaScript %(modulo) gives negative result." }, { "code": null, "e": 5394, "s": 4334, "text": "Making changes in JavaScript %(modulo) to work as a mod operator: To perform modulo operator (%) like actual modulo rather than calculating the remainder. We will use the following formula.Suppose numbers are a and b then calculate mod = a % bSyntax:Number.prototype.mod = function(b) {\n // Calculate\n return ((this % b) + b) % b;\n}\nIn the above formula we are calculating modulo from remainder using modular property (a + b) mod c = (a mod c + b mod c) mod c.Below Program illustrates the above approach:Example:<script> // JavaScript implementation of above approach // Use mod() functionNumber.prototype.mod = function(b) { // Calculate return ((this % b) + b) % b;} // Driver codevar x = -21;var b = 4; // Call mod() functionvar result = x.mod(b); // Print resultdocument.write(\"The outcome is: \" + result + \"</br>\"); x = -33;b = 5; // Call mod() functionresult = x.mod(b); // Print resultdocument.write(\"The outcome is: \" + result);</script> Output:The outcome is: 3\nThe outcome is: 2\n" }, { "code": null, "e": 5402, "s": 5394, "text": "Syntax:" }, { "code": null, "e": 5492, "s": 5402, "text": "Number.prototype.mod = function(b) {\n // Calculate\n return ((this % b) + b) % b;\n}\n" }, { "code": null, "e": 5620, "s": 5492, "text": "In the above formula we are calculating modulo from remainder using modular property (a + b) mod c = (a mod c + b mod c) mod c." }, { "code": null, "e": 5666, "s": 5620, "text": "Below Program illustrates the above approach:" }, { "code": null, "e": 5675, "s": 5666, "text": "Example:" }, { "code": "<script> // JavaScript implementation of above approach // Use mod() functionNumber.prototype.mod = function(b) { // Calculate return ((this % b) + b) % b;} // Driver codevar x = -21;var b = 4; // Call mod() functionvar result = x.mod(b); // Print resultdocument.write(\"The outcome is: \" + result + \"</br>\"); x = -33;b = 5; // Call mod() functionresult = x.mod(b); // Print resultdocument.write(\"The outcome is: \" + result);</script> ", "e": 6173, "s": 5675, "text": null }, { "code": null, "e": 6181, "s": 6173, "text": "Output:" }, { "code": null, "e": 6218, "s": 6181, "text": "The outcome is: 3\nThe outcome is: 2\n" }, { "code": null, "e": 6237, "s": 6218, "text": "ashkanheidaryfazel" }, { "code": null, "e": 6258, "s": 6237, "text": "javascript-operators" }, { "code": null, "e": 6265, "s": 6258, "text": "Picked" }, { "code": null, "e": 6276, "s": 6265, "text": "JavaScript" }, { "code": null, "e": 6293, "s": 6276, "text": "Web Technologies" }, { "code": null, "e": 6320, "s": 6293, "text": "Web technologies Questions" }, { "code": null, "e": 6418, "s": 6320, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6479, "s": 6418, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6551, "s": 6479, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 6591, "s": 6551, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6644, "s": 6591, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 6686, "s": 6644, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 6719, "s": 6686, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6781, "s": 6719, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6842, "s": 6781, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6892, "s": 6842, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Groups in Linux System Administration - GeeksforGeeks
19 Nov, 2021 Each group in a Linux system is uniquely identified by a group identification number or GID. All the information listing groups in a system are stored in /etc/group file. The hashed passwords for groups are stored in /etc/gshadow file. Every user has a primary user group and zero or more supplementary groups. On login, the group membership is set to the primary group of user. This can be changed to any other supplementary group using newgrp or chgrp commands. This file is readable by any user but only root as read and write permissions for it. This file consists of the following colon separated information about groups in a system: Group name fieldPassword field If this field is empty, no password is needed.Group Identification number or GIDComma separated list of usernames of users that belong to the group. Group name field Password field If this field is empty, no password is needed. If this field is empty, no password is needed. Group Identification number or GID Comma separated list of usernames of users that belong to the group. Syntax: [group_name]:[group_password]:[GID]:[users] Example: This file is readable and writable by only by root user. Each entry of this file contains each group’s encrypted password, group membership and administrator information separated by a colon. Group name fieldPassword field It contains an encrypted password.The password is used when a user who is not a member of the group wants to gain the permissions of this group. Members can access the group without being prompted for a password. If no password is set, it is indicated by ‘!’ or ‘!!’.It implies only members can access the group. There’s no way other users can use the group.’!!’ indicates that no password has ever been set on the group. Comma separated list of user-names who are group administrators. Administrators can change the password or the members of the group. Comma separated list of user-names who are group members. Group name field Password field It contains an encrypted password.The password is used when a user who is not a member of the group wants to gain the permissions of this group. Members can access the group without being prompted for a password. If no password is set, it is indicated by ‘!’ or ‘!!’.It implies only members can access the group. There’s no way other users can use the group.’!!’ indicates that no password has ever been set on the group. It contains an encrypted password.The password is used when a user who is not a member of the group wants to gain the permissions of this group. Members can access the group without being prompted for a password. If no password is set, it is indicated by ‘!’ or ‘!!’.It implies only members can access the group. There’s no way other users can use the group.’!!’ indicates that no password has ever been set on the group. Comma separated list of user-names who are group administrators. Administrators can change the password or the members of the group. Administrators can change the password or the members of the group. Comma separated list of user-names who are group members. Syntax: [group_name]:[group_password]:[administrators]:[users] Example: abhishek0719kadiyan linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples SORT command in Linux/Unix with examples curl command in Linux with Examples 'crontab' in Linux with Examples UDP Server-Client implementation in C diff command in Linux with examples Conditional Statements | Shell Script Cat command in Linux with examples
[ { "code": null, "e": 24635, "s": 24607, "text": "\n19 Nov, 2021" }, { "code": null, "e": 24872, "s": 24635, "text": "Each group in a Linux system is uniquely identified by a group identification number or GID. All the information listing groups in a system are stored in /etc/group file. The hashed passwords for groups are stored in /etc/gshadow file. " }, { "code": null, "e": 25102, "s": 24872, "text": "Every user has a primary user group and zero or more supplementary groups. On login, the group membership is set to the primary group of user. This can be changed to any other supplementary group using newgrp or chgrp commands. " }, { "code": null, "e": 25280, "s": 25102, "text": "This file is readable by any user but only root as read and write permissions for it. This file consists of the following colon separated information about groups in a system: " }, { "code": null, "e": 25460, "s": 25280, "text": "Group name fieldPassword field If this field is empty, no password is needed.Group Identification number or GIDComma separated list of usernames of users that belong to the group." }, { "code": null, "e": 25477, "s": 25460, "text": "Group name field" }, { "code": null, "e": 25539, "s": 25477, "text": "Password field If this field is empty, no password is needed." }, { "code": null, "e": 25586, "s": 25539, "text": "If this field is empty, no password is needed." }, { "code": null, "e": 25621, "s": 25586, "text": "Group Identification number or GID" }, { "code": null, "e": 25690, "s": 25621, "text": "Comma separated list of usernames of users that belong to the group." }, { "code": null, "e": 25700, "s": 25690, "text": "Syntax: " }, { "code": null, "e": 25744, "s": 25700, "text": "[group_name]:[group_password]:[GID]:[users]" }, { "code": null, "e": 25753, "s": 25744, "text": "Example:" }, { "code": null, "e": 25947, "s": 25753, "text": "This file is readable and writable by only by root user. Each entry of this file contains each group’s encrypted password, group membership and administrator information separated by a colon. " }, { "code": null, "e": 26594, "s": 25947, "text": "Group name fieldPassword field It contains an encrypted password.The password is used when a user who is not a member of the group wants to gain the permissions of this group. Members can access the group without being prompted for a password. If no password is set, it is indicated by ‘!’ or ‘!!’.It implies only members can access the group. There’s no way other users can use the group.’!!’ indicates that no password has ever been set on the group. Comma separated list of user-names who are group administrators. Administrators can change the password or the members of the group. Comma separated list of user-names who are group members." }, { "code": null, "e": 26611, "s": 26594, "text": "Group name field" }, { "code": null, "e": 27051, "s": 26611, "text": "Password field It contains an encrypted password.The password is used when a user who is not a member of the group wants to gain the permissions of this group. Members can access the group without being prompted for a password. If no password is set, it is indicated by ‘!’ or ‘!!’.It implies only members can access the group. There’s no way other users can use the group.’!!’ indicates that no password has ever been set on the group. " }, { "code": null, "e": 27266, "s": 27051, "text": "It contains an encrypted password.The password is used when a user who is not a member of the group wants to gain the permissions of this group. Members can access the group without being prompted for a password. " }, { "code": null, "e": 27477, "s": 27266, "text": "If no password is set, it is indicated by ‘!’ or ‘!!’.It implies only members can access the group. There’s no way other users can use the group.’!!’ indicates that no password has ever been set on the group. " }, { "code": null, "e": 27612, "s": 27477, "text": "Comma separated list of user-names who are group administrators. Administrators can change the password or the members of the group. " }, { "code": null, "e": 27682, "s": 27612, "text": "Administrators can change the password or the members of the group. " }, { "code": null, "e": 27740, "s": 27682, "text": "Comma separated list of user-names who are group members." }, { "code": null, "e": 27750, "s": 27740, "text": "Syntax: " }, { "code": null, "e": 27805, "s": 27750, "text": "[group_name]:[group_password]:[administrators]:[users]" }, { "code": null, "e": 27815, "s": 27805, "text": "Example: " }, { "code": null, "e": 27835, "s": 27815, "text": "abhishek0719kadiyan" }, { "code": null, "e": 27849, "s": 27835, "text": "linux-command" }, { "code": null, "e": 27860, "s": 27849, "text": "Linux-Unix" }, { "code": null, "e": 27958, "s": 27860, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27996, "s": 27958, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28031, "s": 27996, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 28066, "s": 28031, "text": "tar command in Linux with examples" }, { "code": null, "e": 28107, "s": 28066, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 28143, "s": 28107, "text": "curl command in Linux with Examples" }, { "code": null, "e": 28176, "s": 28143, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 28214, "s": 28176, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28250, "s": 28214, "text": "diff command in Linux with examples" }, { "code": null, "e": 28288, "s": 28250, "text": "Conditional Statements | Shell Script" } ]
File upload Fields in Serializers - Django REST Framework - GeeksforGeeks
20 Dec, 2021 In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around File Upload Fields Fields in Serializers in Django REST Framework. There are two major fields – FileField and ImageField. FileField is basically a file representation. It performs Django’s standard FileField validation. This field is same as FileField – Django Models.It has the following arguments – max_length – Designates the maximum length for the file name. allow_empty_file – Designates if empty files are allowed. use_url – If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise. Syntax – field_name = serializers.FileField(*args, **kwargs) ImageField is an image representation.It validates the uploaded file content as matching a known image format. This is same as ImageField – Django formsIt has the following arguments – max_length – Designates the maximum length for the file name. allow_empty_file – Designates if empty files are allowed. use_url – If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise. Syntax – field_name = serializers.ImageField(*args, **kwargs) To explain the usage of file upload Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with FileField and ImageField as the fields. Python3 # import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, files, image): self.files = files self.image = image # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields files = serializers.FileField() image = serializers.ImageField() Now let us create some objects and try serializing them and check if they are actually working, Run, – Python manage.py shell Now, run following python commands in the shell # import everything from serializers >>> from apis.serializers import * # create objects of type Text File and Image >>> from django.core.files import File >>> text_file = File(open("test.txt"), 'rb') >>> image_file = File(open("test.jpeg"), 'rb') # create a object of type Geeks >>> obj = Geeks(text_file, image_file) # serialize the object >>> serializer = GeeksSerializer(obj) # print serialized data >>> serializer.data {'files': None, 'image': None} Here is the output of all these operations on terminal – Note that prime motto of these fields is to impart validations, such as Filefield validates the data to file only. Let’s check if these validations are working or not – # Create a dictionary and add invalid values >>> data = {} >>> data['files'] = text_file >>> data['image_file'] = "invalid" # dictionary created >>> data {'files': , 'image_file': 'invalid'} # deserialize the data >>> serializer = GeeksSerializer(data=data) # check if data is valid >>> serializer.is_valid() False # check the errors >>> serializer.errors {'image': [ErrorDetail(string='No file was submitted.', code='required')]} Here is the output of these commands which clearly shows image as invalid and file as valid – Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work. .math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } surinderdawra388 Django-REST Python Django rest-framework 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 Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24440, "s": 24412, "text": "\n20 Dec, 2021" }, { "code": null, "e": 25127, "s": 24440, "text": "In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around File Upload Fields Fields in Serializers in Django REST Framework. There are two major fields – FileField and ImageField. " }, { "code": null, "e": 25308, "s": 25127, "text": "FileField is basically a file representation. It performs Django’s standard FileField validation. This field is same as FileField – Django Models.It has the following arguments – " }, { "code": null, "e": 25370, "s": 25308, "text": "max_length – Designates the maximum length for the file name." }, { "code": null, "e": 25428, "s": 25370, "text": "allow_empty_file – Designates if empty files are allowed." }, { "code": null, "e": 25710, "s": 25428, "text": "use_url – If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise." }, { "code": null, "e": 25720, "s": 25710, "text": "Syntax – " }, { "code": null, "e": 25773, "s": 25720, "text": "field_name = serializers.FileField(*args, **kwargs) " }, { "code": null, "e": 25960, "s": 25773, "text": "ImageField is an image representation.It validates the uploaded file content as matching a known image format. This is same as ImageField – Django formsIt has the following arguments – " }, { "code": null, "e": 26022, "s": 25960, "text": "max_length – Designates the maximum length for the file name." }, { "code": null, "e": 26080, "s": 26022, "text": "allow_empty_file – Designates if empty files are allowed." }, { "code": null, "e": 26362, "s": 26080, "text": "use_url – If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise." }, { "code": null, "e": 26372, "s": 26362, "text": "Syntax – " }, { "code": null, "e": 26426, "s": 26372, "text": "field_name = serializers.ImageField(*args, **kwargs) " }, { "code": null, "e": 26700, "s": 26426, "text": "To explain the usage of file upload Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with FileField and ImageField as the fields. " }, { "code": null, "e": 26708, "s": 26700, "text": "Python3" }, { "code": "# import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, files, image): self.files = files self.image = image # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields files = serializers.FileField() image = serializers.ImageField()", "e": 27058, "s": 26708, "text": null }, { "code": null, "e": 27163, "s": 27058, "text": "Now let us create some objects and try serializing them and check if they are actually working, Run, – " }, { "code": null, "e": 27186, "s": 27163, "text": "Python manage.py shell" }, { "code": null, "e": 27235, "s": 27186, "text": "Now, run following python commands in the shell " }, { "code": null, "e": 27694, "s": 27235, "text": "# import everything from serializers\n>>> from apis.serializers import *\n\n# create objects of type Text File and Image\n>>> from django.core.files import File\n>>> text_file = File(open(\"test.txt\"), 'rb')\n>>> image_file = File(open(\"test.jpeg\"), 'rb')\n\n# create a object of type Geeks\n>>> obj = Geeks(text_file, image_file)\n\n# serialize the object\n>>> serializer = GeeksSerializer(obj)\n\n# print serialized data\n>>> serializer.data\n{'files': None, 'image': None}" }, { "code": null, "e": 27752, "s": 27694, "text": "Here is the output of all these operations on terminal – " }, { "code": null, "e": 27922, "s": 27752, "text": "Note that prime motto of these fields is to impart validations, such as Filefield validates the data to file only. Let’s check if these validations are working or not – " }, { "code": null, "e": 28357, "s": 27922, "text": "# Create a dictionary and add invalid values\n>>> data = {}\n>>> data['files'] = text_file\n>>> data['image_file'] = \"invalid\"\n\n# dictionary created\n>>> data\n{'files': , 'image_file': 'invalid'}\n\n# deserialize the data\n>>> serializer = GeeksSerializer(data=data)\n\n# check if data is valid\n>>> serializer.is_valid()\nFalse\n\n# check the errors\n>>> serializer.errors\n{'image': [ErrorDetail(string='No file was submitted.', code='required')]}" }, { "code": null, "e": 28452, "s": 28357, "text": "Here is the output of these commands which clearly shows image as invalid and file as valid – " }, { "code": null, "e": 28856, "s": 28452, "text": "Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work. " }, { "code": null, "e": 29196, "s": 28856, "text": ".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } " }, { "code": null, "e": 29213, "s": 29196, "text": "surinderdawra388" }, { "code": null, "e": 29225, "s": 29213, "text": "Django-REST" }, { "code": null, "e": 29239, "s": 29225, "text": "Python Django" }, { "code": null, "e": 29254, "s": 29239, "text": "rest-framework" }, { "code": null, "e": 29261, "s": 29254, "text": "Python" }, { "code": null, "e": 29359, "s": 29261, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29377, "s": 29359, "text": "Python Dictionary" }, { "code": null, "e": 29412, "s": 29377, "text": "Read a file line by line in Python" }, { "code": null, "e": 29434, "s": 29412, "text": "Enumerate() in Python" }, { "code": null, "e": 29466, "s": 29434, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29496, "s": 29466, "text": "Iterate over a list in Python" }, { "code": null, "e": 29538, "s": 29496, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29564, "s": 29538, "text": "Python String | replace()" }, { "code": null, "e": 29601, "s": 29564, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29644, "s": 29601, "text": "Python program to convert a list to string" } ]
Simple Genetic Algorithm (SGA)
07 Apr, 2021 Prerequisite – Genetic Algorithm Introduction : Simple Genetic Algorithm (SGA) is one of the three types of strategies followed in Genetic algorithm. SGA starts with the creation of an initial population of size N.Then, we evaluate the goodness/fitness of each of the solutions/individuals. SGA starts with the creation of an initial population of size N. Then, we evaluate the goodness/fitness of each of the solutions/individuals. After that, the convergence criterion is checked, if it meets then we converge the algorithm otherwise go for the next steps – Select Np individuals from the previous population.Create the mating pool randomly.Perform Crossover.Perform Mutation in offspring solutions.Perform inversion in offspring solutions.Replace the old solutions of the last generation with the newly created solutions and go to step (2). Select Np individuals from the previous population. Create the mating pool randomly. Perform Crossover. Perform Mutation in offspring solutions. Perform inversion in offspring solutions. Replace the old solutions of the last generation with the newly created solutions and go to step (2). Simple Genetic Algorithm Block Diagram Important Parameters while solving problems in Simple Genetic Algorithm : Initial Population NMating pool size NpConvergence thresholdCrossoverMutationInversion Initial Population N Mating pool size Np Convergence threshold Crossover Mutation Inversion Features : Computationally Expensive Biased towards more highly fit individuals Performs well when the initial population is large enough. Applications : Learning robot behaviour using Simple Genetic Algorithm. In the finance industry. Neural networks. Soft computing Applications like Fuzzy logic, Neurocomputing. Optimization problems. Genetic Algorithms Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Apr, 2021" }, { "code": null, "e": 85, "s": 52, "text": "Prerequisite – Genetic Algorithm" }, { "code": null, "e": 100, "s": 85, "text": "Introduction :" }, { "code": null, "e": 202, "s": 100, "text": "Simple Genetic Algorithm (SGA) is one of the three types of strategies followed in Genetic algorithm." }, { "code": null, "e": 343, "s": 202, "text": "SGA starts with the creation of an initial population of size N.Then, we evaluate the goodness/fitness of each of the solutions/individuals." }, { "code": null, "e": 408, "s": 343, "text": "SGA starts with the creation of an initial population of size N." }, { "code": null, "e": 485, "s": 408, "text": "Then, we evaluate the goodness/fitness of each of the solutions/individuals." }, { "code": null, "e": 612, "s": 485, "text": "After that, the convergence criterion is checked, if it meets then we converge the algorithm otherwise go for the next steps –" }, { "code": null, "e": 896, "s": 612, "text": "Select Np individuals from the previous population.Create the mating pool randomly.Perform Crossover.Perform Mutation in offspring solutions.Perform inversion in offspring solutions.Replace the old solutions of the last generation with the newly created solutions and go to step (2)." }, { "code": null, "e": 948, "s": 896, "text": "Select Np individuals from the previous population." }, { "code": null, "e": 981, "s": 948, "text": "Create the mating pool randomly." }, { "code": null, "e": 1000, "s": 981, "text": "Perform Crossover." }, { "code": null, "e": 1041, "s": 1000, "text": "Perform Mutation in offspring solutions." }, { "code": null, "e": 1083, "s": 1041, "text": "Perform inversion in offspring solutions." }, { "code": null, "e": 1185, "s": 1083, "text": "Replace the old solutions of the last generation with the newly created solutions and go to step (2)." }, { "code": null, "e": 1224, "s": 1185, "text": "Simple Genetic Algorithm Block Diagram" }, { "code": null, "e": 1299, "s": 1224, "text": "Important Parameters while solving problems in Simple Genetic Algorithm : " }, { "code": null, "e": 1386, "s": 1299, "text": "Initial Population NMating pool size NpConvergence thresholdCrossoverMutationInversion" }, { "code": null, "e": 1407, "s": 1386, "text": "Initial Population N" }, { "code": null, "e": 1427, "s": 1407, "text": "Mating pool size Np" }, { "code": null, "e": 1449, "s": 1427, "text": "Convergence threshold" }, { "code": null, "e": 1459, "s": 1449, "text": "Crossover" }, { "code": null, "e": 1468, "s": 1459, "text": "Mutation" }, { "code": null, "e": 1478, "s": 1468, "text": "Inversion" }, { "code": null, "e": 1489, "s": 1478, "text": "Features :" }, { "code": null, "e": 1515, "s": 1489, "text": "Computationally Expensive" }, { "code": null, "e": 1558, "s": 1515, "text": "Biased towards more highly fit individuals" }, { "code": null, "e": 1617, "s": 1558, "text": "Performs well when the initial population is large enough." }, { "code": null, "e": 1632, "s": 1617, "text": "Applications :" }, { "code": null, "e": 1689, "s": 1632, "text": "Learning robot behaviour using Simple Genetic Algorithm." }, { "code": null, "e": 1714, "s": 1689, "text": "In the finance industry." }, { "code": null, "e": 1731, "s": 1714, "text": "Neural networks." }, { "code": null, "e": 1793, "s": 1731, "text": "Soft computing Applications like Fuzzy logic, Neurocomputing." }, { "code": null, "e": 1816, "s": 1793, "text": "Optimization problems." }, { "code": null, "e": 1835, "s": 1816, "text": "Genetic Algorithms" }, { "code": null, "e": 1852, "s": 1835, "text": "Machine Learning" }, { "code": null, "e": 1869, "s": 1852, "text": "Machine Learning" } ]
Extend Class Method in Python
06 Feb, 2020 In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism. This is similar to overriding in Java and virtual methods in C++. A call from the instance of the subclass executes the subclass’s version of the function. To call superclass’s version super() method is used. Why Extend a Function?The goal of extending a class method in Python can be achieved by Inheritance. One of the major advantages provided by extending a method is that it makes the code reusable. Further, multiple subclasses can share the same code and are even allowed to update it as per the requirement. We’ll deal with both cases here CASE 1: without extending a class method # definition of superclass "Triangles"class Triangles(object): count = 0 # Calling Constructor def __init__(self, name, s1, s2, s3): self.name = name self.s1 = s1 self.s2 = s2 self.s3 = s3 Triangles.count+= 1 def setName(self, name): self.name = name def setdim(self, s1, s2, s3): self.s1 = s1 self.s2 = s2 self.s3 = s3 def getcount(self): return Triangles.count def __str__(self): return 'Name: '+self.name+'\nDimensions: '+str(self.s1)+','+str(self.s2)+','+str(self.s3) # describing a subclass # inherits from Trianglesclass Peri(Triangles): # function to calculate the area def calculate(self): self.pm = 0 self.pm = self.s1 + self.s2 + self.s3 # function to display just the area # because it is not extended def display(self): return self.pm def main(): # instance of the subclass p = Peri('PQR', 2, 3, 4) # call to calculate() p.calculate() # explicit call to __str__() print(p.__str__()) # call to display() print(p.display()) main() Output: Name: PQR Dimensions: 2, 3, 4 9 CASE 2: extending a class method # definition of superclass "Triangles"class Triangles(object): count = 0 def __init__(self, name, s1, s2, s3): self.name = name self.s1 = s1 self.s2 = s2 self.s3 = s3 Triangles.count+= 1 def setName(self, name): self.name = name def setdim(self, s1, s2, s3): self.s1 = s1 self.s2 = s2 self.s3 = s3 def getcount(self): return Triangles.count # superclass's version of display() def display(self): return 'Name: '+self.name+'\nDimensions: '+str(self.s1)+', '+str(self.s2)+', '+str(self.s3) # definition of the subclass# inherits from "Triangles"class Peri(Triangles): def calculate(self): self.pm = 0 self.pm = self.s1 + self.s2 + self.s3 # extended method def display(self): # calls display() of superclass print (super(Peri, self).display()) # adding its own properties return self.pm def main(): # instance of the subclass p = Peri('PQR', 2, 3, 4) # call to calculate p.calculate() # one call is enough print(p.display()) main() Output: Name: PQR Dimensions: 2, 3, 4 9 The output produced in both cases is the same, the only difference being that the second case makes it easier for other subclasses to inherit the methods and “extend” them as required which as mentioned increases code reusability. Python-OOP python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Feb, 2020" }, { "code": null, "e": 555, "s": 54, "text": "In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism. This is similar to overriding in Java and virtual methods in C++. A call from the instance of the subclass executes the subclass’s version of the function. To call superclass’s version super() method is used." }, { "code": null, "e": 862, "s": 555, "text": "Why Extend a Function?The goal of extending a class method in Python can be achieved by Inheritance. One of the major advantages provided by extending a method is that it makes the code reusable. Further, multiple subclasses can share the same code and are even allowed to update it as per the requirement." }, { "code": null, "e": 894, "s": 862, "text": "We’ll deal with both cases here" }, { "code": null, "e": 935, "s": 894, "text": "CASE 1: without extending a class method" }, { "code": "# definition of superclass \"Triangles\"class Triangles(object): count = 0 # Calling Constructor def __init__(self, name, s1, s2, s3): self.name = name self.s1 = s1 self.s2 = s2 self.s3 = s3 Triangles.count+= 1 def setName(self, name): self.name = name def setdim(self, s1, s2, s3): self.s1 = s1 self.s2 = s2 self.s3 = s3 def getcount(self): return Triangles.count def __str__(self): return 'Name: '+self.name+'\\nDimensions: '+str(self.s1)+','+str(self.s2)+','+str(self.s3) # describing a subclass # inherits from Trianglesclass Peri(Triangles): # function to calculate the area def calculate(self): self.pm = 0 self.pm = self.s1 + self.s2 + self.s3 # function to display just the area # because it is not extended def display(self): return self.pm def main(): # instance of the subclass p = Peri('PQR', 2, 3, 4) # call to calculate() p.calculate() # explicit call to __str__() print(p.__str__()) # call to display() print(p.display()) main()", "e": 2117, "s": 935, "text": null }, { "code": null, "e": 2125, "s": 2117, "text": "Output:" }, { "code": null, "e": 2158, "s": 2125, "text": "Name: PQR\nDimensions: 2, 3, 4\n9\n" }, { "code": null, "e": 2191, "s": 2158, "text": "CASE 2: extending a class method" }, { "code": "# definition of superclass \"Triangles\"class Triangles(object): count = 0 def __init__(self, name, s1, s2, s3): self.name = name self.s1 = s1 self.s2 = s2 self.s3 = s3 Triangles.count+= 1 def setName(self, name): self.name = name def setdim(self, s1, s2, s3): self.s1 = s1 self.s2 = s2 self.s3 = s3 def getcount(self): return Triangles.count # superclass's version of display() def display(self): return 'Name: '+self.name+'\\nDimensions: '+str(self.s1)+', '+str(self.s2)+', '+str(self.s3) # definition of the subclass# inherits from \"Triangles\"class Peri(Triangles): def calculate(self): self.pm = 0 self.pm = self.s1 + self.s2 + self.s3 # extended method def display(self): # calls display() of superclass print (super(Peri, self).display()) # adding its own properties return self.pm def main(): # instance of the subclass p = Peri('PQR', 2, 3, 4) # call to calculate p.calculate() # one call is enough print(p.display()) main()", "e": 3390, "s": 2191, "text": null }, { "code": null, "e": 3398, "s": 3390, "text": "Output:" }, { "code": null, "e": 3431, "s": 3398, "text": "Name: PQR\nDimensions: 2, 3, 4\n9\n" }, { "code": null, "e": 3662, "s": 3431, "text": "The output produced in both cases is the same, the only difference being that the second case makes it easier for other subclasses to inherit the methods and “extend” them as required which as mentioned increases code reusability." }, { "code": null, "e": 3673, "s": 3662, "text": "Python-OOP" }, { "code": null, "e": 3693, "s": 3673, "text": "python-oop-concepts" }, { "code": null, "e": 3700, "s": 3693, "text": "Python" }, { "code": null, "e": 3798, "s": 3700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3840, "s": 3798, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3862, "s": 3840, "text": "Enumerate() in Python" }, { "code": null, "e": 3888, "s": 3862, "text": "Python String | replace()" }, { "code": null, "e": 3920, "s": 3888, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3949, "s": 3920, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3976, "s": 3949, "text": "Python Classes and Objects" }, { "code": null, "e": 3997, "s": 3976, "text": "Python OOPs Concepts" }, { "code": null, "e": 4033, "s": 3997, "text": "Convert integer to string in Python" }, { "code": null, "e": 4056, "s": 4033, "text": "Introduction To PYTHON" } ]
Ruby - Regular Expressions
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a pattern. A regular expression literal is a pattern between slashes or between arbitrary delimiters followed by %r as follows − /pattern/ /pattern/im # option can be specified %r!/usr/local! # general delimited regular expression #!/usr/bin/ruby line1 = "Cats are smarter than dogs"; line2 = "Dogs also like meat"; if ( line1 =~ /Cats(.*)/ ) puts "Line1 contains Cats" end if ( line2 =~ /Cats(.*)/ ) puts "Line2 contains Dogs" end This will produce the following result − Line1 contains Cats Regular expression literals may include an optional modifier to control various aspects of matching. The modifier is specified after the second slash character, as shown previously and may be represented by one of these characters − i Ignores case when matching text. o Performs #{} interpolations only once, the first time the regexp literal is evaluated. x Ignores whitespace and allows comments in regular expressions. m Matches multiple lines, recognizing newlines as normal characters. u,e,s,n Interprets the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. If none of these modifiers is specified, the regular expression is assumed to use the source encoding. Like string literals delimited with %Q, Ruby allows you to begin your regular expressions with %r followed by a delimiter of your choice. This is useful when the pattern you are describing contains a lot of forward slash characters that you don't want to escape − # Following matches a single slash character, no escape required %r|/| # Flag characters are allowed with this syntax, too %r[</(.*)>]i Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash. ^ Matches beginning of line. $ Matches end of line. . Matches any single character except newline. Using m option allows it to match newline as well. [...] Matches any single character in brackets. [^...] Matches any single character not in brackets re* Matches 0 or more occurrences of preceding expression. re+ Matches 1 or more occurrence of preceding expression. re? Matches 0 or 1 occurrence of preceding expression. re{ n} Matches exactly n number of occurrences of preceding expression. re{ n,} Matches n or more occurrences of preceding expression. re{ n, m} Matches at least n and at most m occurrences of preceding expression. a| b Matches either a or b. (re) Groups regular expressions and remembers matched text. (?imx) Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected. (?-imx) Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected. (?: re) Groups regular expressions without remembering matched text. (?imx: re) Temporarily toggles on i, m, or x options within parentheses. (?-imx: re) Temporarily toggles off i, m, or x options within parentheses. (?#...) Comment. (?= re) Specifies position using a pattern. Doesn't have a range. (?! re) Specifies position using pattern negation. Doesn't have a range. (?> re) Matches independent pattern without backtracking. \w Matches word characters. \W Matches nonword characters. \s Matches whitespace. Equivalent to [\t\n\r\f]. \S Matches nonwhitespace. \d Matches digits. Equivalent to [0-9]. \D Matches nondigits. \A Matches beginning of string. \Z Matches end of string. If a newline exists, it matches just before newline. \z Matches end of string. \G Matches point where last match finished. \b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. \B Matches non-word boundaries. \n, \t, etc. Matches newlines, carriage returns, tabs, etc. \1...\9 Matches nth grouped subexpression. \10 Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code. /ruby/ Matches "ruby". ¥ Matches Yen sign. Multibyte characters are supported in Ruby 1.9 and Ruby 1.8. /[Rr]uby/ Matches "Ruby" or "ruby". /rub[ye]/ Matches "ruby" or "rube". /[aeiou]/ Matches any one lowercase vowel. /[0-9]/ Matches any digit; same as /[0123456789]/. /[a-z]/ Matches any lowercase ASCII letter. /[A-Z]/ Matches any uppercase ASCII letter. /[a-zA-Z0-9]/ Matches any of the above. /[^aeiou]/ Matches anything other than a lowercase vowel. /[^0-9]/ Matches anything other than a digit. /./ Matches any character except newline. /./m In multi-line mode, matches newline, too. /\d/ Matches a digit: /[0-9]/. /\D/ Matches a non-digit: /[^0-9]/. /\s/ Matches a whitespace character: /[ \t\r\n\f]/. /\S/ Matches non-whitespace: /[^ \t\r\n\f]/. /\w/ Matches a single word character: /[A-Za-z0-9_]/. /\W/ Matches a non-word character: /[^A-Za-z0-9_]/. /ruby?/ Matches "rub" or "ruby": the y is optional. /ruby*/ Matches "rub" plus 0 or more ys. /ruby+/ Matches "rub" plus 1 or more ys. /\d{3}/ Matches exactly 3 digits. /\d{3,}/ Matches 3 or more digits. /\d{3,5}/ Matches 3, 4, or 5 digits. This matches the smallest number of repetitions − /<.*>/ Greedy repetition: matches "<ruby>perl>". /<.*?>/ Non-greedy: matches "<ruby>" in "<ruby>perl>". /\D\d+/ No group: + repeats \d /(\D\d)+/ Grouped: + repeats \D\d pair /([Rr]uby(, )?)+/ Match "Ruby", "Ruby, ruby, ruby", etc. This matches a previously matched group again − /([Rr])uby&\1ails/ Matches ruby&rails or Ruby&Rails. /(['"])(?:(?!\1).)*\1/ Single or double-quoted string. \1 matches whatever the 1st group matched . \2 matches whatever the 2nd group matched, etc. /ruby|rube/ Matches "ruby" or "rube". /rub(y|le))/ Matches "ruby" or "ruble". /ruby(!+|\?)/ "ruby" followed by one or more ! or one ? It needs to specify match position. /^Ruby/ Matches "Ruby" at the start of a string or internal line. /Ruby$/ Matches "Ruby" at the end of a string or line. /\ARuby/ Matches "Ruby" at the start of a string. /Ruby\Z/ Matches "Ruby" at the end of a string. /\bRuby\b/ Matches "Ruby" at a word boundary. /\brub\B/ \B is non-word boundary: matches "rub" in "rube" and "ruby" but not alone. /Ruby(?=!)/ Matches "Ruby", if followed by an exclamation point. /Ruby(?!!)/ Matches "Ruby", if not followed by an exclamation point. /R(?#comment)/ Matches "R". All the rest is a comment. /R(?i)uby/ Case-insensitive while matching "uby". /R(?i:uby)/ Same as above. /rub(?:y|le))/ Group only without creating \1 backreference. Some of the most important String methods that use regular expressions are sub and gsub, and their in-place variants sub! and gsub!. All of these methods perform a search-and-replace operation using a Regexp pattern. The sub & sub! replaces the first occurrence of the pattern and gsub & gsub! replaces all occurrences. The sub and gsub returns a new string, leaving the original unmodified where as sub! and gsub! modify the string on which they are called. Following is the example − #!/usr/bin/ruby phone = "2004-959-559 #This is Phone Number" # Delete Ruby-style comments phone = phone.sub!(/#.*$/, "") puts "Phone Num : #{phone}" # Remove anything other than digits phone = phone.gsub!(/\D/, "") puts "Phone Num : #{phone}" This will produce the following result − Phone Num : 2004-959-559 Phone Num : 2004959559 Following is another example − #!/usr/bin/ruby text = "rails are rails, really good Ruby on Rails" # Change "rails" to "Rails" throughout text.gsub!("rails", "Rails") # Capitalize the word "Rails" throughout text.gsub!(/\brails\b/, "Rails") puts "#{text}" This will produce the following result − Rails are Rails, really good Ruby on Rails
[ { "code": null, "e": 2593, "s": 2428, "text": "A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a pattern." }, { "code": null, "e": 2711, "s": 2593, "text": "A regular expression literal is a pattern between slashes or between arbitrary delimiters followed by %r as follows −" }, { "code": null, "e": 2817, "s": 2711, "text": "/pattern/\n/pattern/im # option can be specified\n%r!/usr/local! # general delimited regular expression\n" }, { "code": null, "e": 3027, "s": 2817, "text": "#!/usr/bin/ruby\n\nline1 = \"Cats are smarter than dogs\";\nline2 = \"Dogs also like meat\";\n\nif ( line1 =~ /Cats(.*)/ )\n puts \"Line1 contains Cats\"\nend\nif ( line2 =~ /Cats(.*)/ )\n puts \"Line2 contains Dogs\"\nend" }, { "code": null, "e": 3068, "s": 3027, "text": "This will produce the following result −" }, { "code": null, "e": 3089, "s": 3068, "text": "Line1 contains Cats\n" }, { "code": null, "e": 3322, "s": 3089, "text": "Regular expression literals may include an optional modifier to control various aspects of matching. The modifier is specified after the second slash character, as shown previously and may be represented by one of these characters −" }, { "code": null, "e": 3324, "s": 3322, "text": "i" }, { "code": null, "e": 3357, "s": 3324, "text": "Ignores case when matching text." }, { "code": null, "e": 3359, "s": 3357, "text": "o" }, { "code": null, "e": 3446, "s": 3359, "text": "Performs #{} interpolations only once, the first time the regexp literal is evaluated." }, { "code": null, "e": 3448, "s": 3446, "text": "x" }, { "code": null, "e": 3511, "s": 3448, "text": "Ignores whitespace and allows comments in regular expressions." }, { "code": null, "e": 3513, "s": 3511, "text": "m" }, { "code": null, "e": 3580, "s": 3513, "text": "Matches multiple lines, recognizing newlines as normal characters." }, { "code": null, "e": 3588, "s": 3580, "text": "u,e,s,n" }, { "code": null, "e": 3754, "s": 3588, "text": "Interprets the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. If none of these modifiers is specified, the regular expression is assumed to use the source encoding." }, { "code": null, "e": 4018, "s": 3754, "text": "Like string literals delimited with %Q, Ruby allows you to begin your regular expressions with %r followed by a delimiter of your choice. This is useful when the pattern you are describing contains a lot of forward slash characters that you don't want to escape −" }, { "code": null, "e": 4156, "s": 4018, "text": "# Following matches a single slash character, no escape required\n%r|/|\n\n# Flag characters are allowed with this syntax, too\n%r[</(.*)>]i\n" }, { "code": null, "e": 4320, "s": 4156, "text": "Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \\), all characters match themselves. You can escape a control character by preceding it with a backslash." }, { "code": null, "e": 4322, "s": 4320, "text": "^" }, { "code": null, "e": 4349, "s": 4322, "text": "Matches beginning of line." }, { "code": null, "e": 4351, "s": 4349, "text": "$" }, { "code": null, "e": 4372, "s": 4351, "text": "Matches end of line." }, { "code": null, "e": 4374, "s": 4372, "text": "." }, { "code": null, "e": 4470, "s": 4374, "text": "Matches any single character except newline. Using m option allows it to match newline as well." }, { "code": null, "e": 4476, "s": 4470, "text": "[...]" }, { "code": null, "e": 4518, "s": 4476, "text": "Matches any single character in brackets." }, { "code": null, "e": 4525, "s": 4518, "text": "[^...]" }, { "code": null, "e": 4570, "s": 4525, "text": "Matches any single character not in brackets" }, { "code": null, "e": 4574, "s": 4570, "text": "re*" }, { "code": null, "e": 4629, "s": 4574, "text": "Matches 0 or more occurrences of preceding expression." }, { "code": null, "e": 4633, "s": 4629, "text": "re+" }, { "code": null, "e": 4687, "s": 4633, "text": "Matches 1 or more occurrence of preceding expression." }, { "code": null, "e": 4691, "s": 4687, "text": "re?" }, { "code": null, "e": 4742, "s": 4691, "text": "Matches 0 or 1 occurrence of preceding expression." }, { "code": null, "e": 4749, "s": 4742, "text": "re{ n}" }, { "code": null, "e": 4814, "s": 4749, "text": "Matches exactly n number of occurrences of preceding expression." }, { "code": null, "e": 4822, "s": 4814, "text": "re{ n,}" }, { "code": null, "e": 4877, "s": 4822, "text": "Matches n or more occurrences of preceding expression." }, { "code": null, "e": 4887, "s": 4877, "text": "re{ n, m}" }, { "code": null, "e": 4957, "s": 4887, "text": "Matches at least n and at most m occurrences of preceding expression." }, { "code": null, "e": 4962, "s": 4957, "text": "a| b" }, { "code": null, "e": 4985, "s": 4962, "text": "Matches either a or b." }, { "code": null, "e": 4990, "s": 4985, "text": "(re)" }, { "code": null, "e": 5045, "s": 4990, "text": "Groups regular expressions and remembers matched text." }, { "code": null, "e": 5052, "s": 5045, "text": "(?imx)" }, { "code": null, "e": 5170, "s": 5052, "text": "Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected." }, { "code": null, "e": 5178, "s": 5170, "text": "(?-imx)" }, { "code": null, "e": 5297, "s": 5178, "text": "Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected." }, { "code": null, "e": 5305, "s": 5297, "text": "(?: re)" }, { "code": null, "e": 5366, "s": 5305, "text": "Groups regular expressions without remembering matched text." }, { "code": null, "e": 5377, "s": 5366, "text": "(?imx: re)" }, { "code": null, "e": 5439, "s": 5377, "text": "Temporarily toggles on i, m, or x options within parentheses." }, { "code": null, "e": 5451, "s": 5439, "text": "(?-imx: re)" }, { "code": null, "e": 5514, "s": 5451, "text": "Temporarily toggles off i, m, or x options within parentheses." }, { "code": null, "e": 5522, "s": 5514, "text": "(?#...)" }, { "code": null, "e": 5531, "s": 5522, "text": "Comment." }, { "code": null, "e": 5539, "s": 5531, "text": "(?= re)" }, { "code": null, "e": 5597, "s": 5539, "text": "Specifies position using a pattern. Doesn't have a range." }, { "code": null, "e": 5605, "s": 5597, "text": "(?! re)" }, { "code": null, "e": 5670, "s": 5605, "text": "Specifies position using pattern negation. Doesn't have a range." }, { "code": null, "e": 5678, "s": 5670, "text": "(?> re)" }, { "code": null, "e": 5728, "s": 5678, "text": "Matches independent pattern without backtracking." }, { "code": null, "e": 5731, "s": 5728, "text": "\\w" }, { "code": null, "e": 5756, "s": 5731, "text": "Matches word characters." }, { "code": null, "e": 5759, "s": 5756, "text": "\\W" }, { "code": null, "e": 5787, "s": 5759, "text": "Matches nonword characters." }, { "code": null, "e": 5790, "s": 5787, "text": "\\s" }, { "code": null, "e": 5836, "s": 5790, "text": "Matches whitespace. Equivalent to [\\t\\n\\r\\f]." }, { "code": null, "e": 5839, "s": 5836, "text": "\\S" }, { "code": null, "e": 5862, "s": 5839, "text": "Matches nonwhitespace." }, { "code": null, "e": 5865, "s": 5862, "text": "\\d" }, { "code": null, "e": 5902, "s": 5865, "text": "Matches digits. Equivalent to [0-9]." }, { "code": null, "e": 5905, "s": 5902, "text": "\\D" }, { "code": null, "e": 5924, "s": 5905, "text": "Matches nondigits." }, { "code": null, "e": 5927, "s": 5924, "text": "\\A" }, { "code": null, "e": 5956, "s": 5927, "text": "Matches beginning of string." }, { "code": null, "e": 5959, "s": 5956, "text": "\\Z" }, { "code": null, "e": 6035, "s": 5959, "text": "Matches end of string. If a newline exists, it matches just before newline." }, { "code": null, "e": 6038, "s": 6035, "text": "\\z" }, { "code": null, "e": 6061, "s": 6038, "text": "Matches end of string." }, { "code": null, "e": 6064, "s": 6061, "text": "\\G" }, { "code": null, "e": 6105, "s": 6064, "text": "Matches point where last match finished." }, { "code": null, "e": 6108, "s": 6105, "text": "\\b" }, { "code": null, "e": 6202, "s": 6108, "text": "Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets." }, { "code": null, "e": 6205, "s": 6202, "text": "\\B" }, { "code": null, "e": 6234, "s": 6205, "text": "Matches non-word boundaries." }, { "code": null, "e": 6247, "s": 6234, "text": "\\n, \\t, etc." }, { "code": null, "e": 6294, "s": 6247, "text": "Matches newlines, carriage returns, tabs, etc." }, { "code": null, "e": 6302, "s": 6294, "text": "\\1...\\9" }, { "code": null, "e": 6337, "s": 6302, "text": "Matches nth grouped subexpression." }, { "code": null, "e": 6341, "s": 6337, "text": "\\10" }, { "code": null, "e": 6464, "s": 6341, "text": "Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code." }, { "code": null, "e": 6471, "s": 6464, "text": "/ruby/" }, { "code": null, "e": 6487, "s": 6471, "text": "Matches \"ruby\"." }, { "code": null, "e": 6489, "s": 6487, "text": "¥" }, { "code": null, "e": 6568, "s": 6489, "text": "Matches Yen sign. Multibyte characters are supported in Ruby 1.9 and Ruby 1.8." }, { "code": null, "e": 6578, "s": 6568, "text": "/[Rr]uby/" }, { "code": null, "e": 6604, "s": 6578, "text": "Matches \"Ruby\" or \"ruby\"." }, { "code": null, "e": 6614, "s": 6604, "text": "/rub[ye]/" }, { "code": null, "e": 6640, "s": 6614, "text": "Matches \"ruby\" or \"rube\"." }, { "code": null, "e": 6650, "s": 6640, "text": "/[aeiou]/" }, { "code": null, "e": 6683, "s": 6650, "text": "Matches any one lowercase vowel." }, { "code": null, "e": 6691, "s": 6683, "text": "/[0-9]/" }, { "code": null, "e": 6734, "s": 6691, "text": "Matches any digit; same as /[0123456789]/." }, { "code": null, "e": 6742, "s": 6734, "text": "/[a-z]/" }, { "code": null, "e": 6778, "s": 6742, "text": "Matches any lowercase ASCII letter." }, { "code": null, "e": 6786, "s": 6778, "text": "/[A-Z]/" }, { "code": null, "e": 6822, "s": 6786, "text": "Matches any uppercase ASCII letter." }, { "code": null, "e": 6836, "s": 6822, "text": "/[a-zA-Z0-9]/" }, { "code": null, "e": 6862, "s": 6836, "text": "Matches any of the above." }, { "code": null, "e": 6873, "s": 6862, "text": "/[^aeiou]/" }, { "code": null, "e": 6920, "s": 6873, "text": "Matches anything other than a lowercase vowel." }, { "code": null, "e": 6929, "s": 6920, "text": "/[^0-9]/" }, { "code": null, "e": 6966, "s": 6929, "text": "Matches anything other than a digit." }, { "code": null, "e": 6970, "s": 6966, "text": "/./" }, { "code": null, "e": 7008, "s": 6970, "text": "Matches any character except newline." }, { "code": null, "e": 7013, "s": 7008, "text": "/./m" }, { "code": null, "e": 7055, "s": 7013, "text": "In multi-line mode, matches newline, too." }, { "code": null, "e": 7060, "s": 7055, "text": "/\\d/" }, { "code": null, "e": 7086, "s": 7060, "text": "Matches a digit: /[0-9]/." }, { "code": null, "e": 7091, "s": 7086, "text": "/\\D/" }, { "code": null, "e": 7122, "s": 7091, "text": "Matches a non-digit: /[^0-9]/." }, { "code": null, "e": 7127, "s": 7122, "text": "/\\s/" }, { "code": null, "e": 7174, "s": 7127, "text": "Matches a whitespace character: /[ \\t\\r\\n\\f]/." }, { "code": null, "e": 7179, "s": 7174, "text": "/\\S/" }, { "code": null, "e": 7219, "s": 7179, "text": "Matches non-whitespace: /[^ \\t\\r\\n\\f]/." }, { "code": null, "e": 7224, "s": 7219, "text": "/\\w/" }, { "code": null, "e": 7273, "s": 7224, "text": "Matches a single word character: /[A-Za-z0-9_]/." }, { "code": null, "e": 7278, "s": 7273, "text": "/\\W/" }, { "code": null, "e": 7325, "s": 7278, "text": "Matches a non-word character: /[^A-Za-z0-9_]/." }, { "code": null, "e": 7333, "s": 7325, "text": "/ruby?/" }, { "code": null, "e": 7377, "s": 7333, "text": "Matches \"rub\" or \"ruby\": the y is optional." }, { "code": null, "e": 7385, "s": 7377, "text": "/ruby*/" }, { "code": null, "e": 7418, "s": 7385, "text": "Matches \"rub\" plus 0 or more ys." }, { "code": null, "e": 7426, "s": 7418, "text": "/ruby+/" }, { "code": null, "e": 7459, "s": 7426, "text": "Matches \"rub\" plus 1 or more ys." }, { "code": null, "e": 7467, "s": 7459, "text": "/\\d{3}/" }, { "code": null, "e": 7493, "s": 7467, "text": "Matches exactly 3 digits." }, { "code": null, "e": 7502, "s": 7493, "text": "/\\d{3,}/" }, { "code": null, "e": 7528, "s": 7502, "text": "Matches 3 or more digits." }, { "code": null, "e": 7538, "s": 7528, "text": "/\\d{3,5}/" }, { "code": null, "e": 7565, "s": 7538, "text": "Matches 3, 4, or 5 digits." }, { "code": null, "e": 7615, "s": 7565, "text": "This matches the smallest number of repetitions −" }, { "code": null, "e": 7622, "s": 7615, "text": "/<.*>/" }, { "code": null, "e": 7664, "s": 7622, "text": "Greedy repetition: matches \"<ruby>perl>\"." }, { "code": null, "e": 7672, "s": 7664, "text": "/<.*?>/" }, { "code": null, "e": 7719, "s": 7672, "text": "Non-greedy: matches \"<ruby>\" in \"<ruby>perl>\"." }, { "code": null, "e": 7727, "s": 7719, "text": "/\\D\\d+/" }, { "code": null, "e": 7750, "s": 7727, "text": "No group: + repeats \\d" }, { "code": null, "e": 7760, "s": 7750, "text": "/(\\D\\d)+/" }, { "code": null, "e": 7789, "s": 7760, "text": "Grouped: + repeats \\D\\d pair" }, { "code": null, "e": 7807, "s": 7789, "text": "/([Rr]uby(, )?)+/" }, { "code": null, "e": 7846, "s": 7807, "text": "Match \"Ruby\", \"Ruby, ruby, ruby\", etc." }, { "code": null, "e": 7894, "s": 7846, "text": "This matches a previously matched group again −" }, { "code": null, "e": 7913, "s": 7894, "text": "/([Rr])uby&\\1ails/" }, { "code": null, "e": 7947, "s": 7913, "text": "Matches ruby&rails or Ruby&Rails." }, { "code": null, "e": 7970, "s": 7947, "text": "/(['\"])(?:(?!\\1).)*\\1/" }, { "code": null, "e": 8094, "s": 7970, "text": "Single or double-quoted string. \\1 matches whatever the 1st group matched . \\2 matches whatever the 2nd group matched, etc." }, { "code": null, "e": 8106, "s": 8094, "text": "/ruby|rube/" }, { "code": null, "e": 8132, "s": 8106, "text": "Matches \"ruby\" or \"rube\"." }, { "code": null, "e": 8145, "s": 8132, "text": "/rub(y|le))/" }, { "code": null, "e": 8172, "s": 8145, "text": "Matches \"ruby\" or \"ruble\"." }, { "code": null, "e": 8186, "s": 8172, "text": "/ruby(!+|\\?)/" }, { "code": null, "e": 8228, "s": 8186, "text": "\"ruby\" followed by one or more ! or one ?" }, { "code": null, "e": 8264, "s": 8228, "text": "It needs to specify match position." }, { "code": null, "e": 8272, "s": 8264, "text": "/^Ruby/" }, { "code": null, "e": 8330, "s": 8272, "text": "Matches \"Ruby\" at the start of a string or internal line." }, { "code": null, "e": 8338, "s": 8330, "text": "/Ruby$/" }, { "code": null, "e": 8385, "s": 8338, "text": "Matches \"Ruby\" at the end of a string or line." }, { "code": null, "e": 8394, "s": 8385, "text": "/\\ARuby/" }, { "code": null, "e": 8435, "s": 8394, "text": "Matches \"Ruby\" at the start of a string." }, { "code": null, "e": 8444, "s": 8435, "text": "/Ruby\\Z/" }, { "code": null, "e": 8483, "s": 8444, "text": "Matches \"Ruby\" at the end of a string." }, { "code": null, "e": 8494, "s": 8483, "text": "/\\bRuby\\b/" }, { "code": null, "e": 8529, "s": 8494, "text": "Matches \"Ruby\" at a word boundary." }, { "code": null, "e": 8539, "s": 8529, "text": "/\\brub\\B/" }, { "code": null, "e": 8614, "s": 8539, "text": "\\B is non-word boundary: matches \"rub\" in \"rube\" and \"ruby\" but not alone." }, { "code": null, "e": 8626, "s": 8614, "text": "/Ruby(?=!)/" }, { "code": null, "e": 8679, "s": 8626, "text": "Matches \"Ruby\", if followed by an exclamation point." }, { "code": null, "e": 8691, "s": 8679, "text": "/Ruby(?!!)/" }, { "code": null, "e": 8748, "s": 8691, "text": "Matches \"Ruby\", if not followed by an exclamation point." }, { "code": null, "e": 8763, "s": 8748, "text": "/R(?#comment)/" }, { "code": null, "e": 8803, "s": 8763, "text": "Matches \"R\". All the rest is a comment." }, { "code": null, "e": 8814, "s": 8803, "text": "/R(?i)uby/" }, { "code": null, "e": 8853, "s": 8814, "text": "Case-insensitive while matching \"uby\"." }, { "code": null, "e": 8865, "s": 8853, "text": "/R(?i:uby)/" }, { "code": null, "e": 8880, "s": 8865, "text": "Same as above." }, { "code": null, "e": 8895, "s": 8880, "text": "/rub(?:y|le))/" }, { "code": null, "e": 8941, "s": 8895, "text": "Group only without creating \\1 backreference." }, { "code": null, "e": 9074, "s": 8941, "text": "Some of the most important String methods that use regular expressions are sub and gsub, and their in-place variants sub! and gsub!." }, { "code": null, "e": 9261, "s": 9074, "text": "All of these methods perform a search-and-replace operation using a Regexp pattern. The sub & sub! replaces the first occurrence of the pattern and gsub & gsub! replaces all occurrences." }, { "code": null, "e": 9400, "s": 9261, "text": "The sub and gsub returns a new string, leaving the original unmodified where as sub! and gsub! modify the string on which they are called." }, { "code": null, "e": 9427, "s": 9400, "text": "Following is the example −" }, { "code": null, "e": 9680, "s": 9427, "text": "#!/usr/bin/ruby\n\nphone = \"2004-959-559 #This is Phone Number\"\n\n# Delete Ruby-style comments\nphone = phone.sub!(/#.*$/, \"\") \nputs \"Phone Num : #{phone}\"\n\n# Remove anything other than digits\nphone = phone.gsub!(/\\D/, \"\") \nputs \"Phone Num : #{phone}\"" }, { "code": null, "e": 9721, "s": 9680, "text": "This will produce the following result −" }, { "code": null, "e": 9770, "s": 9721, "text": "Phone Num : 2004-959-559\nPhone Num : 2004959559\n" }, { "code": null, "e": 9801, "s": 9770, "text": "Following is another example −" }, { "code": null, "e": 10029, "s": 9801, "text": "#!/usr/bin/ruby\n\ntext = \"rails are rails, really good Ruby on Rails\"\n\n# Change \"rails\" to \"Rails\" throughout\ntext.gsub!(\"rails\", \"Rails\")\n\n# Capitalize the word \"Rails\" throughout\ntext.gsub!(/\\brails\\b/, \"Rails\")\nputs \"#{text}\"" }, { "code": null, "e": 10070, "s": 10029, "text": "This will produce the following result −" } ]
UInt32.MaxValue Field in C# with Examples
01 May, 2019 The MaxValue field of UInt32 Struct is used to represent the maximum value of the 32-bit unsigned integer. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 4294967295. Its hexadecimal value is 0xFFFFFFFF. It is used to avoid the OverflowException at run-time by verifying that an Int64 value is within the range of the UInt32 type before a type conversion. Syntax: public const uint MaxValue = 4294967295; Return Value: This field always returns 4294967295. Example: // C# program to illustrate the// UInt32.MaxValue fieldusing System; class GFG { // Main Method static public void Main() { // display the Maximum value // of UInt32 struct Console.WriteLine("Maximum Value is: " + UInt32.MaxValue); // Taking an array of the // unsigned long integer // i.e UInt64 data type ulong[] num = {3422146, 732443, 42343535776, 2342534654756123}; // taking variable of UInt32 type uint mynum; foreach(long n in num) { if (n >= UInt32.MinValue && n <= UInt32.MaxValue) { // using the method of Convert class // to convert Int64 to UInt32 mynum = Convert.ToUInt32(n); Console.WriteLine("Conversion is Possible."); } else { Console.WriteLine("Not Possible"); } } }} Output: Maximum Value is: 4294967295 Conversion is Possible. Conversion is Possible. Not Possible Not Possible Reference: https://docs.microsoft.com/en-us/dotnet/api/system.uint32.maxvalue?view=netstandard-2.1 CSharp-UInt32-Struct C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | Method Overriding C# | String.IndexOf( ) Method | Set - 1 C# | Constructors C# | Class and Object
[ { "code": null, "e": 28, "s": 0, "text": "\n01 May, 2019" }, { "code": null, "e": 458, "s": 28, "text": "The MaxValue field of UInt32 Struct is used to represent the maximum value of the 32-bit unsigned integer. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 4294967295. Its hexadecimal value is 0xFFFFFFFF. It is used to avoid the OverflowException at run-time by verifying that an Int64 value is within the range of the UInt32 type before a type conversion." }, { "code": null, "e": 466, "s": 458, "text": "Syntax:" }, { "code": null, "e": 507, "s": 466, "text": "public const uint MaxValue = 4294967295;" }, { "code": null, "e": 559, "s": 507, "text": "Return Value: This field always returns 4294967295." }, { "code": null, "e": 568, "s": 559, "text": "Example:" }, { "code": "// C# program to illustrate the// UInt32.MaxValue fieldusing System; class GFG { // Main Method static public void Main() { // display the Maximum value // of UInt32 struct Console.WriteLine(\"Maximum Value is: \" + UInt32.MaxValue); // Taking an array of the // unsigned long integer // i.e UInt64 data type ulong[] num = {3422146, 732443, 42343535776, 2342534654756123}; // taking variable of UInt32 type uint mynum; foreach(long n in num) { if (n >= UInt32.MinValue && n <= UInt32.MaxValue) { // using the method of Convert class // to convert Int64 to UInt32 mynum = Convert.ToUInt32(n); Console.WriteLine(\"Conversion is Possible.\"); } else { Console.WriteLine(\"Not Possible\"); } } }}", "e": 1513, "s": 568, "text": null }, { "code": null, "e": 1521, "s": 1513, "text": "Output:" }, { "code": null, "e": 1625, "s": 1521, "text": "Maximum Value is: 4294967295\nConversion is Possible.\nConversion is Possible.\nNot Possible\nNot Possible\n" }, { "code": null, "e": 1636, "s": 1625, "text": "Reference:" }, { "code": null, "e": 1724, "s": 1636, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.uint32.maxvalue?view=netstandard-2.1" }, { "code": null, "e": 1745, "s": 1724, "text": "CSharp-UInt32-Struct" }, { "code": null, "e": 1748, "s": 1745, "text": "C#" }, { "code": null, "e": 1846, "s": 1748, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1874, "s": 1846, "text": "C# Dictionary with examples" }, { "code": null, "e": 1917, "s": 1874, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 1948, "s": 1917, "text": "Introduction to .NET Framework" }, { "code": null, "e": 1963, "s": 1948, "text": "C# | Delegates" }, { "code": null, "e": 2012, "s": 1963, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2028, "s": 2012, "text": "C# | Data Types" }, { "code": null, "e": 2051, "s": 2028, "text": "C# | Method Overriding" }, { "code": null, "e": 2091, "s": 2051, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 2109, "s": 2091, "text": "C# | Constructors" } ]
How to Find Standard Deviation in R?
07 Apr, 2021 In this article, we will discuss how to find the Standard Deviation in R Programming Language. Standard deviation is the measure of the dispersion of the values. It can also be defined as the square root of variance. Formula of sample standard deviation: where, s = sample standard deviation N = Number of entities = Mean of entities Basically, there are two different ways to calculate standard Deviation in R Programming language, both of them are discussed below. In this method of calculating the standard deviation, we will be using the above standard formula of the sample standard deviation in R language. Example 1: R v <- c(12,24,74,32,14,29,84,56,67,41) s<-sqrt(sum((v-mean(v))^2/(length(v)-1))) print(s) Output: [1] 25.53886 Example 2: R v <- c(1.8,3.7,9.2,4.7,6.1,2.8,6.1,2.2,1.4,7.9) s<-sqrt(sum((v-mean(v))^2/(length(v)-1))) print(s) Output: [1] 2.676004 The sd() function is used to return the standard deviation. Syntax: sd(x, na.rm = FALSE) Parameters: x: a numeric vector, matrix or data frame. na.rm: missing values be removed? Return: The sample standard deviation of x. Example 1: R v <- c(12,24,74,32,14,29,84,56,67,41) s<-sd(v) print(s) Output: [1] 25.53886 Example 2: R v <- c(71,48,98,65,45,27,39,61,50,24,17) s1<-sqrt(sum((v-mean(v))^2/(length(v)-1)))print(s1) s2<-sd(v)print(s2) Output: [1] 23.52175 Example 3: R v <- c(1.8,3.7,9.2,4.7,6.1,2.8,6.1,2.2,1.4,7.9) s1<-sqrt(sum((v-mean(v))^2/(length(v)-1)))print(s1) s2<-sd(v)print(s2) Output: [1] 2.676004 Picked R-Mathematics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2021" }, { "code": null, "e": 245, "s": 28, "text": "In this article, we will discuss how to find the Standard Deviation in R Programming Language. Standard deviation is the measure of the dispersion of the values. It can also be defined as the square root of variance." }, { "code": null, "e": 283, "s": 245, "text": "Formula of sample standard deviation:" }, { "code": null, "e": 291, "s": 283, "text": "where, " }, { "code": null, "e": 321, "s": 291, "text": "s = sample standard deviation" }, { "code": null, "e": 344, "s": 321, "text": "N = Number of entities" }, { "code": null, "e": 364, "s": 344, "text": " = Mean of entities" }, { "code": null, "e": 497, "s": 364, "text": "Basically, there are two different ways to calculate standard Deviation in R Programming language, both of them are discussed below." }, { "code": null, "e": 644, "s": 497, "text": "In this method of calculating the standard deviation, we will be using the above standard formula of the sample standard deviation in R language. " }, { "code": null, "e": 655, "s": 644, "text": "Example 1:" }, { "code": null, "e": 657, "s": 655, "text": "R" }, { "code": "v <- c(12,24,74,32,14,29,84,56,67,41) s<-sqrt(sum((v-mean(v))^2/(length(v)-1))) print(s)", "e": 748, "s": 657, "text": null }, { "code": null, "e": 756, "s": 748, "text": "Output:" }, { "code": null, "e": 769, "s": 756, "text": "[1] 25.53886" }, { "code": null, "e": 780, "s": 769, "text": "Example 2:" }, { "code": null, "e": 782, "s": 780, "text": "R" }, { "code": "v <- c(1.8,3.7,9.2,4.7,6.1,2.8,6.1,2.2,1.4,7.9) s<-sqrt(sum((v-mean(v))^2/(length(v)-1))) print(s)", "e": 883, "s": 782, "text": null }, { "code": null, "e": 891, "s": 883, "text": "Output:" }, { "code": null, "e": 904, "s": 891, "text": "[1] 2.676004" }, { "code": null, "e": 964, "s": 904, "text": "The sd() function is used to return the standard deviation." }, { "code": null, "e": 993, "s": 964, "text": "Syntax: sd(x, na.rm = FALSE)" }, { "code": null, "e": 1005, "s": 993, "text": "Parameters:" }, { "code": null, "e": 1048, "s": 1005, "text": "x: a numeric vector, matrix or data frame." }, { "code": null, "e": 1082, "s": 1048, "text": "na.rm: missing values be removed?" }, { "code": null, "e": 1126, "s": 1082, "text": "Return: The sample standard deviation of x." }, { "code": null, "e": 1137, "s": 1126, "text": "Example 1:" }, { "code": null, "e": 1139, "s": 1137, "text": "R" }, { "code": "v <- c(12,24,74,32,14,29,84,56,67,41) s<-sd(v) print(s)", "e": 1197, "s": 1139, "text": null }, { "code": null, "e": 1205, "s": 1197, "text": "Output:" }, { "code": null, "e": 1218, "s": 1205, "text": "[1] 25.53886" }, { "code": null, "e": 1229, "s": 1218, "text": "Example 2:" }, { "code": null, "e": 1231, "s": 1229, "text": "R" }, { "code": "v <- c(71,48,98,65,45,27,39,61,50,24,17) s1<-sqrt(sum((v-mean(v))^2/(length(v)-1)))print(s1) s2<-sd(v)print(s2)", "e": 1345, "s": 1231, "text": null }, { "code": null, "e": 1353, "s": 1345, "text": "Output:" }, { "code": null, "e": 1366, "s": 1353, "text": "[1] 23.52175" }, { "code": null, "e": 1377, "s": 1366, "text": "Example 3:" }, { "code": null, "e": 1379, "s": 1377, "text": "R" }, { "code": "v <- c(1.8,3.7,9.2,4.7,6.1,2.8,6.1,2.2,1.4,7.9) s1<-sqrt(sum((v-mean(v))^2/(length(v)-1)))print(s1) s2<-sd(v)print(s2)", "e": 1500, "s": 1379, "text": null }, { "code": null, "e": 1508, "s": 1500, "text": "Output:" }, { "code": null, "e": 1521, "s": 1508, "text": "[1] 2.676004" }, { "code": null, "e": 1528, "s": 1521, "text": "Picked" }, { "code": null, "e": 1542, "s": 1528, "text": "R-Mathematics" }, { "code": null, "e": 1553, "s": 1542, "text": "R Language" }, { "code": null, "e": 1651, "s": 1553, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1703, "s": 1651, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1761, "s": 1703, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1796, "s": 1761, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1834, "s": 1796, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1883, "s": 1834, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1900, "s": 1883, "text": "R - if statement" }, { "code": null, "e": 1937, "s": 1900, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 1980, "s": 1937, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2017, "s": 1980, "text": "How to import an Excel File into R ?" } ]
Maximum of all subarrays of size k | Practice | GeeksforGeeks
Given an array arr[] of size N and an integer K. Find the maximum for each and every contiguous subarray of size K. Example 1: Input: N = 9, K = 3 arr[] = 1 2 3 1 4 5 2 3 6 Output: 3 3 4 5 5 5 6 Explanation: 1st contiguous subarray = {1 2 3} Max = 3 2nd contiguous subarray = {2 3 1} Max = 3 3rd contiguous subarray = {3 1 4} Max = 4 4th contiguous subarray = {1 4 5} Max = 5 5th contiguous subarray = {4 5 2} Max = 5 6th contiguous subarray = {5 2 3} Max = 5 7th contiguous subarray = {2 3 6} Max = 6 Example 2: Input: N = 10, K = 4 arr[] = 8 5 10 7 9 4 15 12 90 13 Output: 10 10 10 15 15 90 90 Explanation: 1st contiguous subarray = {8 5 10 7}, Max = 10 2nd contiguous subarray = {5 10 7 9}, Max = 10 3rd contiguous subarray = {10 7 9 4}, Max = 10 4th contiguous subarray = {7 9 4 15}, Max = 15 5th contiguous subarray = {9 4 15 12}, Max = 15 6th contiguous subarray = {4 15 12 90}, Max = 90 7th contiguous subarray = {15 12 90 13}, Max = 90 Your Task: You dont need to read input or print anything. Complete the function max_of_subarrays() which takes the array, N and K as input parameters and returns a list of integers denoting the maximum of every contiguous subarray of size K. Expected Time Complexity: O(N) Expected Auxiliary Space: O(k) Constraints: 1 ≤ N ≤ 107 1 ≤ K ≤ N 0 ≤ arr[i] ≤ 107 0 vvwlolwhat8 hours ago static ArrayList <Integer> max_of_subarrays(int a[], int n, int k) { ArrayList<Integer> maxList = new ArrayList<>(); int max; for (int i = 0; i < n - k + 1; i++) { max = Integer.MIN_VALUE; for (int j = i; j < k + i; j++) { if (a[j] > max) max = a[j]; } maxList.add(max); } return maxList; } 0 mohitpandey38915 hours ago class Solution { public: vector <int> max_of_subarrays(int *arr, int n, int k) { vector<int> ans; list<int> l; int i=0; int j=0; while(j<n){ while(!l.empty()&&l.back()<arr[j]){ l.pop_back(); } l.push_back(arr[j]); if(j-i+1==k){ ans.push_back(l.front()); if(arr[i]==l.front()){ l.pop_front(); } i++; } j++; } return ans; } }; 0 shishir17pandey2 days ago vector <int> max_of_subarrays(int *arr, int n, int k) { // multiset<int,greater<int>>s; vector<int>v; for(int i=0;i<k;i++){ s.insert(arr[i]); } v.push_back(*s.begin()); for(int i=k;i<n;i++){ s.erase(s.lower_bound(arr[i-k])); s.insert(arr[i]); v.push_back(*s.begin()); } return v; } 0 priyxnshi2 days ago it fails after 94 test cases, can someone help me optimize the code? vector <int> max_of_subarrays(int *arr, int n, int k) { // your code here vector<int>ans; for(int i=0;i<=n-k;i++){ int max=arr[i]; for(int j=1;j<k;j++){ if(arr[i+j]>max){ max=arr[i+j]; } } ans.push_back(max); } return ans; } 0 shrutidsms2 days ago can somebody please tell me what's wrong with this code ArrayList<Integer> ans = new ArrayList<>(); int start = 0; int end = k-1; int max = Integer.MIN_VALUE; while( end < n){ for(int i = start; i < end; i++){ max = Math.max(Math.max(arr[i], arr[i+1]), max); } ans.add(max); start++; end++; } return ans; 0 nabilmurshedpkt This comment was deleted. 0 nabilmurshedpkt This comment was deleted. -3 yashbiyani3 days ago 100% Accuracy | JAVA SOLUTION class Solution { //Function to find maximum of each subarray of size k. static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k) { // Your code here ArrayList<Integer> list=new ArrayList<Integer>(); int max=0; for(int i=0;i<=n-k;i++) { max=arr[i]; for(int j=i+1;j<i+k;j++) { max=Math.max(arr[j],max); } list.add(max); } return list; } } 0 dmahindrakar054 days ago //Java //sliding window static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k) { int i=0,j=0; ArrayList <Integer> res = new ArrayList<Integer>(); int count =0; while(j<=n){ if(count<k){ count++; j++; }else if(count==k){ int m =i; int nn =j; //System.out.println(m+" "+nn); int max =0; while(m<nn){ max =Math.max(max,arr[m]); m++; } res.add(max); count++; j++; }else{ count--; i++; } } return res; } 0 sumitsinghrajput786gwalior5 days ago // Java static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k) { // Your code here ArrayList<Integer> ans = new ArrayList<>(); PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); int i=0, j=0; while(i<n){ pq.add(arr[i]); if(i-j==k-1){ ans.add(pq.peek()); i++; } else if(i-j<k-1){ i++; } else{ while(i-j>k-1 && !pq.isEmpty()){ pq.remove(arr[j]); j++; } ans.add(pq.peek()); i++; } } return ans; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 354, "s": 238, "text": "Given an array arr[] of size N and an integer K. Find the maximum for each and every contiguous subarray of size K." }, { "code": null, "e": 365, "s": 354, "text": "Example 1:" }, { "code": null, "e": 743, "s": 365, "text": "Input:\nN = 9, K = 3\narr[] = 1 2 3 1 4 5 2 3 6\nOutput: \n3 3 4 5 5 5 6 \nExplanation: \n1st contiguous subarray = {1 2 3} Max = 3\n2nd contiguous subarray = {2 3 1} Max = 3\n3rd contiguous subarray = {3 1 4} Max = 4\n4th contiguous subarray = {1 4 5} Max = 5\n5th contiguous subarray = {4 5 2} Max = 5\n6th contiguous subarray = {5 2 3} Max = 5\n7th contiguous subarray = {2 3 6} Max = 6" }, { "code": null, "e": 754, "s": 743, "text": "Example 2:" }, { "code": null, "e": 1190, "s": 754, "text": "Input:\nN = 10, K = 4\narr[] = 8 5 10 7 9 4 15 12 90 13\nOutput: \n10 10 10 15 15 90 90\nExplanation: \n1st contiguous subarray = {8 5 10 7}, Max = 10\n2nd contiguous subarray = {5 10 7 9}, Max = 10\n3rd contiguous subarray = {10 7 9 4}, Max = 10\n4th contiguous subarray = {7 9 4 15}, Max = 15\n5th contiguous subarray = {9 4 15 12}, \nMax = 15\n6th contiguous subarray = {4 15 12 90},\nMax = 90\n7th contiguous subarray = {15 12 90 13}, \nMax = 90\n" }, { "code": null, "e": 1434, "s": 1190, "text": "Your Task: \nYou dont need to read input or print anything. Complete the function max_of_subarrays() which takes the array, N and K as input parameters and returns a list of integers denoting the maximum of every contiguous subarray of size K." }, { "code": null, "e": 1496, "s": 1434, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(k)" }, { "code": null, "e": 1548, "s": 1496, "text": "Constraints:\n1 ≤ N ≤ 107\n1 ≤ K ≤ N\n0 ≤ arr[i] ≤ 107" }, { "code": null, "e": 1550, "s": 1548, "text": "0" }, { "code": null, "e": 1572, "s": 1550, "text": "vvwlolwhat8 hours ago" }, { "code": null, "e": 1955, "s": 1572, "text": " static ArrayList <Integer> max_of_subarrays(int a[], int n, int k) { ArrayList<Integer> maxList = new ArrayList<>(); int max; for (int i = 0; i < n - k + 1; i++) { max = Integer.MIN_VALUE; for (int j = i; j < k + i; j++) { if (a[j] > max) max = a[j]; } maxList.add(max); } return maxList; }" }, { "code": null, "e": 1957, "s": 1955, "text": "0" }, { "code": null, "e": 1984, "s": 1957, "text": "mohitpandey38915 hours ago" }, { "code": null, "e": 2556, "s": 1984, "text": "class Solution\n{\n public:\n \n vector <int> max_of_subarrays(int *arr, int n, int k)\n {\n vector<int> ans;\n list<int> l;\n int i=0;\n int j=0;\n while(j<n){\n while(!l.empty()&&l.back()<arr[j]){\n l.pop_back();\n }\n l.push_back(arr[j]);\n if(j-i+1==k){\n ans.push_back(l.front());\n if(arr[i]==l.front()){\n l.pop_front();\n }\n i++;\n }\n j++;\n }\n return ans;\n }\n};" }, { "code": null, "e": 2558, "s": 2556, "text": "0" }, { "code": null, "e": 2584, "s": 2558, "text": "shishir17pandey2 days ago" }, { "code": null, "e": 2973, "s": 2584, "text": " vector <int> max_of_subarrays(int *arr, int n, int k) { // multiset<int,greater<int>>s; vector<int>v; for(int i=0;i<k;i++){ s.insert(arr[i]); } v.push_back(*s.begin()); for(int i=k;i<n;i++){ s.erase(s.lower_bound(arr[i-k])); s.insert(arr[i]); v.push_back(*s.begin()); } return v; }" }, { "code": null, "e": 2975, "s": 2973, "text": "0" }, { "code": null, "e": 2995, "s": 2975, "text": "priyxnshi2 days ago" }, { "code": null, "e": 3064, "s": 2995, "text": "it fails after 94 test cases, can someone help me optimize the code?" }, { "code": null, "e": 3410, "s": 3064, "text": " vector <int> max_of_subarrays(int *arr, int n, int k) { // your code here vector<int>ans; for(int i=0;i<=n-k;i++){ int max=arr[i]; for(int j=1;j<k;j++){ if(arr[i+j]>max){ max=arr[i+j]; } } ans.push_back(max); } return ans; }" }, { "code": null, "e": 3412, "s": 3410, "text": "0" }, { "code": null, "e": 3433, "s": 3412, "text": "shrutidsms2 days ago" }, { "code": null, "e": 3489, "s": 3433, "text": "can somebody please tell me what's wrong with this code" }, { "code": null, "e": 3880, "s": 3489, "text": "ArrayList<Integer> ans = new ArrayList<>();\n \n int start = 0;\n int end = k-1;\n int max = Integer.MIN_VALUE;\n \n while( end < n){\n for(int i = start; i < end; i++){\n max = Math.max(Math.max(arr[i], arr[i+1]), max);\n }\n ans.add(max);\n start++;\n end++;\n }\n return ans;" }, { "code": null, "e": 3882, "s": 3880, "text": "0" }, { "code": null, "e": 3898, "s": 3882, "text": "nabilmurshedpkt" }, { "code": null, "e": 3924, "s": 3898, "text": "This comment was deleted." }, { "code": null, "e": 3926, "s": 3924, "text": "0" }, { "code": null, "e": 3942, "s": 3926, "text": "nabilmurshedpkt" }, { "code": null, "e": 3968, "s": 3942, "text": "This comment was deleted." }, { "code": null, "e": 3971, "s": 3968, "text": "-3" }, { "code": null, "e": 3992, "s": 3971, "text": "yashbiyani3 days ago" }, { "code": null, "e": 4022, "s": 3992, "text": "100% Accuracy | JAVA SOLUTION" }, { "code": null, "e": 4519, "s": 4022, "text": "class Solution\n{\n //Function to find maximum of each subarray of size k.\n static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k)\n {\n // Your code here\n ArrayList<Integer> list=new ArrayList<Integer>();\n int max=0;\n for(int i=0;i<=n-k;i++)\n {\n max=arr[i];\n for(int j=i+1;j<i+k;j++)\n {\n max=Math.max(arr[j],max);\n }\n list.add(max);\n }\n return list;\n }\n}" }, { "code": null, "e": 4523, "s": 4521, "text": "0" }, { "code": null, "e": 4548, "s": 4523, "text": "dmahindrakar054 days ago" }, { "code": null, "e": 4572, "s": 4548, "text": "//Java //sliding window" }, { "code": null, "e": 5262, "s": 4572, "text": "static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k) { int i=0,j=0; ArrayList <Integer> res = new ArrayList<Integer>(); int count =0; while(j<=n){ if(count<k){ count++; j++; }else if(count==k){ int m =i; int nn =j; //System.out.println(m+\" \"+nn); int max =0; while(m<nn){ max =Math.max(max,arr[m]); m++; } res.add(max); count++; j++; }else{ count--; i++; } } return res; }" }, { "code": null, "e": 5266, "s": 5264, "text": "0" }, { "code": null, "e": 5303, "s": 5266, "text": "sumitsinghrajput786gwalior5 days ago" }, { "code": null, "e": 5311, "s": 5303, "text": "// Java" }, { "code": null, "e": 6004, "s": 5313, "text": "static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k) { // Your code here ArrayList<Integer> ans = new ArrayList<>(); PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); int i=0, j=0; while(i<n){ pq.add(arr[i]); if(i-j==k-1){ ans.add(pq.peek()); i++; } else if(i-j<k-1){ i++; } else{ while(i-j>k-1 && !pq.isEmpty()){ pq.remove(arr[j]); j++; } ans.add(pq.peek()); i++; } } return ans; }" }, { "code": null, "e": 6150, "s": 6004, "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": 6186, "s": 6150, "text": " Login to access your submissions. " }, { "code": null, "e": 6196, "s": 6186, "text": "\nProblem\n" }, { "code": null, "e": 6206, "s": 6196, "text": "\nContest\n" }, { "code": null, "e": 6269, "s": 6206, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6454, "s": 6269, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6738, "s": 6454, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 6884, "s": 6738, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 6961, "s": 6884, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 7002, "s": 6961, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 7030, "s": 7002, "text": "Disable browser extensions." }, { "code": null, "e": 7101, "s": 7030, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 7288, "s": 7101, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Ruby - Variables, Constants and Literals
Variables are the memory locations, which hold any data to be used by any program. There are five types of variables supported by Ruby. You already have gone through a small description of these variables in the previous chapter as well. These five types of variables are explained in this chapter. Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option. Assignment to global variables alters the global status. It is not recommended to use global variables. They make programs cryptic. Here is an example showing the usage of global variable. #!/usr/bin/ruby $global_variable = 10 class Class1 def print_global puts "Global variable in Class1 is #$global_variable" end end class Class2 def print_global puts "Global variable in Class2 is #$global_variable" end end class1obj = Class1.new class1obj.print_global class2obj = Class2.new class2obj.print_global Here $global_variable is a global variable. This will produce the following result − NOTE − In Ruby, you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant. Global variable in Class1 is 10 Global variable in Class2 is 10 Instance variables begin with @. Uninitialized instance variables have the value nil and produce warnings with the -w option. Here is an example showing the usage of Instance Variables. #!/usr/bin/ruby class Customer def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end end # Create Objects cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2 = Customer.new("2", "Poul", "New Empire road, Khandala") # Call Methods cust1.display_details() cust2.display_details() Here, @cust_id, @cust_name and @cust_addr are instance variables. This will produce the following result − Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya Customer id 2 Customer name Poul Customer address New Empire road, Khandala Class variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined. Overriding class variables produce warnings with the -w option. Here is an example showing the usage of class variable − #!/usr/bin/ruby class Customer @@no_of_customers = 0 def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" end end # Create Objects cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2 = Customer.new("2", "Poul", "New Empire road, Khandala") # Call Methods cust1.total_no_of_customers() cust2.total_no_of_customers() Here @@no_of_customers is a class variable. This will produce the following result − Total number of customers: 1 Total number of customers: 2 Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block's opening brace to its close brace {}. When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments. Assignment to uninitialized local variables also serves as variable declaration. The variables start to exist until the end of the current scope is reached. The lifetime of local variables is determined when Ruby parses the program. In the above example, local variables are id, name and addr. Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning. #!/usr/bin/ruby class Example VAR1 = 100 VAR2 = 200 def show puts "Value of first Constant is #{VAR1}" puts "Value of second Constant is #{VAR2}" end end # Create Objects object = Example.new() object.show Here VAR1 and VAR2 are constants. This will produce the following result − Value of first Constant is 100 Value of second Constant is 200 They are special variables that have the appearance of local variables but behave like constants. You cannot assign any value to these variables. self − The receiver object of the current method. self − The receiver object of the current method. true − Value representing true. true − Value representing true. false − Value representing false. false − Value representing false. nil − Value representing undefined. nil − Value representing undefined. __FILE__ − The name of the current source file. __FILE__ − The name of the current source file. __LINE__ − The current line number in the source file. __LINE__ − The current line number in the source file. The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals. Ruby supports integer numbers. An integer number can range from -230 to 230-1 or -262 to 262-1. Integers within this range are objects of class Fixnum and integers outside this range are stored in objects of class Bignum. You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string. You can also get the integer value, corresponding to an ASCII character or escape the sequence by preceding it with a question mark. 123 # Fixnum decimal 1_234 # Fixnum decimal with underline -500 # Negative Fixnum 0377 # octal 0xff # hexadecimal 0b1011 # binary ?a # character code for 'a' ?\n # code for a newline (0x0a) 12345678901234567890 # Bignum NOTE − Class and Objects are explained in a separate chapter of this tutorial. Ruby supports floating numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following − 123.4 # floating point value 1.0e6 # scientific notation 4E20 # dot not required 4e+20 # sign before exponential Ruby strings are simply sequences of 8-bit bytes and they are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings don't allow substitution and allow backslash notation only for \\ and \' #!/usr/bin/ruby -w puts 'escape using "\\"'; puts 'That\'s right'; This will produce the following result − escape using "\" That's right You can substitute the value of any Ruby expression into a string using the sequence #{ expr }. Here, expr could be any ruby expression. #!/usr/bin/ruby -w puts "Multiplication Value : #{24*60*60}"; This will produce the following result − Multiplication Value : 86400 Following is the list of Backslash notations supported by Ruby − For more detail on Ruby Strings, go through Ruby Strings. Literals of Ruby Array are created by placing a comma-separated series of object references between the square brackets. A trailing comma is ignored. #!/usr/bin/ruby ary = [ "fred", 10, 3.14, "This is a string", "last element", ] ary.each do |i| puts i end This will produce the following result − fred 10 3.14 This is a string last element For more detail on Ruby Arrays, go through Ruby Arrays. A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence => between the key and the value. A trailing comma is ignored. #!/usr/bin/ruby hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f } hsh.each do |key, value| print key, " is ", value, "\n" end This will produce the following result − red is 3840 green is 240 blue is 15 For more detail on Ruby Hashes, go through Ruby Hashes. A Range represents an interval which is a set of values with a start and an end. Ranges may be constructed using the s..e and s...e literals, or with Range.new. Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value. When used as an iterator, ranges return each value in the sequence. A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1...5) means it includes 1, 2, 3, 4 values. #!/usr/bin/ruby (10..15).each do |n| print n, ' ' end This will produce the following result − 10 11 12 13 14 15 For more detail on Ruby Ranges, go through Ruby Ranges. 46 Lectures 9.5 hours Eduonix Learning Solutions 97 Lectures 7.5 hours Skillbakerystudios 227 Lectures 40 hours YouAccel 19 Lectures 10 hours Programming Line 51 Lectures 5 hours Stone River ELearning 39 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2377, "s": 2294, "text": "Variables are the memory locations, which hold any data to be used by any program." }, { "code": null, "e": 2593, "s": 2377, "text": "There are five types of variables supported by Ruby. You already have gone through a small description of these variables in the previous chapter as well. These five types of variables are explained in this chapter." }, { "code": null, "e": 2715, "s": 2593, "text": "Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option." }, { "code": null, "e": 2847, "s": 2715, "text": "Assignment to global variables alters the global status. It is not recommended to use global variables. They make programs cryptic." }, { "code": null, "e": 2904, "s": 2847, "text": "Here is an example showing the usage of global variable." }, { "code": null, "e": 3244, "s": 2904, "text": "#!/usr/bin/ruby\n\n$global_variable = 10\nclass Class1\n def print_global\n puts \"Global variable in Class1 is #$global_variable\"\n end\nend\nclass Class2\n def print_global\n puts \"Global variable in Class2 is #$global_variable\"\n end\nend\n\nclass1obj = Class1.new\nclass1obj.print_global\nclass2obj = Class2.new\nclass2obj.print_global" }, { "code": null, "e": 3329, "s": 3244, "text": "Here $global_variable is a global variable. This will produce the following result −" }, { "code": null, "e": 3465, "s": 3329, "text": "NOTE − In Ruby, you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant." }, { "code": null, "e": 3530, "s": 3465, "text": "Global variable in Class1 is 10\nGlobal variable in Class2 is 10\n" }, { "code": null, "e": 3656, "s": 3530, "text": "Instance variables begin with @. Uninitialized instance variables have the value nil and produce warnings with the -w option." }, { "code": null, "e": 3716, "s": 3656, "text": "Here is an example showing the usage of Instance Variables." }, { "code": null, "e": 4218, "s": 3716, "text": "#!/usr/bin/ruby\n\nclass Customer\n def initialize(id, name, addr)\n @cust_id = id\n @cust_name = name\n @cust_addr = addr\n end\n def display_details()\n puts \"Customer id #@cust_id\"\n puts \"Customer name #@cust_name\"\n puts \"Customer address #@cust_addr\"\n end\nend\n\n# Create Objects\ncust1 = Customer.new(\"1\", \"John\", \"Wisdom Apartments, Ludhiya\")\ncust2 = Customer.new(\"2\", \"Poul\", \"New Empire road, Khandala\")\n\n# Call Methods\ncust1.display_details()\ncust2.display_details()" }, { "code": null, "e": 4325, "s": 4218, "text": "Here, @cust_id, @cust_name and @cust_addr are instance variables. This will produce the following result −" }, { "code": null, "e": 4479, "s": 4325, "text": "Customer id 1\nCustomer name John\nCustomer address Wisdom Apartments, Ludhiya\nCustomer id 2\nCustomer name Poul\nCustomer address New Empire road, Khandala\n" }, { "code": null, "e": 4580, "s": 4479, "text": "Class variables begin with @@ and must be initialized before they can be used in method definitions." }, { "code": null, "e": 4753, "s": 4580, "text": "Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined." }, { "code": null, "e": 4817, "s": 4753, "text": "Overriding class variables produce warnings with the -w option." }, { "code": null, "e": 4874, "s": 4817, "text": "Here is an example showing the usage of class variable −" }, { "code": null, "e": 5539, "s": 4874, "text": "#!/usr/bin/ruby\n\nclass Customer\n @@no_of_customers = 0\n def initialize(id, name, addr)\n @cust_id = id\n @cust_name = name\n @cust_addr = addr\n end\n def display_details()\n puts \"Customer id #@cust_id\"\n puts \"Customer name #@cust_name\"\n puts \"Customer address #@cust_addr\"\n end\n def total_no_of_customers()\n @@no_of_customers += 1\n puts \"Total number of customers: #@@no_of_customers\"\n end\nend\n\n# Create Objects\ncust1 = Customer.new(\"1\", \"John\", \"Wisdom Apartments, Ludhiya\")\ncust2 = Customer.new(\"2\", \"Poul\", \"New Empire road, Khandala\")\n\n# Call Methods\ncust1.total_no_of_customers()\ncust2.total_no_of_customers()" }, { "code": null, "e": 5624, "s": 5539, "text": "Here @@no_of_customers is a class variable. This will produce the following result −" }, { "code": null, "e": 5683, "s": 5624, "text": "Total number of customers: 1\nTotal number of customers: 2\n" }, { "code": null, "e": 5883, "s": 5683, "text": "Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block's opening brace to its close brace {}." }, { "code": null, "e": 5998, "s": 5883, "text": "When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments." }, { "code": null, "e": 6231, "s": 5998, "text": "Assignment to uninitialized local variables also serves as variable declaration. The variables start to exist until the end of the current scope is reached. The lifetime of local variables is determined when Ruby parses the program." }, { "code": null, "e": 6292, "s": 6231, "text": "In the above example, local variables are id, name and addr." }, { "code": null, "e": 6497, "s": 6292, "text": "Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally." }, { "code": null, "e": 6682, "s": 6497, "text": "Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning." }, { "code": null, "e": 6914, "s": 6682, "text": "#!/usr/bin/ruby\n\nclass Example\n VAR1 = 100\n VAR2 = 200\n def show\n puts \"Value of first Constant is #{VAR1}\"\n puts \"Value of second Constant is #{VAR2}\"\n end\nend\n\n# Create Objects\nobject = Example.new()\nobject.show" }, { "code": null, "e": 6989, "s": 6914, "text": "Here VAR1 and VAR2 are constants. This will produce the following result −" }, { "code": null, "e": 7053, "s": 6989, "text": "Value of first Constant is 100\nValue of second Constant is 200\n" }, { "code": null, "e": 7199, "s": 7053, "text": "They are special variables that have the appearance of local variables but behave like constants. You cannot assign any value to these variables." }, { "code": null, "e": 7249, "s": 7199, "text": "self − The receiver object of the current method." }, { "code": null, "e": 7299, "s": 7249, "text": "self − The receiver object of the current method." }, { "code": null, "e": 7331, "s": 7299, "text": "true − Value representing true." }, { "code": null, "e": 7363, "s": 7331, "text": "true − Value representing true." }, { "code": null, "e": 7397, "s": 7363, "text": "false − Value representing false." }, { "code": null, "e": 7431, "s": 7397, "text": "false − Value representing false." }, { "code": null, "e": 7467, "s": 7431, "text": "nil − Value representing undefined." }, { "code": null, "e": 7503, "s": 7467, "text": "nil − Value representing undefined." }, { "code": null, "e": 7551, "s": 7503, "text": "__FILE__ − The name of the current source file." }, { "code": null, "e": 7599, "s": 7551, "text": "__FILE__ − The name of the current source file." }, { "code": null, "e": 7654, "s": 7599, "text": "__LINE__ − The current line number in the source file." }, { "code": null, "e": 7709, "s": 7654, "text": "__LINE__ − The current line number in the source file." }, { "code": null, "e": 7815, "s": 7709, "text": "The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals." }, { "code": null, "e": 8037, "s": 7815, "text": "Ruby supports integer numbers. An integer number can range from -230 to 230-1 or -262 to 262-1. Integers within this range are objects of class Fixnum and integers outside this range are stored in objects of class Bignum." }, { "code": null, "e": 8271, "s": 8037, "text": "You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string." }, { "code": null, "e": 8404, "s": 8271, "text": "You can also get the integer value, corresponding to an ASCII character or escape the sequence by preceding it with a question mark." }, { "code": null, "e": 8753, "s": 8404, "text": "123 # Fixnum decimal\n1_234 # Fixnum decimal with underline\n-500 # Negative Fixnum\n0377 # octal\n0xff # hexadecimal\n0b1011 # binary\n?a # character code for 'a'\n?\\n # code for a newline (0x0a)\n12345678901234567890 # Bignum" }, { "code": null, "e": 8832, "s": 8753, "text": "NOTE − Class and Objects are explained in a separate chapter of this tutorial." }, { "code": null, "e": 8989, "s": 8832, "text": "Ruby supports floating numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following −" }, { "code": null, "e": 9163, "s": 8989, "text": "123.4 # floating point value\n1.0e6 # scientific notation\n4E20 # dot not required\n4e+20 # sign before exponential" }, { "code": null, "e": 9413, "s": 9163, "text": "Ruby strings are simply sequences of 8-bit bytes and they are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings don't allow substitution and allow backslash notation only for \\\\ and \\'" }, { "code": null, "e": 9481, "s": 9413, "text": "#!/usr/bin/ruby -w\n\nputs 'escape using \"\\\\\"';\nputs 'That\\'s right';" }, { "code": null, "e": 9522, "s": 9481, "text": "This will produce the following result −" }, { "code": null, "e": 9553, "s": 9522, "text": "escape using \"\\\"\nThat's right\n" }, { "code": null, "e": 9690, "s": 9553, "text": "You can substitute the value of any Ruby expression into a string using the sequence #{ expr }. Here, expr could be any ruby expression." }, { "code": null, "e": 9753, "s": 9690, "text": "#!/usr/bin/ruby -w\n\nputs \"Multiplication Value : #{24*60*60}\";" }, { "code": null, "e": 9794, "s": 9753, "text": "This will produce the following result −" }, { "code": null, "e": 9824, "s": 9794, "text": "Multiplication Value : 86400\n" }, { "code": null, "e": 9889, "s": 9824, "text": "Following is the list of Backslash notations supported by Ruby −" }, { "code": null, "e": 9947, "s": 9889, "text": "For more detail on Ruby Strings, go through Ruby Strings." }, { "code": null, "e": 10097, "s": 9947, "text": "Literals of Ruby Array are created by placing a comma-separated series of object references between the square brackets. A trailing comma is ignored." }, { "code": null, "e": 10209, "s": 10097, "text": "#!/usr/bin/ruby\n\nary = [ \"fred\", 10, 3.14, \"This is a string\", \"last element\", ]\nary.each do |i|\n puts i\nend" }, { "code": null, "e": 10250, "s": 10209, "text": "This will produce the following result −" }, { "code": null, "e": 10294, "s": 10250, "text": "fred\n10\n3.14\nThis is a string\nlast element\n" }, { "code": null, "e": 10350, "s": 10294, "text": "For more detail on Ruby Arrays, go through Ruby Arrays." }, { "code": null, "e": 10533, "s": 10350, "text": "A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence => between the key and the value. A trailing comma is ignored." }, { "code": null, "e": 10682, "s": 10533, "text": "#!/usr/bin/ruby\n\nhsh = colors = { \"red\" => 0xf00, \"green\" => 0x0f0, \"blue\" => 0x00f }\nhsh.each do |key, value|\n print key, \" is \", value, \"\\n\"\nend" }, { "code": null, "e": 10723, "s": 10682, "text": "This will produce the following result −" }, { "code": null, "e": 10760, "s": 10723, "text": "red is 3840\ngreen is 240\nblue is 15\n" }, { "code": null, "e": 10816, "s": 10760, "text": "For more detail on Ruby Hashes, go through Ruby Hashes." }, { "code": null, "e": 10977, "s": 10816, "text": "A Range represents an interval which is a set of values with a start and an end. Ranges may be constructed using the s..e and s...e literals, or with Range.new." }, { "code": null, "e": 11163, "s": 10977, "text": "Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value. When used as an iterator, ranges return each value in the sequence." }, { "code": null, "e": 11274, "s": 11163, "text": "A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1...5) means it includes 1, 2, 3, 4 values." }, { "code": null, "e": 11334, "s": 11274, "text": "#!/usr/bin/ruby\n\n(10..15).each do |n| \n print n, ' ' \nend" }, { "code": null, "e": 11375, "s": 11334, "text": "This will produce the following result −" }, { "code": null, "e": 11394, "s": 11375, "text": "10 11 12 13 14 15\n" }, { "code": null, "e": 11450, "s": 11394, "text": "For more detail on Ruby Ranges, go through Ruby Ranges." }, { "code": null, "e": 11485, "s": 11450, "text": "\n 46 Lectures \n 9.5 hours \n" }, { "code": null, "e": 11513, "s": 11485, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11548, "s": 11513, "text": "\n 97 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11568, "s": 11548, "text": " Skillbakerystudios" }, { "code": null, "e": 11603, "s": 11568, "text": "\n 227 Lectures \n 40 hours \n" }, { "code": null, "e": 11613, "s": 11603, "text": " YouAccel" }, { "code": null, "e": 11647, "s": 11613, "text": "\n 19 Lectures \n 10 hours \n" }, { "code": null, "e": 11665, "s": 11647, "text": " Programming Line" }, { "code": null, "e": 11698, "s": 11665, "text": "\n 51 Lectures \n 5 hours \n" }, { "code": null, "e": 11721, "s": 11698, "text": " Stone River ELearning" }, { "code": null, "e": 11756, "s": 11721, "text": "\n 39 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11779, "s": 11756, "text": " Stone River ELearning" }, { "code": null, "e": 11786, "s": 11779, "text": " Print" }, { "code": null, "e": 11797, "s": 11786, "text": " Add Notes" } ]
Python - Rename column names by index in a Pandas DataFrame without using rename()
We can easily rename a column by index i.e. without using rename(). Import the required library − import pandas as pd Create a DataFrame with 3 columns − dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130] } ) Let us now rename all the columns using columns.values[0[ by setting the index of the column to be changed in the square brackets − dataFrame.columns.values[0] = "Car Names" dataFrame.columns.values[1] = "Registration Cost" dataFrame.columns.values[2] = "Units_Sold" Following is the code − import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130] } ) print"DataFrame ...\n",dataFrame # Renaming columns name dataFrame.columns.values[0] = "Car Names" dataFrame.columns.values[1] = "Registration Cost" dataFrame.columns.values[2] = "Units_Sold" print"\nUpdated DataFrame with new column names...\n",dataFrame This will produce the following output − DataFrame ... Car Reg_Price Units 0 BMW 7000 90 1 Lexus 1500 120 2 Tesla 5000 100 3 Mustang 8000 150 4 Mercedes 9000 200 5 Jaguar 6000 130 Updated DataFrame with new column names... Car Names Registration Cost Units_Sold 0 BMW 7000 90 1 Lexus 1500 120 2 Tesla 5000 100 3 Mustang 8000 150 4 Mercedes 9000 200 5 Jaguar 6000 130
[ { "code": null, "e": 1160, "s": 1062, "text": "We can easily rename a column by index i.e. without using rename(). Import the required library −" }, { "code": null, "e": 1180, "s": 1160, "text": "import pandas as pd" }, { "code": null, "e": 1216, "s": 1180, "text": "Create a DataFrame with 3 columns −" }, { "code": null, "e": 1415, "s": 1216, "text": "dataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units\": [90, 120, 100, 150, 200, 130]\n }\n)" }, { "code": null, "e": 1547, "s": 1415, "text": "Let us now rename all the columns using columns.values[0[ by setting the index of the column to be changed in the square brackets −" }, { "code": null, "e": 1682, "s": 1547, "text": "dataFrame.columns.values[0] = \"Car Names\"\ndataFrame.columns.values[1] = \"Registration Cost\"\ndataFrame.columns.values[2] = \"Units_Sold\"" }, { "code": null, "e": 1706, "s": 1682, "text": "Following is the code −" }, { "code": null, "e": 2204, "s": 1706, "text": "import pandas as pd\n\n# Create DataFrame\ndataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units\": [90, 120, 100, 150, 200, 130]\n }\n)\n\nprint\"DataFrame ...\\n\",dataFrame\n\n# Renaming columns name\ndataFrame.columns.values[0] = \"Car Names\"\ndataFrame.columns.values[1] = \"Registration Cost\"\ndataFrame.columns.values[2] = \"Units_Sold\"\n\nprint\"\\nUpdated DataFrame with new column names...\\n\",dataFrame" }, { "code": null, "e": 2245, "s": 2204, "text": "This will produce the following output −" }, { "code": null, "e": 2837, "s": 2245, "text": "DataFrame ...\n Car Reg_Price Units\n0 BMW 7000 90\n1 Lexus 1500 120\n2 Tesla 5000 100\n3 Mustang 8000 150\n4 Mercedes 9000 200\n5 Jaguar 6000 130\n\nUpdated DataFrame with new column names...\n Car Names Registration Cost Units_Sold\n0 BMW 7000 90\n1 Lexus 1500 120\n2 Tesla 5000 100\n3 Mustang 8000 150\n4 Mercedes 9000 200\n5 Jaguar 6000 130" } ]
Define ng-if, ng-show and ng-hide - GeeksforGeeks
24 Jun, 2020 In this article, we will be explaining about ng-if, ng-show and ng-hide directive. ng-if Directive:The ng-if Directive in AngularJS is used to remove or recreate a portion of HTML element based on an expression.If the expression inside it is false then the element is completely removed from the DOM.if the expression is true then the element will be added to the DOM.Syntax:<element ng-if="expression"></element> Example:In following Example, When there is any text in input element then div content will be shown otherwise it will be hidden.<!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script><body ng-app=""> Enter Text:<input type="text" ng-model="textcheck"> <div ng-if="textcheck"><h1 style="color:green">GeeksforGeeks</h1></div> </body></html>Output:When there is any text in the input field, Heading div is added to HTML DOM and is shown but when the input field is empty, div is removed and is not shown. The ng-if Directive in AngularJS is used to remove or recreate a portion of HTML element based on an expression. If the expression inside it is false then the element is completely removed from the DOM. if the expression is true then the element will be added to the DOM. Syntax: <element ng-if="expression"></element> Example: In following Example, When there is any text in input element then div content will be shown otherwise it will be hidden. <!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script><body ng-app=""> Enter Text:<input type="text" ng-model="textcheck"> <div ng-if="textcheck"><h1 style="color:green">GeeksforGeeks</h1></div> </body></html> Output: When there is any text in the input field, Heading div is added to HTML DOM and is shown but when the input field is empty, div is removed and is not shown. ng-show Directive: The ng-show Directive in AngluarJS is used to show or hide the specified HTML element.If given expression in ng-show attribute is true then the HTML element will display otherwise it hide the HTML element.Syntax:<element ng-show="expression"> </element> Example:In the following Example, When their checkbox is selected then div content will be shown otherwise it will be hidden.<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script><body ng-app=""> <input type="checkbox" ng-model="check"> <div ng-show="check"> <h1 style="color:green">GeeksforGeeks</h1></div> </body></html>Output:When the Check box is selected, the HTML attribute div are set to show, otherwise hide them. If given expression in ng-show attribute is true then the HTML element will display otherwise it hide the HTML element. Syntax: <element ng-show="expression"> </element> Example: In the following Example, When their checkbox is selected then div content will be shown otherwise it will be hidden. <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script><body ng-app=""> <input type="checkbox" ng-model="check"> <div ng-show="check"> <h1 style="color:green">GeeksforGeeks</h1></div> </body></html> Output: When the Check box is selected, the HTML attribute div are set to show, otherwise hide them. ng-hide Directive: The ng-hide Directive in AngluarJS is used to show or hide the specified HTML element.If the expression given in the ng-hide attribute is true than the HTML elements hide.ng-hide is also a predefined CSS class in AngularJS, and sets the element’s display to none.Syntax: <element ng-hide="expression"> </element> Example:In this example, If checkbox is selected this means ng-hide attribute is true and the HTML elements will hide.<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script><body ng-app=""> Show DIV:<input type="checkbox" ng-model="check"> <div ng-hide="check"> <h1 style="color:green">GeeksforGeeks</h1></div> </body></html>Output:When the Check box is selected, the HTML attribute div are set to hide, otherwise show them. If the expression given in the ng-hide attribute is true than the HTML elements hide. ng-hide is also a predefined CSS class in AngularJS, and sets the element’s display to none. Syntax: <element ng-hide="expression"> </element> Example: In this example, If checkbox is selected this means ng-hide attribute is true and the HTML elements will hide. <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script><body ng-app=""> Show DIV:<input type="checkbox" ng-model="check"> <div ng-hide="check"> <h1 style="color:green">GeeksforGeeks</h1></div> </body></html> Output: When the Check box is selected, the HTML attribute div are set to hide, otherwise show them. Basic Difference between ng-if, ng-show and ng-hide Hence, there is a considerable difference between ng-if, ng-show and ng-hide directive which makes them different for their usages . AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Auth Guards in Angular 9/10/11 How to bundle an Angular app for production? What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component How to set focus on input field automatically on page load in AngularJS ? Top 10 Front End Developer Skills That You Need 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": 24176, "s": 24148, "text": "\n24 Jun, 2020" }, { "code": null, "e": 24259, "s": 24176, "text": "In this article, we will be explaining about ng-if, ng-show and ng-hide directive." }, { "code": null, "e": 25154, "s": 24259, "text": "ng-if Directive:The ng-if Directive in AngularJS is used to remove or recreate a portion of HTML element based on an expression.If the expression inside it is false then the element is completely removed from the DOM.if the expression is true then the element will be added to the DOM.Syntax:<element ng-if=\"expression\"></element>\nExample:In following Example, When there is any text in input element then div content will be shown otherwise it will be hidden.<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script><body ng-app=\"\"> Enter Text:<input type=\"text\" ng-model=\"textcheck\"> <div ng-if=\"textcheck\"><h1 style=\"color:green\">GeeksforGeeks</h1></div> </body></html>Output:When there is any text in the input field, Heading div is added to HTML DOM and is shown but when the input field is empty, div is removed and is not shown." }, { "code": null, "e": 25267, "s": 25154, "text": "The ng-if Directive in AngularJS is used to remove or recreate a portion of HTML element based on an expression." }, { "code": null, "e": 25357, "s": 25267, "text": "If the expression inside it is false then the element is completely removed from the DOM." }, { "code": null, "e": 25426, "s": 25357, "text": "if the expression is true then the element will be added to the DOM." }, { "code": null, "e": 25434, "s": 25426, "text": "Syntax:" }, { "code": null, "e": 25474, "s": 25434, "text": "<element ng-if=\"expression\"></element>\n" }, { "code": null, "e": 25483, "s": 25474, "text": "Example:" }, { "code": null, "e": 25605, "s": 25483, "text": "In following Example, When there is any text in input element then div content will be shown otherwise it will be hidden." }, { "code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script><body ng-app=\"\"> Enter Text:<input type=\"text\" ng-model=\"textcheck\"> <div ng-if=\"textcheck\"><h1 style=\"color:green\">GeeksforGeeks</h1></div> </body></html>", "e": 25877, "s": 25605, "text": null }, { "code": null, "e": 25885, "s": 25877, "text": "Output:" }, { "code": null, "e": 26042, "s": 25885, "text": "When there is any text in the input field, Heading div is added to HTML DOM and is shown but when the input field is empty, div is removed and is not shown." }, { "code": null, "e": 26810, "s": 26042, "text": "ng-show Directive: The ng-show Directive in AngluarJS is used to show or hide the specified HTML element.If given expression in ng-show attribute is true then the HTML element will display otherwise it hide the HTML element.Syntax:<element ng-show=\"expression\"> </element> Example:In the following Example, When their checkbox is selected then div content will be shown otherwise it will be hidden.<!DOCTYPE html> <html> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script><body ng-app=\"\"> <input type=\"checkbox\" ng-model=\"check\"> <div ng-show=\"check\"> <h1 style=\"color:green\">GeeksforGeeks</h1></div> </body></html>Output:When the Check box is selected, the HTML attribute div are set to show, otherwise hide them." }, { "code": null, "e": 26930, "s": 26810, "text": "If given expression in ng-show attribute is true then the HTML element will display otherwise it hide the HTML element." }, { "code": null, "e": 26938, "s": 26930, "text": "Syntax:" }, { "code": null, "e": 26981, "s": 26938, "text": "<element ng-show=\"expression\"> </element> " }, { "code": null, "e": 26990, "s": 26981, "text": "Example:" }, { "code": null, "e": 27108, "s": 26990, "text": "In the following Example, When their checkbox is selected then div content will be shown otherwise it will be hidden." }, { "code": "<!DOCTYPE html> <html> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script><body ng-app=\"\"> <input type=\"checkbox\" ng-model=\"check\"> <div ng-show=\"check\"> <h1 style=\"color:green\">GeeksforGeeks</h1></div> </body></html>", "e": 27379, "s": 27108, "text": null }, { "code": null, "e": 27387, "s": 27379, "text": "Output:" }, { "code": null, "e": 27480, "s": 27387, "text": "When the Check box is selected, the HTML attribute div are set to show, otherwise hide them." }, { "code": null, "e": 28314, "s": 27480, "text": "ng-hide Directive: The ng-hide Directive in AngluarJS is used to show or hide the specified HTML element.If the expression given in the ng-hide attribute is true than the HTML elements hide.ng-hide is also a predefined CSS class in AngularJS, and sets the element’s display to none.Syntax: <element ng-hide=\"expression\"> </element> \nExample:In this example, If checkbox is selected this means ng-hide attribute is true and the HTML elements will hide.<!DOCTYPE html> <html> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script><body ng-app=\"\"> Show DIV:<input type=\"checkbox\" ng-model=\"check\"> <div ng-hide=\"check\"> <h1 style=\"color:green\">GeeksforGeeks</h1></div> </body></html>Output:When the Check box is selected, the HTML attribute div are set to hide, otherwise show them." }, { "code": null, "e": 28400, "s": 28314, "text": "If the expression given in the ng-hide attribute is true than the HTML elements hide." }, { "code": null, "e": 28493, "s": 28400, "text": "ng-hide is also a predefined CSS class in AngularJS, and sets the element’s display to none." }, { "code": null, "e": 28501, "s": 28493, "text": "Syntax:" }, { "code": null, "e": 28546, "s": 28501, "text": " <element ng-hide=\"expression\"> </element> \n" }, { "code": null, "e": 28555, "s": 28546, "text": "Example:" }, { "code": null, "e": 28666, "s": 28555, "text": "In this example, If checkbox is selected this means ng-hide attribute is true and the HTML elements will hide." }, { "code": "<!DOCTYPE html> <html> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script><body ng-app=\"\"> Show DIV:<input type=\"checkbox\" ng-model=\"check\"> <div ng-hide=\"check\"> <h1 style=\"color:green\">GeeksforGeeks</h1></div> </body></html>", "e": 28950, "s": 28666, "text": null }, { "code": null, "e": 28958, "s": 28950, "text": "Output:" }, { "code": null, "e": 29051, "s": 28958, "text": "When the Check box is selected, the HTML attribute div are set to hide, otherwise show them." }, { "code": null, "e": 29103, "s": 29051, "text": "Basic Difference between ng-if, ng-show and ng-hide" }, { "code": null, "e": 29236, "s": 29103, "text": "Hence, there is a considerable difference between ng-if, ng-show and ng-hide directive which makes them different for their usages ." }, { "code": null, "e": 29251, "s": 29236, "text": "AngularJS-Misc" }, { "code": null, "e": 29258, "s": 29251, "text": "Picked" }, { "code": null, "e": 29268, "s": 29258, "text": "AngularJS" }, { "code": null, "e": 29285, "s": 29268, "text": "Web Technologies" }, { "code": null, "e": 29383, "s": 29285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29392, "s": 29383, "text": "Comments" }, { "code": null, "e": 29405, "s": 29392, "text": "Old Comments" }, { "code": null, "e": 29436, "s": 29405, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 29481, "s": 29436, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 29523, "s": 29481, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 29558, "s": 29523, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29632, "s": 29558, "text": "How to set focus on input field automatically on page load in AngularJS ?" }, { "code": null, "e": 29688, "s": 29632, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29721, "s": 29688, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29783, "s": 29721, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29826, "s": 29783, "text": "How to fetch data from an API in ReactJS ?" } ]
Comb Sort
The basic idea of comb sort and the bubble sort is same. In other words, comb sort is an improvement on the bubble sort. In the bubble sorting technique, the items are compared with the next item in each phase. But for the comb sort, the items are sorted in a specific gap. After completing each phase, the gap is decreased. The decreasing factor or the shrink factor for this sort is 1.3. It means that after completing each phase the gap is divided by 1.3. Time Complexity: O(n log n) for the best case. O(n^2/2^p) (p is a number of increment) for average case and O(n^2) for the worst case. Space Complexity: O(1) Input: A list of unsorted data: 108 96 23 74 12 56 85 42 13 47 Output: Array before Sorting: 108 96 23 74 12 56 85 42 13 47 Array after Sorting: 12 13 23 42 47 56 74 85 96 108 CombSort(array, size) Input − An array of data, and the total number in the array Output − The sorted Array Begin gap := size flag := true while the gap ≠ 1 OR flag = true do gap = floor(gap/1.3) //the the floor value after division if gap < 1 then gap := 1 flag = false for i := 0 to size – gap -1 do if array[i] > array[i+gap] then swap array[i] with array[i+gap] flag = true; done done End #include<iostream> #include<algorithm> using namespace std; void display(int *array, int size) { for(int i = 0; i<size; i++) cout << array[i] << " "; cout << endl; } void combSort(int *array, int size) { int gap = size; //initialize gap size with size of array bool flag = true; while(gap != 1 || flag == true) { gap = (gap*10)/13; //minimize gap by shrink factor if(gap<1) gap = 1; flag = false; for(int i = 0; i<size-gap; i++) { //compare elements with gap if(array[i] > array[i+gap]) { swap(array[i], array[i+gap]); flag = true; } } } } int main() { int n; cout << "Enter the number of elements: "; cin >> n; int arr[n]; //create an array with given number of elements cout << "Enter elements:" << endl; for(int i = 0; i<n; i++) { cin >> arr[i]; } cout << "Array before Sorting: "; display(arr, n); combSort(arr, n); cout << "Array after Sorting: "; display(arr, n); } Enter the number of elements: 10 Enter elements: 108 96 23 74 12 56 85 42 13 47 Array before Sorting: 108 96 23 74 12 56 85 42 13 47 Array after Sorting: 12 13 23 42 47 56 74 85 96 108
[ { "code": null, "e": 1521, "s": 1062, "text": "The basic idea of comb sort and the bubble sort is same. In other words, comb sort is an improvement on the bubble sort. In the bubble sorting technique, the items are compared with the next item in each phase. But for the comb sort, the items are sorted in a specific gap. After completing each phase, the gap is decreased. The decreasing factor or the shrink factor for this sort is 1.3. It means that after completing each phase the gap is divided by 1.3." }, { "code": null, "e": 1656, "s": 1521, "text": "Time Complexity: O(n log n) for the best case. O(n^2/2^p) (p is a number of increment) for average case and O(n^2) for the worst case." }, { "code": null, "e": 1679, "s": 1656, "text": "Space Complexity: O(1)" }, { "code": null, "e": 1855, "s": 1679, "text": "Input:\nA list of unsorted data: 108 96 23 74 12 56 85 42 13 47\nOutput:\nArray before Sorting: 108 96 23 74 12 56 85 42 13 47\nArray after Sorting: 12 13 23 42 47 56 74 85 96 108" }, { "code": null, "e": 1877, "s": 1855, "text": "CombSort(array, size)" }, { "code": null, "e": 1937, "s": 1877, "text": "Input − An array of data, and the total number in the array" }, { "code": null, "e": 1963, "s": 1937, "text": "Output − The sorted Array" }, { "code": null, "e": 2334, "s": 1963, "text": "Begin\n gap := size\n flag := true\n while the gap ≠ 1 OR flag = true do\n gap = floor(gap/1.3) //the the floor value after division\n if gap < 1 then\n gap := 1\n flag = false\n\n for i := 0 to size – gap -1 do\n if array[i] > array[i+gap] then\n swap array[i] with array[i+gap]\n flag = true;\n done\n done\nEnd" }, { "code": null, "e": 3360, "s": 2334, "text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\n\nvoid display(int *array, int size) {\n for(int i = 0; i<size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\n\nvoid combSort(int *array, int size) {\n int gap = size; //initialize gap size with size of array\n bool flag = true;\n\n while(gap != 1 || flag == true) {\n gap = (gap*10)/13; //minimize gap by shrink factor\n if(gap<1)\n gap = 1;\n flag = false;\n\n for(int i = 0; i<size-gap; i++) { //compare elements with gap\n if(array[i] > array[i+gap]) {\n swap(array[i], array[i+gap]);\n flag = true;\n }\n }\n }\n}\n\nint main() {\n int n;\n cout << \"Enter the number of elements: \";\n cin >> n;\n int arr[n]; //create an array with given number of elements\n cout << \"Enter elements:\" << endl;\n\n for(int i = 0; i<n; i++) {\n cin >> arr[i];\n }\n\n cout << \"Array before Sorting: \";\n display(arr, n);\n combSort(arr, n);\n cout << \"Array after Sorting: \";\n display(arr, n);\n}" }, { "code": null, "e": 3545, "s": 3360, "text": "Enter the number of elements: 10\nEnter elements:\n108 96 23 74 12 56 85 42 13 47\nArray before Sorting: 108 96 23 74 12 56 85 42 13 47\nArray after Sorting: 12 13 23 42 47 56 74 85 96 108" } ]
How to create a custom progress bar component in React.js ?
30 Jun, 2021 In this article, We will make a custom reusable Progress bar component using React.js Prerequisites: Basic Knowledge of React Basic Knowledge of HTML/CSS Inline styling in React The <Progressbar /> component should do the following: Indicates the progress visually to the user via the colored bar.Shows the percentage numerically as a %Props that allow you to change the height, width, and background color of the progress bar . Indicates the progress visually to the user via the colored bar. Shows the percentage numerically as a % Props that allow you to change the height, width, and background color of the progress bar . Basically, the progress bar consists of a parent div, which represents the whole progress bar, and a child div in which the completed part of the bar along with the span will show the completed percentage number. Props: bgcolor: It will change the background color of the progress bar . progress: It will have value between 1 to 100 . height: It is used to change the height of the progress bar . Creating React Application And Installing Module: Step 1: Create a React application using the following command npx create-react-app progress_bar Step 2: After creating your project folder i.e. folder name, move to it using the following command: cd Progress_bar Step 3: Add a Progress_bar.js file in the Component folder and then import the Progressbar component in App.js Project Structure: It will look like the following. Folder structure Step 4: Now let create the Progress bar in Progress_bar.js Progress_bar.js import React from 'react' const Progress_bar = ({bgcolor,progress,height}) => { const Parentdiv = { height: height, width: '100%', backgroundColor: 'whitesmoke', borderRadius: 40, margin: 50 } const Childdiv = { height: '100%', width: `${progress}%`, backgroundColor: bgcolor, borderRadius:40, textAlign: 'right' } const progresstext = { padding: 10, color: 'black', fontWeight: 900 } return ( <div style={Parentdiv}> <div style={Childdiv}> <span style={progresstext}>{`${progress}%`}</span> </div> </div> )} export default Progress_bar; Step 5: Lets Render the Progress bar component by importing the Progress_bar component into. App.js import './App.css';import Progressbar from './Component/Progress_bar'; function App() { return ( <div className="App"> <h3 className="heading">Progress Bar</h3> <Progressbar bgcolor="orange" progress='30' height={30} /> <Progressbar bgcolor="red" progress='60' height={30} /> <Progressbar bgcolor="#99ff66" progress='50' height={30} /> <Progressbar bgcolor="#ff00ff" progress='85' height={30} /> <Progressbar bgcolor="#99ccff" progress='95' height={30} /> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Progress bar in react React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jun, 2021" }, { "code": null, "e": 141, "s": 54, "text": "In this article, We will make a custom reusable Progress bar component using React.js " }, { "code": null, "e": 157, "s": 141, "text": "Prerequisites: " }, { "code": null, "e": 182, "s": 157, "text": "Basic Knowledge of React" }, { "code": null, "e": 210, "s": 182, "text": "Basic Knowledge of HTML/CSS" }, { "code": null, "e": 234, "s": 210, "text": "Inline styling in React" }, { "code": null, "e": 289, "s": 234, "text": "The <Progressbar /> component should do the following:" }, { "code": null, "e": 485, "s": 289, "text": "Indicates the progress visually to the user via the colored bar.Shows the percentage numerically as a %Props that allow you to change the height, width, and background color of the progress bar ." }, { "code": null, "e": 550, "s": 485, "text": "Indicates the progress visually to the user via the colored bar." }, { "code": null, "e": 590, "s": 550, "text": "Shows the percentage numerically as a %" }, { "code": null, "e": 683, "s": 590, "text": "Props that allow you to change the height, width, and background color of the progress bar ." }, { "code": null, "e": 896, "s": 683, "text": "Basically, the progress bar consists of a parent div, which represents the whole progress bar, and a child div in which the completed part of the bar along with the span will show the completed percentage number." }, { "code": null, "e": 905, "s": 898, "text": "Props:" }, { "code": null, "e": 972, "s": 905, "text": "bgcolor: It will change the background color of the progress bar ." }, { "code": null, "e": 1021, "s": 972, "text": "progress: It will have value between 1 to 100 ." }, { "code": null, "e": 1083, "s": 1021, "text": "height: It is used to change the height of the progress bar ." }, { "code": null, "e": 1133, "s": 1083, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 1197, "s": 1133, "text": "Step 1: Create a React application using the following command " }, { "code": null, "e": 1231, "s": 1197, "text": "npx create-react-app progress_bar" }, { "code": null, "e": 1332, "s": 1231, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:" }, { "code": null, "e": 1348, "s": 1332, "text": "cd Progress_bar" }, { "code": null, "e": 1462, "s": 1348, "text": "Step 3: Add a Progress_bar.js file in the Component folder and then import the Progressbar component in App.js" }, { "code": null, "e": 1514, "s": 1462, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1531, "s": 1514, "text": "Folder structure" }, { "code": null, "e": 1592, "s": 1531, "text": "Step 4: Now let create the Progress bar in Progress_bar.js " }, { "code": null, "e": 1608, "s": 1592, "text": "Progress_bar.js" }, { "code": "import React from 'react' const Progress_bar = ({bgcolor,progress,height}) => { const Parentdiv = { height: height, width: '100%', backgroundColor: 'whitesmoke', borderRadius: 40, margin: 50 } const Childdiv = { height: '100%', width: `${progress}%`, backgroundColor: bgcolor, borderRadius:40, textAlign: 'right' } const progresstext = { padding: 10, color: 'black', fontWeight: 900 } return ( <div style={Parentdiv}> <div style={Childdiv}> <span style={progresstext}>{`${progress}%`}</span> </div> </div> )} export default Progress_bar;", "e": 2320, "s": 1608, "text": null }, { "code": null, "e": 2413, "s": 2320, "text": "Step 5: Lets Render the Progress bar component by importing the Progress_bar component into." }, { "code": null, "e": 2420, "s": 2413, "text": "App.js" }, { "code": "import './App.css';import Progressbar from './Component/Progress_bar'; function App() { return ( <div className=\"App\"> <h3 className=\"heading\">Progress Bar</h3> <Progressbar bgcolor=\"orange\" progress='30' height={30} /> <Progressbar bgcolor=\"red\" progress='60' height={30} /> <Progressbar bgcolor=\"#99ff66\" progress='50' height={30} /> <Progressbar bgcolor=\"#ff00ff\" progress='85' height={30} /> <Progressbar bgcolor=\"#99ccff\" progress='95' height={30} /> </div> );} export default App;", "e": 2959, "s": 2420, "text": null }, { "code": null, "e": 3072, "s": 2959, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 3082, "s": 3072, "text": "npm start" }, { "code": null, "e": 3181, "s": 3082, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 3203, "s": 3181, "text": "Progress bar in react" }, { "code": null, "e": 3219, "s": 3203, "text": "React-Questions" }, { "code": null, "e": 3227, "s": 3219, "text": "ReactJS" }, { "code": null, "e": 3244, "s": 3227, "text": "Web Technologies" } ]
Print the first and last character of each word in a String
06 May, 2021 Given a string, the task is to print the first and last character of each word in a string.Examples: Input: Geeks for geeks Output: Gs fr gs Input: Computer applications Output: Cr as Approach Run a loop from the first letter to the last letter.Print the first and last letter of the string.If there is a space in the string then print the character that lies just before space and just after space. Run a loop from the first letter to the last letter. Print the first and last letter of the string. If there is a space in the string then print the character that lies just before space and just after space. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // CPP program to print// the first and last character// of each word in a String'#include<bits/stdc++.h>using namespace std; // Function to print the first// and last character of each word.void FirstAndLast(string str){ int i; for (i = 0; i < str.length(); i++) { // If it is the first word // of the string then print it. if (i == 0) cout<<str[i]; // If it is the last word of the string // then also print it. if (i == str.length() - 1) cout<<str[i]; // If there is a space // print the successor and predecessor // to space. if (str[i] == ' ') { cout<<str[i-1]<<" "<<str[i+1]; } }} // Driver codeint main(){ string str = "Geeks for Geeks"; FirstAndLast(str);} // This code is contributed by// Surendra_Gangwar // Java program to print// the first and last character// of each word in a String class GFG { // Function to print the first // and last character of each word. static void FirstAndLast(String str) { int i; for (i = 0; i < str.length(); i++) { // If it is the first word // of the string then print it. if (i == 0) System.out.print(str.charAt(i)); // If it is the last word of the string // then also print it. if (i == str.length() - 1) System.out.print(str.charAt(i)); // If there is a space // print the successor and predecessor // to space. if (str.charAt(i) == ' ') { System.out.print(str.charAt(i - 1) + " " + str.charAt(i + 1)); } } } // Driver code public static void main(String args[]) { String str = "Geeks for Geeks"; FirstAndLast(str); }} # Python3 program to print# the first and last character# of each word in a String' # Function to print the first# and last character of each word.def FirstAndLast(string): for i in range(len(string)): # If it is the first word # of the string then print it. if i == 0: print(string[i], end = "") # If it is the last word of the string # then also print it. if i == len(string) - 1: print(string[i], end = "") # If there is a space # print the successor and predecessor # to space. if string[i] == " ": print(string[i - 1], string[i + 1], end = "") # Driver codeif __name__ == "__main__": string = "Geeks for Geeks" FirstAndLast(string) # This code is contributed by# sanjeev2552 // C# program to print// the first and last character// of each word in a Stringusing System; class GFG{ // Function to print the first // and last character of each word. static void FirstAndLast(string str) { int i; for (i = 0; i < str.Length; i++) { // If it is the first word // of the string then print it. if (i == 0) Console.Write(str[i]); // If it is the last word of the string // then also print it. if (i == str.Length - 1) Console.Write(str[i]); // If there is a space // print the successor and predecessor // to space. if (str[i] == ' ') { Console.Write(str[i - 1] + " " + str[i + 1]); } } } // Driver code public static void Main() { string str = "Geeks for Geeks"; FirstAndLast(str); }} // This code is contributed by Ryuga <script> // JavaScript program to print // the first and last character // of each word in a String' // Function to print the first // and last character of each word. function FirstAndLast(str) { for (var i = 0; i < str.length; i++) { // If it is the first word // of the string then print it. if (i == 0) document.write(str[i]); // If it is the last word of the string // then also print it. if (i == str.length - 1) document.write(str[i]); // If there is a space // print the successor and predecessor // to space. if (str[i] === " ") { document.write(str[i - 1] + " " + str[i + 1]); } } } // Driver code var str = "Geeks for Geeks"; FirstAndLast(str); </script> Gs fr Gs ankthon SURENDRA_GANGWAR sanjeev2552 rdtank School Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 May, 2021" }, { "code": null, "e": 156, "s": 53, "text": "Given a string, the task is to print the first and last character of each word in a string.Examples: " }, { "code": null, "e": 240, "s": 156, "text": "Input: Geeks for geeks\nOutput: Gs fr gs\n\nInput: Computer applications\nOutput: Cr as" }, { "code": null, "e": 253, "s": 242, "text": "Approach " }, { "code": null, "e": 460, "s": 253, "text": "Run a loop from the first letter to the last letter.Print the first and last letter of the string.If there is a space in the string then print the character that lies just before space and just after space." }, { "code": null, "e": 513, "s": 460, "text": "Run a loop from the first letter to the last letter." }, { "code": null, "e": 560, "s": 513, "text": "Print the first and last letter of the string." }, { "code": null, "e": 669, "s": 560, "text": "If there is a space in the string then print the character that lies just before space and just after space." }, { "code": null, "e": 722, "s": 669, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 726, "s": 722, "text": "C++" }, { "code": null, "e": 731, "s": 726, "text": "Java" }, { "code": null, "e": 739, "s": 731, "text": "Python3" }, { "code": null, "e": 742, "s": 739, "text": "C#" }, { "code": null, "e": 753, "s": 742, "text": "Javascript" }, { "code": "// CPP program to print// the first and last character// of each word in a String'#include<bits/stdc++.h>using namespace std; // Function to print the first// and last character of each word.void FirstAndLast(string str){ int i; for (i = 0; i < str.length(); i++) { // If it is the first word // of the string then print it. if (i == 0) cout<<str[i]; // If it is the last word of the string // then also print it. if (i == str.length() - 1) cout<<str[i]; // If there is a space // print the successor and predecessor // to space. if (str[i] == ' ') { cout<<str[i-1]<<\" \"<<str[i+1]; } }} // Driver codeint main(){ string str = \"Geeks for Geeks\"; FirstAndLast(str);} // This code is contributed by// Surendra_Gangwar", "e": 1610, "s": 753, "text": null }, { "code": "// Java program to print// the first and last character// of each word in a String class GFG { // Function to print the first // and last character of each word. static void FirstAndLast(String str) { int i; for (i = 0; i < str.length(); i++) { // If it is the first word // of the string then print it. if (i == 0) System.out.print(str.charAt(i)); // If it is the last word of the string // then also print it. if (i == str.length() - 1) System.out.print(str.charAt(i)); // If there is a space // print the successor and predecessor // to space. if (str.charAt(i) == ' ') { System.out.print(str.charAt(i - 1) + \" \" + str.charAt(i + 1)); } } } // Driver code public static void main(String args[]) { String str = \"Geeks for Geeks\"; FirstAndLast(str); }}", "e": 2662, "s": 1610, "text": null }, { "code": "# Python3 program to print# the first and last character# of each word in a String' # Function to print the first# and last character of each word.def FirstAndLast(string): for i in range(len(string)): # If it is the first word # of the string then print it. if i == 0: print(string[i], end = \"\") # If it is the last word of the string # then also print it. if i == len(string) - 1: print(string[i], end = \"\") # If there is a space # print the successor and predecessor # to space. if string[i] == \" \": print(string[i - 1], string[i + 1], end = \"\") # Driver codeif __name__ == \"__main__\": string = \"Geeks for Geeks\" FirstAndLast(string) # This code is contributed by# sanjeev2552", "e": 3474, "s": 2662, "text": null }, { "code": "// C# program to print// the first and last character// of each word in a Stringusing System; class GFG{ // Function to print the first // and last character of each word. static void FirstAndLast(string str) { int i; for (i = 0; i < str.Length; i++) { // If it is the first word // of the string then print it. if (i == 0) Console.Write(str[i]); // If it is the last word of the string // then also print it. if (i == str.Length - 1) Console.Write(str[i]); // If there is a space // print the successor and predecessor // to space. if (str[i] == ' ') { Console.Write(str[i - 1] + \" \" + str[i + 1]); } } } // Driver code public static void Main() { string str = \"Geeks for Geeks\"; FirstAndLast(str); }} // This code is contributed by Ryuga", "e": 4528, "s": 3474, "text": null }, { "code": "<script> // JavaScript program to print // the first and last character // of each word in a String' // Function to print the first // and last character of each word. function FirstAndLast(str) { for (var i = 0; i < str.length; i++) { // If it is the first word // of the string then print it. if (i == 0) document.write(str[i]); // If it is the last word of the string // then also print it. if (i == str.length - 1) document.write(str[i]); // If there is a space // print the successor and predecessor // to space. if (str[i] === \" \") { document.write(str[i - 1] + \" \" + str[i + 1]); } } } // Driver code var str = \"Geeks for Geeks\"; FirstAndLast(str); </script>", "e": 5416, "s": 4528, "text": null }, { "code": null, "e": 5425, "s": 5416, "text": "Gs fr Gs" }, { "code": null, "e": 5435, "s": 5427, "text": "ankthon" }, { "code": null, "e": 5452, "s": 5435, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5464, "s": 5452, "text": "sanjeev2552" }, { "code": null, "e": 5471, "s": 5464, "text": "rdtank" }, { "code": null, "e": 5490, "s": 5471, "text": "School Programming" }, { "code": null, "e": 5498, "s": 5490, "text": "Strings" }, { "code": null, "e": 5506, "s": 5498, "text": "Strings" } ]